text
stringlengths
10
2.61M
module Errors #class ExceptionType < StandardError; end Argument = Class.new(StandardError) end # This is an example, so you can change as you like class Sea attr_accessor :x,:y def initialize(m, n) @x = m.to_i @y = n.to_i raise Errors::Argument unless @x > 2 && @y > 2 set_islands_at_random end def set_islands_at_random @array = Array.new(@y) { Array.new(@x) {create_island}} end def create_island island = rand(3) island % 2 end def print_array return nil if @array.nil? @array.each {|row| puts row.join(' ')} end def count_island all_island = [] @array.flatten.each_with_index{|island,index| all_island.push(index) if island == 1 } check_island(all_island) end def check_island(all_island) island_group = [] all_island.each {|index| island_group.push(group_island(index,[],all_island)) unless check_group_island(index,island_group) } island_group.length end def check_group_island(index, array) return false unless array && array.length > 0 array.each {|sub| return true if sub.include?(index) } false end def group_island(index,group_island_array,all_island) group_island_array.push(index) get_island_around(index).each{|island| group_island_array = find_sub_island!(island,group_island_array,all_island) } group_island_array end def get_island_around(index) top ,left, right, bot = index-@x, index -1, index +1, index+@x left =-1 if index % @x == 0 right =-1 if index % @x == @x-1 [top,left,right,bot] end def find_sub_island!(index, group_island_array,all_island_array) if all_island_array.include?(index) && !group_island_array.include?(index) group_island_array = group_island(index,group_island_array,all_island_array) end group_island_array end end @sea =Sea.new(4,3) (1..5).each do |i| puts "Test #{i}" @sea.set_islands_at_random @sea.print_array puts "Number of island : #{@sea.count_island.to_s}" puts ">>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<" end
require 'rails_helper' require 'rake' describe "daily_tasks namespace" do before(:each) do Rake.application.rake_require "tasks/daily_tasks" Rake::Task.define_task(:environment) end describe "take_snapshot task" do let :run_rake_task do Rake::Task["daily_tasks:take_snapshot"].reenable Rake.application.invoke_task "daily_tasks:take_snapshot" end it "should take a snapshot of membership data" do expect(Snapshot).to receive(:take_snapshot).once run_rake_task end end describe "send absence email" do let :run_rake_task do Rake::Task["daily_tasks:send_absence_email"].reenable Rake.application.invoke_task "daily_tasks:send_absence_email" end it "checks for abesnt members" do expect(Member).to receive(:members_absent) run_rake_task end it "sends an email to the shoutout committee if there are absent members" do absent_members = [class_double(Member)] allow(Member).to receive(:members_absent) { absent_members } expect(ShoutOutEmail).to receive(:absent_members_email).and_return(double("mailer", :deliver => true)) run_rake_task end it "does not send an email to the shoutout committee if there are no absent members" do allow(Member).to receive(:members_absent) { [] } expect(ShoutOutEmail).not_to receive(:absent_members_email) run_rake_task end end end
class AddColumnToStoreAuth < ActiveRecord::Migration[6.1] def change add_column :store_auths, :jti, :string, null: false add_index :store_auths, :jti, unique: true end end
class Image < Attachment mount_uploader :file, ImageUploader validates :file, file_size: { maximum: 4.megabyte }, image_size: { max_width: 2048 } end
class Recording < ActiveRecord::Base attr_accessible :song_id, :band_id belongs_to :band belongs_to :song end
class ReviewsAddAffiliation < ActiveRecord::Migration def self.up add_column :reviews, :affiliation, :enum, :limit => Review::AFFILIATION_ENUM_VALUES, :default => nil, :allow_nil => true end def self.down remove_column :reviews, :affiliation end end
class Admin::GhostingSessionsController < Admin::ControllerBase before_action :ghosting_user_id, only: :create skip_before_action :authenticate_admin_user!, only: :destroy def create cookies[:ghosting_user_id] = @ghosting_user_id redirect_to root_path end def destroy cookies.delete :ghosting_user_id redirect_to admin_instructor_profiles_path end private def ghosting_user_id @ghosting_user_id = params[:ghosting_session].try(:[], :user_id) if @ghosting_user_id.nil? flash[:danger] = "Something went wrong: no user_id" redirect_to admin_instructor_profiles_path end end end
class Option < ApplicationRecord belongs_to :question validates :option_text, presence: true end
class RenameSubtitleToDescriptionToActivities < ActiveRecord::Migration def change rename_column :activities, :subtitle, :description end end
# frozen_string_literal: true require 'rails_admin/config/proxyable' require 'rails_admin/config/configurable' require 'rails_admin/config/inspectable' require 'rails_admin/config/has_fields' require 'rails_admin/config/has_groups' require 'rails_admin/config/has_description' module RailsAdmin module Config module Sections # Configuration of the show view for a new object class Base include RailsAdmin::Config::Proxyable include RailsAdmin::Config::Configurable include RailsAdmin::Config::Inspectable include RailsAdmin::Config::HasFields include RailsAdmin::Config::HasGroups include RailsAdmin::Config::HasDescription attr_reader :abstract_model, :parent, :root NAMED_INSTANCE_VARIABLES = %i[@parent @root @abstract_model].freeze def initialize(parent) @parent = parent @root = parent.root @abstract_model = root.abstract_model end end end end end
print (2**1000).to_s.split("").map { |i| i.to_i }.inject(:+)
# Overwrite the BSON object ID as_json and to_json methods # so that when rendered as json it will simply use to_string class BSON::ObjectId alias_method :original_to_json, :to_json def as_json(*a) to_s end def to_json(*a) as_json.to_json end end # Open up the Hash class to provide a stringify keys method to sanitize # hashes before we create a Mote::Document. # # @see https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/hash/keys.rb class Hash # Creates a new hash with keys stringified def stringify_keys dup.stringify_keys! end # Loop through all keys and create a string key for each one # deleteing the old key and returning the hash # # @return [Hash] Stringified hash def stringify_keys! keys.each do |key| self[key.to_s] = delete(key) end self end end
class RemoveOrphanedAssignments < ActiveRecord::Migration def change Rails.cache.write('check:migrate:remove_orphaned_assignments', Assignment.last&.id) end end
class Email def initialize(email) @raw = email.to_s end def to_str @raw.downcase end alias_method :to_s, :to_str class << self def load(value = nil) new value end def dump(obj) return if obj.nil? obj.to_str end end def method_missing(name, *args, &block) super unless @raw.respond_to?(name) to_str.public_send(name, *args, &block) end def ==(other) to_str == other.to_str end end
class NotificationMailer < ActionMailer::Base def notification_email(notification,email) @email = email @notification = notification @from = GenericNotificationsRails.config.email_from subject_pref = GenericNotificationsRails.config.email_subject if subject_pref @subject = instance_exec &subject_pref else @subject = "Notification from #{Rails.application.class.parent_name}" end mail(to: @email.address, subject: @subject) end end
require 'spec_helper' describe Metasploit::Model::Platform, # setting the metadata type makes rspec-rails include RSpec::Rails::ModelExampleGroup, which includes a better # be_valid matcher that will print full error messages type: :model do it_should_behave_like 'Metasploit::Model::Platform', namespace_name: 'Dummy' do def attribute_type(attribute) type_by_attribute = { fully_qualified_name: :string } type_by_attribute.fetch(attribute) end end # @note Not tested in 'Metasploit::Model::Platform' shared example because it is a module method and not a class # method because seeding should always refer back to {Metasploit::Model::Platform} and not the classes in which # it is included. context 'fully_qualified_names' do subject(:fully_qualified_name_set) do described_class.fully_qualified_name_set end it { should include 'AIX' } it { should include 'Android' } it { should include 'BSD' } it { should include 'BSDi' } it { should include 'Cisco' } it { should include 'Firefox' } it { should include 'FreeBSD' } it { should include 'HPUX' } it { should include 'IRIX' } it { should include 'Java' } it { should include 'Javascript' } it { should include 'NetBSD' } it { should include 'Netware' } it { should include 'NodeJS' } it { should include 'OpenBSD' } it { should include 'OSX' } it { should include 'PHP' } it { should include 'Python' } it { should include 'Ruby' } it { should include 'Solaris'} it { should include 'Solaris 4' } it { should include 'Solaris 5' } it { should include 'Solaris 6' } it { should include 'Solaris 7' } it { should include 'Solaris 8' } it { should include 'Solaris 9' } it { should include 'Solaris 10' } it { should include 'Windows' } it { should include 'Windows 95' } it { should include 'Windows 98' } it { should include 'Windows 98 FE' } it { should include 'Windows 98 SE' } it { should include 'Windows ME' } it { should include 'Windows NT' } it { should include 'Windows NT SP0' } it { should include 'Windows NT SP1' } it { should include 'Windows NT SP2' } it { should include 'Windows NT SP3' } it { should include 'Windows NT SP4' } it { should include 'Windows NT SP5' } it { should include 'Windows NT SP6' } it { should include 'Windows NT SP6a' } it { should include 'Windows 2000' } it { should include 'Windows 2000 SP0' } it { should include 'Windows 2000 SP1' } it { should include 'Windows 2000 SP2' } it { should include 'Windows 2000 SP3' } it { should include 'Windows 2000 SP4' } it { should include 'Windows XP' } it { should include 'Windows XP SP0' } it { should include 'Windows XP SP1' } it { should include 'Windows XP SP2' } it { should include 'Windows XP SP3' } it { should include 'Windows 2003' } it { should include 'Windows 2003 SP0' } it { should include 'Windows 2003 SP1' } it { should include 'Windows Vista' } it { should include 'Windows Vista SP0' } it { should include 'Windows Vista SP1' } it { should include 'Windows 7' } it { should include 'UNIX' } end end
module Entities module Telegram class Message < Entity attribute :message_id, Types::Strict::Integer attribute :from, From attribute :chat, Chat attribute :date, Types::Strict::Integer attribute :text, Types::Strict::String end end end
class ChangeSeatsIdToUuid < ActiveRecord::Migration[6.0] def change add_column :seats, :uuid, :uuid, default: "gen_random_uuid()", null: false add_column :users, :seat_uuid, :uuid execute <<-SQL UPDATE users SET seat_uuid = seats.uuid FROM seats WHERE users.seat_id = seats.id; SQL change_table :users do |t| t.remove :seat_id t.rename :seat_uuid, :seat_id end change_table :seats do |t| t.remove :id t.rename :uuid, :id end execute "ALTER TABLE seats ADD PRIMARY KEY (id);" end end
# frozen_string_literal: true require_relative '../aa_service_bus.rb' def app AaServiceBus end RSpec.describe AaServiceBus, type: :request do describe 'GET /' do before { get '/', {}, 'HTTP_AUTHORIZATION' => '' } it { expect(last_response.body).to include 'Welcome to the Agile Alliance Service Bus' } end describe 'GET /check_member' do context 'unauthenticated' do before { get '/check_member/foo@bar.com' } it { expect(last_response.status).to eq 401 } end context 'authenticated' do before { WebMock.enable! } after { WebMock.disable! } context 'when the AA API is up' do context 'and the user is a member' do subject(:body) { last_response.body } it 'responds true' do WebMock.stub_request(:post, "#{ENV['AA_API_HOST']}/check-membership").to_return(status: 200, body: '<?xml version=\"1.0\" encoding=\"UTF-8\"?><data><result>1</result></data>', headers: {}) get '/check_member/foo@bar.com', {}, 'HTTP_AUTHORIZATION' => ENV['AA_API_TOKEN'] expect(last_response.status).to eq 200 expect(JSON.parse(body)['member']).to be_truthy end end context 'and the user is not a member' do subject(:body) { last_response.body } it 'responds false' do WebMock.stub_request(:post, "#{ENV['AA_API_HOST']}/check-membership").to_return(status: 200, body: '<?xml version=\"1.0\" encoding=\"UTF-8\"?><data><result>0</result></data>', headers: {}) get '/check_member/bla@xpto.com', {}, 'HTTP_AUTHORIZATION' => ENV['AA_API_TOKEN'] expect(last_response.status).to eq 200 expect(JSON.parse(body)['member']).to be_falsey end end context 'and the service returned no node <result>' do subject(:body) { last_response.body } it 'responds false' do WebMock.stub_request(:post, "#{ENV['AA_API_HOST']}/check-membership").to_return(status: 200, body: '<?xml version=\"1.0\" encoding=\"UTF-8\"?><data></data>', headers: {}) get '/check_member/bla@xpto.com', {}, 'HTTP_AUTHORIZATION' => ENV['AA_API_TOKEN'] expect(last_response.status).to eq 200 expect(JSON.parse(body)['member']).to be_falsey end end context 'and the service returned no node <data>' do subject(:body) { last_response.body } it 'responds false' do WebMock.stub_request(:post, "#{ENV['AA_API_HOST']}/check-membership").to_return(status: 200, body: '<?xml version=\"1.0\" encoding=\"UTF-8\"?>', headers: {}) get '/check_member/bla@xpto.com', {}, 'HTTP_AUTHORIZATION' => ENV['AA_API_TOKEN'] expect(last_response.status).to eq 200 expect(JSON.parse(body)['member']).to be_falsey end end end context 'when the AA service is down' do subject(:body) { last_response.body } let!(:file) { File.read('./spec/fixtures/test.csv', encoding: 'ISO-8859-1:UTF-8') } context 'and the user is a member' do it 'verifies on CSV file and returns true' do expect(File).to receive(:read) { file } WebMock.stub_request(:post, "#{ENV['AA_API_HOST']}/check-membership").to_raise(Net::OpenTimeout) get '/check_member/bla@xpto.com', {}, 'HTTP_AUTHORIZATION' => ENV['AA_API_TOKEN'] expect(last_response.status).to eq 200 expect(JSON.parse(body)['member']).to be_truthy end end context 'and the user is not a member' do it 'verifies on CSV file and returns false' do expect(File).to receive(:read) { file } WebMock.stub_request(:post, "#{ENV['AA_API_HOST']}/check-membership").to_raise(Net::OpenTimeout) get '/check_member/foo@bar.com', {}, 'HTTP_AUTHORIZATION' => ENV['AA_API_TOKEN'] expect(last_response.status).to eq 200 expect(JSON.parse(body)['member']).to be_falsey end end end end end end
class Libhdhomerun < Formula homepage "https://www.silicondust.com/support/downloads/linux/" url "http://download.silicondust.com/hdhomerun/libhdhomerun_20141210.tgz" sha1 "4f6827e17f8f79401f272f62089352fe01eae740" bottle do cellar :any sha1 "2c58f3fd30b8ea2f03c5f0edc051c6b0cdc9ca14" => :yosemite sha1 "cc8190e5256ae8ba11041449e98b7c85ae2565a2" => :mavericks sha1 "7e96bccea269523447a15356e8cb65216365ca99" => :mountain_lion end def install system "make" bin.install "hdhomerun_config" lib.install "libhdhomerun.dylib" include.install Dir["hdhomerun*.h"] end test do # Devices may be found or not found, with differing return codes discover = pipe_output("#{bin}/hdhomerun_config discover") outputs = ["no devices found", "hdhomerun device", "found at"] assert outputs.any? { |x| discover.include? x } end end
require 'rubygems' require 'json' require 'httparty' begin require 'cgi' end $:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) # module RockyKlout # VERSION = '0.0.2' # end class RockyKlout include HTTParty VERSION = '0.0.2' @@base_uri = "http://api.klout.com" @@api_version = "1" @@api_key = "" def initialize(api_key) @@api_key = api_key end def api_key=(api) @@api_key = api end def api_key @@api_key end def score_klout(usernames) request_uri = "/#{@@api_version}/klout.json?key=#{@@api_key}&users=" + usernames.collect{|name| CGI.escape(name)}.join(",") self.class.get(@@base_uri + request_uri) end def user_show(usernames) request_uri = "/#{@@api_version}/users/show.json?key=#{@@api_key}&users=" + usernames.collect{|name| CGI.escape(name)}.join(",") self.class.get(@@base_uri + request_uri) end def user_topics(usernames) request_uri = "/#{@@api_version}/users/topics.json?key=#{@@api_key}&users=" + usernames.collect{|name| CGI.escape(name)}.join(",") self.class.get(@@base_uri + request_uri) end def user_stats(usernames) request_uri = "/#{@@api_version}/users/stats.json?key=#{@@api_key}&users=" + usernames.collect{|name| CGI.escape(name)}.join(",") self.class.get(@@base_uri + request_uri) end def user_history(usernames, measure, start_date, end_date) request_uri = "/#{@@api_version}/users/show.json?key=#{@@api_key}&users=" + usernames.collect{|name| CGI.escape(name)}.join(",") + "&measure=" + CGI.escape(measure) + "&start_date=" + CGI.escape(start_date) "&end_date=" + CGI.escape(end_date) self.class.get(@@base_uri + request_uri) end def relationship_influenced_by(usernames) request_uri = "/#{@@api_version}/soi/influenced_by.json?key=#{@@api_key}&users=" + usernames.collect{|name| CGI.escape(name)}.join(",") self.class.get(@@base_uri + request_uri) end def relationship_influencer_of(usernames) request_uri = "/#{@@api_version}/soi/influencer_of.json?key=#{@@api_key}&users=" + usernames.collect{|name| CGI.escape(name)}.join(",") self.class.get(@@base_uri + request_uri) end def topic_search(topic) request_uri = "/#{@@api_version}/topics/search.json?key=#{@@api_key}&topic=" + CGI.escape(topic) self.class.get(@@base_uri + request_uri) end def topic_verify(topic) request_uri = "/#{@@api_version}/topics/verify.json?key=#{@@api_key}&topic=" + CGI.escape(topic) self.class.get(@@base_uri + request_uri) end end
require 'rails_helper' RSpec.describe Ng::V1::StatesController, type: :controller do let(:user) { User.first } let(:admin_user) { User.where(admin: true).first } let(:state) { State.first } let(:user_auth_data) { Base64.strict_encode64("#{user.email}:test@1234") } let(:admin_auth_data) { Base64.strict_encode64("#{admin_user.email}:admin@admin") } let(:ordered_states) { State.ordered.to_a } describe 'GET #index' do it_should_behave_like 'Unauthorized User' do before do get :index end end context 'Admin User' do before :each do request.headers['Authorization'] = "Basic #{admin_auth_data}" get :index end it 'return 200' do expect(response).to have_http_status(200) expect(JSON.parse(response.body)).to include('states_list') expect(response.body).to eql({ states_list: State.ordered.includes(:vehicles) }.to_json) end end end describe 'POST #create' do it_should_behave_like 'Unauthorized User' do before do post :create, params: { state: { name: 'Test State' } } end end context 'Admin User' do before :each do request.headers['Authorization'] = "Basic #{admin_auth_data}" end it 'return 200' do expect do post :create, params: { state: { name: 'Test State' } } end.to change(State, :count).by(1) end end end describe 'PUT #update' do it_should_behave_like 'Unauthorized User' do before do put :update, params: { id: state.id, state: { name: 'Updated Title' } } end end context 'Admin User' do let(:state) {State.first} before :each do request.headers['Authorization'] = "Basic #{admin_auth_data}" put :update, params: { id: state.id, state: { name: 'Updated Title' } } state.reload end it 'returns 200 and updates the state title' do expect(state.name).to eql('Updated Title') end end end describe 'DELETE #destroy' do it_should_behave_like 'Unauthorized User' do before do delete :destroy, params: { id: state.id } end end context 'Admin User' do before :each do request.headers['Authorization'] = "Basic #{admin_auth_data}" delete :destroy, params: { id: state.id } end it 'return 200' do expect(response).to have_http_status(200) end end end describe 'PUT #update_order' do it_should_behave_like 'Unauthorized User' do before do put :update_order end end context 'Admin User' do before :each do request.headers['Authorization'] = "Basic #{admin_auth_data}" ordered_states.sort_by! { rand } @sorted_states = Hash[ordered_states.each_with_index.map { |v, i| [v.id, i] }] put :update_order, params: { sorted_states: @sorted_states } end it 'return 200' do expect(response).to have_http_status(200) expect(State.ordered.pluck(:id)).to eql(@sorted_states.keys) end end end end
class CreateProfiles < ActiveRecord::Migration def change create_table :profiles do |t| t.references :user, foreign_key: true, null: false t.text :description t.text :hobbies t.text :habits t.text :residence t.text :look_for t.index :user_id, unique: true t.timestamps null: false end end end
class Comment < ActiveRecord::Base attr_accessible :entry, :picture_id belongs_to :picture end
class UserInk < ActiveRecord::Base validates :is_cartridge, inclusion: { in: [true, false] } validates :is_bottled, inclusion: { in: [true, false] } validates :user_id, presence: true, numericality: { only_integer: true } validates :ink_id, presence: true, numericality: { only_integer: true } belongs_to :user belongs_to :ink end
class ClubTeam < ActiveRecord::Base before_validation :update_slug scope :main_pages, where(:general_page ^ true).where(:parent_id => nil).order("created_at DESC") scope :general_pages, where(:general_page => true).order("created_at ASC") validates_uniqueness_of :name, :scope => :parent_id def children ClubTeam.where(:parent_id => id).order("created_at DESC") end def parent ClubTeam.where(:id => parent_id).first end def general_page? general_page == true end private def update_slug self.slug = self.name.parameterize end end
module RecipesHelper # Print an Html label with picture and title of Recipe's type # # @param recipe [Recipe] as recipe to print # @return [String] as Html content # @return [nil] if it's not possible to create Html content def recipe_label_type recipe if recipe.rtype html_image = image_tag "type_of_food/%s.svg" % recipe.rtype, class: "img-responsive recipe-label", alt: 'Type de plat', size: '40' link_to html_image + recipe.rtype , recipes_path( :type => recipe.rtype ) end end # Print an Html label with picture and title of Recipe's season # # @param recipe [Recipe] as recipe to print # @return [String] as Html content # @return [nil] if it's not possible to create Html content def recipe_label_season recipe if recipe.rtype html_image = image_tag "seasons/%s.svg" % recipe.season, class: "img-responsive recipe-label", alt: 'Icon de la saison', size: '40' link_to html_image + recipe.season , recipes_path( :season => recipe.season ) else nil end end end
# I427 Fall 2015, Assignment 3 # Code authors: [Ashlee Workman] # # based on skeleton code by D Crandall # Importing required libraries require 'nokogiri' require 'fast-stemmer' # This function writes out a hash or an array (list) to a file. # def write_data(filename, data) file = File.open(filename, "w") file.puts(data) file.close end # function that takes the name of a file and loads in the stop words from the file. # You could return a list from this function, but a hash might be easier and more efficient. # (Why? Hint: think about how you'll use the stop words.) # def load_stopwords_file(file) stop_words = {} # Looping through the file and adding each word to a hash table after chomping them File.open(file, "r").each_line do |line| stop_words[line.chomp] = 1 end return stop_words end # function that takes the name of a directory, and returns a list of all the filenames in that # directory. # def list_files(dir) # Getting all the files names in the directory file_names = Dir[dir + "*"] return file_names end ##################################### # CUSTOM FUNCTIONS ##################################### # parse_html takes the HTML code of a document and removes all the junk from it in order to return the text # content on the page def parse_html(html) doc = Nokogiri::HTML(html) # Removing style and script tag content such as Javascript tags in order to get rid of JUNK text doc.xpath("//script").remove doc.xpath("//style").remove begin text = doc.at('body').inner_text rescue NoMethodError puts "NoMethodError" # puts file_name #title = nil end return text end # remove_punc takes a string containing text and removes all the punctuation from it in order to finally # return a list of words/tokens in the text def remove_punc(text) word_list = [] # Checking for correct encoding and reencoding the string if necessary if ! text.valid_encoding? text = text.encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8') end # Removing puctuation words = text.split(/[ ,;{}`~!@#$%^&*<>.:"'|?\\()_+=\/\[\]\-]/) # Looping though the list, checking for valid words, and changing their case for word in words word = word[/\w*/] word.downcase! word_list.push(word) end # Deleting blanks word_list.delete("") return word_list end # function that takes the *name of an html file stored on disk*, and returns a list # of tokens (words) in that file. # def find_tokens(filename) html = File.read(filename) # Parsing the HTML content of the file parsed_html = parse_html(html) # Converting the text into a list of tokens after removing punctuation tokens = remove_punc(parsed_html) return tokens end # function that takes a list of tokens, and a list (or hash) of stop words, # and returns a new list with all of the stop words removed # def remove_stop_tokens(tokens, stop_words) # Looping through the list of tokens and removing all the stop words from the list for i in tokens if stop_words.member?(i) tokens.delete(i) end end return tokens end # function that takes a list of tokens, runs a stemmer on each token, # and then returns a new list with the stems # def stem_tokens(tokens) stem_list = [] # Looping through the list and finding the stem word for each word for word in tokens word = word[/\w*/] s = word.stem stem_list.push(s) end return stem_list end # get_title takes a file name a returns the text within the HTML title tag of the file def get_title(file_name) html = File.read(file_name) doc = Nokogiri::HTML(html) begin # Grabbing the title from the page title = doc.css("title")[0].text.strip rescue NoMethodError puts "NoMethodError" puts file_name title = nil end return title end # get_file_detials takes a file name containg the index and returns the data of the file # i.e. its name and url in a hash table def get_file_details(file_name) fd = {} # Looping through the file and updating the name and url variable with the new data # and then finally adding them to the hash table File.readlines(file_name).each do |line| data = line.split(" ") puts data[2] name = data[0] url = data[2] fd[name] = url end puts fd return fd end # index_file takes a file and performs the necessary tasks to index that file in the # search engine def index_file(file, pages_dir, stopwords, file_data) # Removing the dir from the file name # begin actual_name = file.gsub(pages_dir, "") # rescue NoMethodError # actual_name = badpage.html # Resetting the file path file_path = "" file_path = File.expand_path(".") + "/" + file print "Parsing HTML document: " + actual_name + " \n" # Finding all the tokens in the file tokens = find_tokens(file_path) # Getting the page title, word count, and page url page_title = get_title(file_path) word_count = tokens.length page_url = file_data[actual_name] # Updating the docindex hash $docindex[file.gsub(pages_dir, "")] = [word_count, page_title, page_url] # Removing the stop words and getting the stem words in the file tokens = remove_stop_tokens(tokens, stopwords) tokens = stem_tokens(tokens) # Creating the invindex hash table for token in tokens begin if $invindex.member?(token) if $invindex[token].member?(actual_name) $invindex[token][actual_name] += 1 else $invindex[token][actual_name] = 1 end else $invindex[token] = {actual_name => 1} end # end # rescue NoMethodError # puts "NoMethodError" end #puts file_name # title = nil end #end end ################################################# # Main program. We expect the user to run the program like this: # # ruby index.rb pages_dir/ index.dat # # The following is just a main program to help get you started. # Feel free to make any changes or additions/subtractions to this code. # # check that the user gave us 3 command line parameters if ARGV.size != 2 abort "Command line should have 3 parameters." end # fetch command line parameters (pages_dir, index_file) = ARGV # Pulling file info for each file from index.dat file_data = get_file_details("index.dat") # read in list of stopwords from file and add them to a gloab hash table stopwords = load_stopwords_file("stop.txt") # get the list of files in the specified directory file_list = list_files(pages_dir) # create hash data structures to store inverted index and document index # the inverted index, and the outgoing links $invindex = {} $docindex = {} puts "\nIndexing Started!\n\n" ####################################################################################### # Single Threaded Algorithm # Loop through each file in the list of files #=begin for file in file_list index_file(file_list.pop, pages_dir, stopwords, file_data) end #=end #num_of_doc = hit_list.length ####################################################################################### ######################################################################################## # Multi-Threaded Indexing Algorithm (Extremely Fast - Useful when indexing thousands of pages) =begin # Initializing the thread variables (Increase/decrease the open threads if needed) total_threads = 200 open_threads = 0 files_checked = 0 Thread.abort_on_exception = true while file_list.length > 0 if open_threads < total_threads open_threads += 1 Thread.new { Thread.current["file"] = file_list.pop index_file(Thread.current["file"], pages_dir, stopwords, file_data) open_threads -= 1 } end end =end ######################################################################################### # save the hashes to the correct files write_data("invindex.dat", $invindex) write_data("doc.dat", $docindex) # done! puts "\nIndexing complete!\n\n"
# frozen_string_literal: true module ApplicationHelper BOOTSTRAP_CSS_CLASSES = { notice: 'primary', alert: 'danger' }.freeze DEFAULT_BOOTSTRAP_CSS_CLASS = :primary def year_now Time.current.year end def github_url(author, repo) link_to repo.to_s, "https://github.com/#{author}/#{repo}", target: :_blank end def bootstrap_alert_css_class(key) css_class = BOOTSTRAP_CSS_CLASSES[key.to_sym] || DEFAULT_BOOTSTRAP_CSS_CLASS "alert alert-#{css_class}" end end
class Api::V1::SessionsController < ApplicationController acts_as_token_authentication_handler_for User, except: [:create] after_action :verify_authorized, except: [:create] def create @user = User.find_by email: params[:email] if @user&.valid_password? params[:password] render :create else head :unauthorized end end def destroy user = authorize(User.find(params[:id]), :update?) user.authentication_token = nil if user.save head :ok else head :unauthorized end end end
require 'rails_helper' RSpec.describe Guide::ScenarioLayoutView do let(:view_model) do described_class.new( :node => node_argument, :node_title => node_title_argument, :scenario => scenario_argument, :format => format_argument, :injected_html => injected_html_argument, ) end let(:node_argument) do instance_double(Guide::Structure, :layout_templates => node_layout_templates, :layout_view_model => node_layout_view_model, :stylesheets => ['Node Stylesheets'], :javascripts => ['Node JavaScripts']) end let(:node_layout_templates) do { html: 'html/layout/template' } end let(:node_layout_view_model) { instance_double(Guide::ViewModel) } let(:node_title_argument) { 'Node Title' } let(:scenario_argument) { double(:name => 'Scenario Name') } let(:format_argument) { 'format' } let(:injected_html_argument) { '<h1>Arbitrary Injected HTML</h1>' } describe '#node_title' do subject(:node_title) { view_model.node_title } it "returns the node title that was passed in on initialization" do expect(node_title).to eq 'Node Title' end end describe '#scenario_name' do subject(:scenario_name) { view_model.scenario_name } it "returns the name of the scenario" do expect(scenario_name).to eq 'Scenario Name' end end describe '#node_layout_template' do subject(:node_layout_template) { view_model.node_layout_template } let(:node_layout_templates) do { html: 'html/layout/template', text: 'text/layout/template', } end context 'there is a node-specific layout template for this format' do let(:format_argument) { :html } it "returns the layout template specified on the node" do expect(node_layout_template).to eq 'html/layout/template' end end context 'a node-specific layout template does not exist for this format' do let(:format_argument) { :pdf } it "returns the default layout for scenarios as specified in configuration" do expect(node_layout_template).to eq Guide.configuration.default_layout_for_scenarios end end end describe '#node_layout_view' do subject(:node_layout_view) { view_model.node_layout_view } it "returns the layout view model specified on the node" do expect(node_layout_view).to eq node_layout_view_model end end describe '#format' do subject(:format) { view_model.format } it "returns the format that was passed in on initialization" do expect(format).to eq 'format' end end describe '#inject_stylesheets?' do subject(:inject_stylesheets?) { view_model.inject_stylesheets? } context 'the scenario is in HTML format' do let(:format_argument) { :html } it { is_expected.to be true } end context 'the scenario is in a different format' do let(:format_argument) { :text } it { is_expected.to be false } end end describe '#node_stylesheets' do subject(:node_stylesheets) { view_model.node_stylesheets } it "returns the stylesheets from the node" do expect(node_stylesheets).to eq ['Node Stylesheets'] end end describe '#inject_javascripts?' do subject(:inject_javascripts?) { view_model.inject_javascripts? } context 'the scenario is in HTML format' do let(:format_argument) { :html } it { is_expected.to be true } end context 'the scenario is in a different format' do let(:format_argument) { :text } it { is_expected.to be false } end end describe '#node_javascripts' do subject(:node_javascripts) { view_model.node_javascripts } it "returns the javascripts from the node" do expect(node_javascripts).to eq ['Node JavaScripts'] end end describe '#injected_html' do subject(:injected_html) { view_model.injected_html } it "returns the HTML injection that was passed in on initialization" do expect(injected_html).to eq '<h1>Arbitrary Injected HTML</h1>' end end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # name :string(255) # email_address :string(255) # screen_name :string(255) # hometown :string(255) # password_digest :string(255) # remember_token :string(255) # created_at :datetime # updated_at :datetime # class User < ActiveRecord::Base has_many :trips has_secure_password before_save :create_remember_token validates :email_address, uniqueness: true validates :password, confirmation: true, length: {in: 6..20} validates :password_confirmation, presence: true end private def create_remember_token self.remember_token = SecureRandom.urlsafe_base64 end
class ChangTableNameItem < ActiveRecord::Migration def change rename_table :item, :items end end
class Purchaser < ActiveRecord::Base attr_accessible :name has_many :line_items end
Given(/^a user visits the Homepage$/) do visit root_path end Given(/^a user visits the About Us Page$/) do visit about_us_path end
require "rails_helper" describe ExotelAPIService, type: :model do let(:account_sid) { Faker::Internet.user_name } let(:token) { SecureRandom.base64 } let(:service) { ExotelAPIService.new(account_sid, token) } let(:auth_token) { Base64.strict_encode64([account_sid, token].join(":")) } let(:request_headers) do { "Authorization" => "Basic #{auth_token}", "Connection" => "close", "Host" => "api.exotel.com", "User-Agent" => "http.rb/#{HTTP::VERSION}" } end around do |example| WebMock.disallow_net_connect! example.run WebMock.allow_net_connect! end describe "#call_details" do let!(:call_details_200) { File.read("spec/support/fixtures/call_details_200.json") } let!(:call_details_400) { File.read("spec/support/fixtures/call_details_400.json") } let!(:sid) { JSON(call_details_200).dig("Call", "AccountSid") } let!(:call_sid) { JSON(call_details_200).dig("Call", "Sid") } let!(:token) { "token" } let!(:auth_token) { Base64.strict_encode64([sid, token].join(":")) } let!(:request_url) { "https://api.exotel.com/v1/Accounts/sid/Calls/#{call_sid}.json" } let!(:request_headers) do { "Authorization" => "Basic #{auth_token}", "Connection" => "close", "Host" => "api.exotel.com", "User-Agent" => "http.rb/#{HTTP::VERSION}" } end it "should return call details for a session id in json when status is 200" do stub_request(:get, request_url).with(headers: request_headers).to_return(status: 200, body: call_details_200, headers: {}) response = described_class.new(sid, token).call_details(call_sid) expect(response[:Call][:From]).to eq("09663127355") expect(response[:Call][:To]).to eq("01930483621") expect(response[:Call].keys).to eq(%i[Sid ParentCallSid DateCreated DateUpdated AccountSid To From PhoneNumberSid Status StartTime EndTime Duration Price Direction AnsweredBy ForwardedFrom CallerName Uri RecordingUrl]) end it "should not return a response for a session that does not exist" do stub_request(:get, request_url).with(headers: request_headers).to_return(status: 400, body: call_details_400, headers: {}) expected_call_details_response = described_class.new(sid, token).call_details(call_sid) expect(expected_call_details_response).to eq(nil) end it "should not return a response when the api returns a 500" do stub_request(:get, request_url).with(headers: request_headers).to_return(status: 500, headers: {}) expected_call_details_response = described_class.new(sid, token).call_details(call_sid) expect(expected_call_details_response).to eq(nil) end it "should report an error if there is a network timeout while calling the api" do stub_request(:get, request_url).to_timeout expect(Sentry).to receive(:capture_message).and_return(true) expect { described_class.new(sid, token).call_details(call_sid) }.to raise_error(ExotelAPIService::HTTPError) end end describe "#whitelist_phone_numbers" do let(:request_url) { URI.parse("https://api.exotel.com/v1/Accounts/#{account_sid}/CustomerWhitelist.json") } let(:virtual_number) { Faker::PhoneNumber.phone_number } let(:phone_numbers) { (0..3).map { Faker::PhoneNumber.phone_number } } let!(:auth_token) { Base64.strict_encode64([account_sid, token].join(":")) } let(:request_body) do { Language: "en", VirtualNumber: virtual_number, Number: phone_numbers.join(",") } end it "calls the exotel whitelist api for given virtual number and phone number list" do Flipper.enable(:exotel_whitelist_api) stub = stub_request(:post, request_url).with( headers: request_headers, body: request_body ) service.whitelist_phone_numbers(virtual_number, phone_numbers) expect(stub).to have_been_requested Flipper.disable(:exotel_whitelist_api) end it "does not call the exotel whitelist api if the feature flag is off" do stub = stub_request(:post, request_url).with( headers: request_headers, body: request_body ) service.whitelist_phone_numbers(virtual_number, phone_numbers) expect(stub).not_to have_been_requested end end describe "parse_exotel_whitelist_expiry" do it "returns nil if expiry time is nil" do expect(service.parse_exotel_whitelist_expiry(nil)).to be_nil end it "returns nil if expiry time is less than 0" do expect(service.parse_exotel_whitelist_expiry(-1)).to be_nil end it "return the time at which the expiry will happen if expiry time is greater than 0" do Timecop.freeze(Time.current) do expected_time = 1.hour.from_now expect(service.parse_exotel_whitelist_expiry(3600)).to eq(expected_time) end end end describe "get_phone_number_details" do let(:phone_number) { Faker::PhoneNumber.phone_number } let(:whitelist_details_url) { URI.parse("https://api.exotel.com/v1/Accounts/#{account_sid}/CustomerWhitelist/#{ERB::Util.url_encode(phone_number)}.json") } let(:numbers_metadata_url) { URI.parse("https://api.exotel.com/v1/Accounts/#{account_sid}/Numbers/#{ERB::Util.url_encode(phone_number)}.json") } let!(:whitelist_details_stub) do stub_request(:get, whitelist_details_url).with(headers: request_headers) .to_return( status: 200, headers: {}, body: JSON( "Result" => {"Status" => "Whitelist", "Type" => "API", "Expiry" => 3600} ) ) end let!(:numbers_metadata_stub) do stub_request(:get, numbers_metadata_url).with(headers: request_headers) .to_return( status: 200, headers: {}, body: JSON( "Numbers" => {"PhoneNumber" => phone_number, "Circle" => "KA", "CircleName" => "Karnataka", "Type" => "Mobile", "Operator" => "V", "OperatorName" => "Vodafone", "DND" => "Yes"} ) ) end it "makes a request to exotel number metadata and whitelist details api" do service.phone_number_details(phone_number) expect(numbers_metadata_stub).to have_been_requested expect(whitelist_details_stub).to have_been_requested end it "returns the phone number status returned from the two apis" do Timecop.freeze do expect(service.phone_number_details(phone_number)) .to eq(dnd_status: true, phone_type: :mobile, whitelist_status: :whitelist, whitelist_status_valid_until: Time.current + 3600.seconds) end end end end
require File.join(File.dirname(__FILE__), '../lib/gilded_rose') describe GildedRose do describe "#update_quality" do it "does not change the name" do items = [Item.new("foo", 0, 0)] GildedRose.new(items).update_quality() expect(items[0].name).to eq "foo" end it "decreases the quality by one of all items except Brie, Backstage passes and Sulfuras" do items = [Item.new("foo", 20, 20)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 19 end it "decreases the sell_in by one of all items except Brie, Backstage passes and Sulfuras" do items = [Item.new("foo", 20, 20)] GildedRose.new(items).update_quality() expect(items[0].sell_in).to eq 19 end it "decreases the quality by two of all items except Brie, Backstage passes and Sulfuras when sell_in is negative" do items = [Item.new("foo", -1, 10)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 8 end it "never allows the quality to be negative" do items = [Item.new("foo", 0, 0)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 0 end it "will not decrease or increase the quality of Sulfuras" do items = [Item.new("Sulfuras, Hand of Ragnaros", 50, 50)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 50 end it "will not decrease or increase the sell_in of Sulfuras" do items = [Item.new("Sulfuras, Hand of Ragnaros", 50, 50)] GildedRose.new(items).update_quality() expect(items[0].sell_in).to eq 50 end it "does not allow the quality of an item to be more than 50" do items = [Item.new("Backstage passes to a TAFKAL80ETC concert", 3, 50)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 50 end it "will increase the quality of backstage pass by one if sell in is 11 or more" do items = [Item.new("Backstage passes to a TAFKAL80ETC concert", 12, 40)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 41 end it "will increase the quality of backstage pass by two if sell in is between 10 and 6" do items = [Item.new("Backstage passes to a TAFKAL80ETC concert", 9, 40)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 42 end it "will increase the quality of backstage pass by three if sell in is five or less" do items = [Item.new("Backstage passes to a TAFKAL80ETC concert", 5, 47)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 50 end it "will increase the quality of brie by one when sell_in is zero or positive" do items = [Item.new("Aged Brie", 1, 49)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 50 end it "will increase the quality of brie by two when sell_in is negative" do items = [Item.new("Aged Brie", -1, 48)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 50 end it "will decrease the sell_in of all items except sulfuras" do items = [Item.new("Aged Brie", 8, 40)] GildedRose.new(items).update_quality() expect(items[0].sell_in).to eq 7 end it "Backstage pass quality is zero when sell_in is negative" do items = [Item.new("Backstage passes to a TAFKAL80ETC concert", 0, 50)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 0 end it "decreases the quality by two for all items except sulfuras when sell_in is negative" do items = [Item.new("foo", -1, 10)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 8 end it "decreases the quality by two for conjured" do items = [Item.new("Conjured", 20, 10)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 8 end end end
require 'rails_helper' RSpec.describe RegistrarPresenter do let(:registrar) { instance_double(Registrar) } let(:presenter) { described_class.new(registrar: registrar, view: view) } describe '#name' do it 'returns name' do expect(registrar).to receive(:name).and_return('test name') expect(presenter.name).to eq('test name') end end describe '#email' do it 'returns email' do expect(registrar).to receive(:email).and_return('test email') expect(presenter.email).to eq('test email') end end describe '#phone' do it 'returns phone' do expect(registrar).to receive(:phone).and_return('test phone') expect(presenter.phone).to eq('test phone') end end describe '#website' do it 'returns website' do expect(registrar).to receive(:website).and_return('test') expect(presenter.website).to eq('test') end end end
class ChangeServiceappPhoneType < ActiveRecord::Migration def up change_column :service_appointments, :company_phone, :bigint end def down change_column :service_appointments, :company_phone, :integer end end
# # test/spec -- a BDD interface for Test::Unit # # Copyright (C) 2006, 2007, 2008, 2009 Christian Neukirchen <mailto:chneukirchen@gmail.com> # # This work is licensed under the same terms as Ruby itself. # require 'test/unit' class Test::Unit::AutoRunner # :nodoc: RUNNERS[:specdox] = lambda { |*args| require 'test/spec/dox' Test::Unit::UI::SpecDox::TestRunner } RUNNERS[:rdox] = lambda { |*args| require 'test/spec/rdox' Test::Unit::UI::RDox::TestRunner } end module Test # :nodoc: end module Test::Spec require 'test/spec/version' CONTEXTS = {} # :nodoc: SHARED_CONTEXTS = Hash.new { |h,k| h[k] = [] } # :nodoc: class DefinitionError < StandardError end class Should include Test::Unit::Assertions def self.deprecated_alias(to, from) # :nodoc: define_method(to) { |*args| warn "Test::Spec::Should##{to} is deprecated and will be removed in future versions." __send__ from, *args } end def initialize(object, message=nil) @object = object @message = message end $TEST_SPEC_TESTCASE = nil def add_assertion $TEST_SPEC_TESTCASE && $TEST_SPEC_TESTCASE.__send__(:add_assertion) end def an self end def a self end def not(*args) case args.size when 0 ShouldNot.new(@object, @message) when 1 ShouldNot.new(@object, @message).pass(args.first) else raise ArgumentError, "#not takes zero or one argument(s)." end end def messaging(message) @message = message.to_s self end alias blaming messaging def satisfy(&block) assert_block(@message || "satisfy block failed.") { yield @object } end def equal(value) assert_equal value, @object, @message end alias == equal def close(value, delta) assert_in_delta value, @object, delta, @message end deprecated_alias :be_close, :close def be(*value) case value.size when 0 self when 1 if CustomShould === value.first pass value.first else assert_same value.first, @object, @message end else raise ArgumentError, "should.be needs zero or one argument" end end def match(value) assert_match value, @object, @message end alias =~ match def instance_of(klass) assert_instance_of klass, @object, @message end deprecated_alias :be_an_instance_of, :instance_of def kind_of(klass) assert_kind_of klass, @object, @message end deprecated_alias :be_a_kind_of, :kind_of def respond_to(method) assert_respond_to @object, method, @message end def _raise(*args, &block) args = [RuntimeError] if args.empty? block ||= @object args << @message if @message assert_raise(*args, &block) end def throw(sym) assert_throws(sym, @message, &@object) end def nil assert_nil @object, @message end deprecated_alias :be_nil, :nil def include(value) msg = build_message(@message, "<?> expected to include ?, but it didn't.", @object, value) assert_block(msg) { @object.include?(value) } end def >(value) assert_operator @object, :>, value, @message end def >=(value) assert_operator @object, :>=, value, @message end def <(value) assert_operator @object, :<, value, @message end def <=(value) assert_operator @object, :<=, value, @message end def ===(value) assert_operator @object, :===, value, @message end def pass(custom) _wrap_assertion { assert_nothing_raised(Test::Unit::AssertionFailedError, @message || custom.failure_message) { assert custom.matches?(@object), @message || custom.failure_message } } end def method_missing(name, *args, &block) # This will make raise call Kernel.raise, and self.raise call _raise. return _raise(*args, &block) if name == :raise if @object.respond_to?("#{name}?") assert @object.__send__("#{name}?", *args), "#{name}? expected to be true. #{@message}" else if @object.respond_to?(name) assert @object.__send__(name, *args), "#{name} expected to be true. #{@message}" else super end end end end class ShouldNot include Test::Unit::Assertions def initialize(object, message=nil) @object = object @message = message end def add_assertion $TEST_SPEC_TESTCASE && $TEST_SPEC_TESTCASE.__send__(:add_assertion) end def satisfy(&block) assert_block(@message || "not.satisfy block succeded.") { not yield @object } end def equal(value) assert_not_equal value, @object, @message end alias == equal def be(*value) case value.size when 0 self when 1 if CustomShould === value.first pass value.first else assert_not_same value.first, @object, @message end else Kernel.raise ArgumentError, "should.be needs zero or one argument" end end def match(value) # Icky Regexp check assert_no_match value, @object, @message end alias =~ match def _raise(*args, &block) block ||= @object args << @message if @message assert_nothing_raised(*args, &block) end def throw assert_nothing_thrown(@message, &@object) end def nil assert_not_nil @object, @message end def be_nil warn "Test::Spec::ShouldNot#be_nil is deprecated and will be removed in future versions." self.nil end def not(*args) case args.size when 0 Should.new(@object, @message) when 1 Should.new(@object, @message).pass(args.first) else raise ArgumentError, "#not takes zero or one argument(s)." end end def pass(custom) _wrap_assertion { begin assert !custom.matches?(@object), @message || custom.failure_message end } end def method_missing(name, *args, &block) # This will make raise call Kernel.raise, and self.raise call _raise. return _raise(*args, &block) if name == :raise if @object.respond_to?("#{name}?") assert_block("#{name}? expected to be false. #{@message}") { not @object.__send__("#{name}?", *args) } else if @object.respond_to?(name) assert_block("#{name} expected to be false. #{@message}") { not @object.__send__("#{name}", *args) } else super end end end end class CustomShould attr_accessor :object def initialize(obj) self.object = obj end def failure_message "#{self.class.name} failed" end def matches?(*args, &block) assumptions(*args, &block) true end def assumptions(*args, &block) raise NotImplementedError, "you need to supply a #{self.class}#matches? method" end end end class Test::Spec::TestCase attr_reader :testcase attr_reader :name attr_reader :position module InstanceMethods def setup # :nodoc: $TEST_SPEC_TESTCASE = self super call_methods_including_parents(:setups) end def teardown # :nodoc: super call_methods_including_parents(:teardowns, :reverse) end def before_all call_methods_including_parents(:before_all) end def after_all call_methods_including_parents(:after_all, :reverse) end def initialize(name) super name # Don't let the default_test clutter up the results and don't # flunk if no tests given, either. throw :invalid_test if name.to_s == "default_test" end def position self.class.position end def context(*args) raise Test::Spec::DefinitionError, "context definition is not allowed inside a specify-block" end alias :describe :context private def call_methods_including_parents(method, reverse=false, klass=self.class) return unless klass if reverse klass.send(method).each { |s| instance_eval(&s) } call_methods_including_parents(method, reverse, klass.parent) else call_methods_including_parents(method, reverse, klass.parent) klass.send(method).each { |s| instance_eval(&s) } end end end module ClassMethods attr_accessor :count attr_accessor :name attr_accessor :position attr_accessor :parent attr_accessor :setups attr_accessor :teardowns attr_accessor :before_all attr_accessor :after_all # old-style (RSpec <1.0): def context(name, superclass=Test::Unit::TestCase, klass=Test::Spec::TestCase, &block) (Test::Spec::CONTEXTS[self.name + "\t" + name] ||= klass.new(name, self, superclass)).add(&block) end def xcontext(name, superclass=Test::Unit::TestCase, &block) context(name, superclass, Test::Spec::DisabledTestCase, &block) end def specify(specname, &block) raise ArgumentError, "specify needs a block" if block.nil? self.count += 1 # Let them run in order of definition define_method("test_spec {%s} %03d [%s]" % [name, count, specname], &block) end def xspecify(specname, &block) specify specname do @_result.add_disabled(specname) end end def setup(&block) setups << block end def teardown(&block) teardowns << block end def shared_context(name, &block) Test::Spec::SHARED_CONTEXTS[self.name + "\t" + name] << block end def behaves_like(shared_context) if Test::Spec::SHARED_CONTEXTS.include?(shared_context) Test::Spec::SHARED_CONTEXTS[shared_context].each { |block| instance_eval(&block) } elsif Test::Spec::SHARED_CONTEXTS.include?(self.name + "\t" + shared_context) Test::Spec::SHARED_CONTEXTS[self.name + "\t" + shared_context].each { |block| instance_eval(&block) } else raise NameError, "Shared context #{shared_context} not found." end end alias :it_should_behave_like :behaves_like # new-style (RSpec 1.0+): alias :describe :context alias :describe_shared :shared_context alias :it :specify alias :xit :xspecify def before(kind=:each, &block) case kind when :each setup(&block) when :all before_all << block else raise ArgumentError, "invalid argument: before(#{kind.inspect})" end end def after(kind=:each, &block) case kind when :each teardown(&block) when :all after_all << block else raise ArgumentError, "invalid argument: after(#{kind.inspect})" end end def init(name, position, parent) self.position = position self.parent = parent if parent self.name = parent.name + "\t" + name else self.name = name end self.count = 0 self.setups = [] self.teardowns = [] self.before_all = [] self.after_all = [] end end @@POSITION = 0 def initialize(name, parent=nil, superclass=Test::Unit::TestCase) @testcase = Class.new(superclass) { include InstanceMethods extend ClassMethods } @@POSITION = @@POSITION + 1 @testcase.init(name, @@POSITION, parent) end def add(&block) raise ArgumentError, "context needs a block" if block.nil? @testcase.class_eval(&block) self end end (Test::Spec::DisabledTestCase = Test::Spec::TestCase.dup).class_eval do alias :test_case_initialize :initialize def initialize(*args, &block) test_case_initialize(*args, &block) @testcase.instance_eval do alias :test_case_specify :specify def specify(specname, &block) test_case_specify(specname) { @_result.add_disabled(specname) } end alias :it :specify end end end class Test::Spec::Disabled < Test::Unit::Failure # :nodoc: def initialize(name) @name = name end def single_character_display "D" end def short_display @name end def long_display @name + " is disabled" end end class Test::Spec::Empty < Test::Unit::Failure # :nodoc: def initialize(name) @name = name end def single_character_display "" end def short_display @name end def long_display @name + " is empty" end end # Monkey-patch test/unit to run tests in an optionally specified order. module Test::Unit # :nodoc: class TestSuite # :nodoc: undef run def run(result, &progress_block) sort! yield(STARTED, name) @tests.first.before_all if @tests.first.respond_to? :before_all @tests.each do |test| test.run(result, &progress_block) end @tests.last.after_all if @tests.last.respond_to? :after_all yield(FINISHED, name) end def sort! @tests = @tests.sort_by { |test| test.respond_to?(:position) ? test.position : 0 } end def position @tests.first.respond_to?(:position) ? @tests.first.position : 0 end end class TestResult # :nodoc: # Records a disabled test. def add_disabled(name) notify_listeners(FAULT, Test::Spec::Disabled.new(name)) notify_listeners(CHANGED, self) end end end # Hide Test::Spec interna in backtraces. module Test::Unit::Util::BacktraceFilter # :nodoc: TESTSPEC_PREFIX = __FILE__.gsub(/spec\.rb\Z/, '') # Vendor plugins like to be loaded several times, don't recurse # infinitely then. unless method_defined? "testspec_filter_backtrace" alias :testspec_filter_backtrace :filter_backtrace end def filter_backtrace(backtrace, prefix=nil) if prefix.nil? testspec_filter_backtrace(testspec_filter_backtrace(backtrace), TESTSPEC_PREFIX) else testspec_filter_backtrace(backtrace, prefix) end end end #-- Global helpers class Object def should(*args) case args.size when 0 Test::Spec::Should.new(self) when 1 Test::Spec::Should.new(self).pass(args.first) else raise ArgumentError, "Object#should takes zero or one argument(s)." end end end module Kernel def context(name, superclass=Test::Unit::TestCase, klass=Test::Spec::TestCase, &block) # :doc: (Test::Spec::CONTEXTS[name] ||= klass.new(name, nil, superclass)).add(&block) end def xcontext(name, superclass=Test::Unit::TestCase, &block) # :doc: context(name, superclass, Test::Spec::DisabledTestCase, &block) end def shared_context(name, &block) Test::Spec::SHARED_CONTEXTS[name] << block end alias :describe :context alias :xdescribe :xcontext alias :describe_shared :shared_context private :context, :xcontext, :shared_context private :describe, :xdescribe, :describe_shared end
require 'test_helper' module Mirrors class MethodMirrorTest < MiniTest::Test def setup @cm = Mirrors.reflect(MethodSpecFixture) @scm = Mirrors.reflect(SuperMethodSpecFixture) @b64 = Mirrors.reflect(Base64).instance_method(:encode64) @ins = Mirrors.reflect(String).instance_method(:inspect) super end def test_source_location @f = MethodSpecFixture m = MethodSpecFixture.instance_method(:source_location) @m = Mirrors.reflect(m) file = Mirrors.reflect(FileMirror::File.new(@f.new.source_location[0])) assert_equal(file, @m.file) assert_equal(@f.new.source_location[1] - 2, @m.line) assert_equal(@f.new.source_location[2], @m.name.to_s) assert_equal(@f.new.source_location[3].name, @m.defining_class.name) assert_includes(@m.source, '[__FILE__, __LINE__, __method__.to_s, self.class]') end def test_source # defined in C; source not available. we want nil. assert_nil(@ins.source) assert_match(/def encode64/, @b64.source) end def test_comment # defined in C; commend not available. we want nil. assert_nil(@ins.comment) assert_match(/#/, @b64.comment) end def test_bytecode assert_nil(@ins.bytecode) assert_match(/local table/, @b64.bytecode) end def test_sexp assert_nil(@ins.sexp) assert_equal(:program, @b64.sexp[0]) end def test_super_method refute(@scm.instance_method(:not_inherited).super_method) s1 = @cm.instance_method(:shadow_with_super) s2 = @scm.instance_method(:shadow_with_super) assert_equal(s1, s2.super_method) assert(s2.calls_super?) refute(s1.calls_super?) s1 = @cm.instance_method(:shadow_without_super) s2 = @scm.instance_method(:shadow_without_super) assert_equal(s1, s2.super_method) refute(s2.calls_super?) refute(s1.calls_super?) a = Mirrors.reflect(MethodSpecFixture::A) b = Mirrors.reflect(MethodSpecFixture::B) am = a.instance_method(:shadow) bm = b.instance_method(:shadow) assert_equal(am, bm.super_method) refute(am.super_method) acm = a.class_method(:class_shadow) bcm = b.class_method(:class_shadow) # NOTE: it feels like it makes sense for this to resolve as above, # but singleton classes are kind of tricky, and it only *really* # applies once the module is included elsewhere. refute(bcm.super_method) refute(acm.super_method) end def test_arguments m = Mirrors.reflect(method(:method_b)) assert_equal(%w(a b bb args block), m.arguments) assert_equal("block", m.block_argument) assert_equal(%w(a), m.required_arguments) assert_equal(%w(b bb), m.optional_arguments) assert_equal('args', m.splat_argument) end def test_public_method m = @cm.instance_method(:method_p_public) assert(m.public?) refute(m.protected?) refute(m.private?) assert_equal(:public, m.visibility) end def test_protected_method m = @cm.instance_method(:method_p_protected) refute(m.public?) assert(m.protected?) refute(m.private?) assert_equal(:protected, m.visibility) end def test_private_method m = @cm.instance_method(:method_p_private) refute(m.public?) refute(m.protected?) assert(m.private?) assert_equal(:private, m.visibility) end def test_method_included_from_instance method_mirror = Mirrors.reflect(ObjectIncludeFixture.new.method(:method_from_dynamic_include)) assert(method_mirror.public?) assert_equal(method_mirror.defining_class.reflectee, DYNAMIC_INCLUDE) end private def method_b(a, b = 1, bb = 2, *args, &block) to_s super end end end
class AddAttachmentsToProjects < ActiveRecord::Migration def change add_column :projects, :attachments, :json end end
module Controllers RSpec.describe Front do class TestController include Controllers::Base end let(:active_controller) { TestController.new } let(:input) { double("Input").as_null_object } let(:screen) { double("Screen").as_null_object } let(:screen_rect) { Rect.new(x: 0, y: 0, width: 50, height: 30) } subject { Front.new } before(:each) do allow(subject).to receive(:input).and_return(input) allow(subject).to receive(:screen).and_return(screen) allow(screen).to receive(:rect).and_return(screen_rect) end describe "#setup" do it "raises error if the screen is < 50 cols" do allow(screen).to receive(:rect).and_return(Rect.new(width: 49, height: 30)) expect(screen).to receive(:setup) expect(screen).to receive(:shutdown) expect do subject.setup end.to raise_error("This game is meant to be played on a screen at minimum 50x30") end it "raises error if the screen is < 30 lines" do allow(screen).to receive(:rect).and_return(Rect.new(width: 50, height: 29)) expect do subject.setup end.to raise_error("This game is meant to be played on a screen at minimum 50x30") end it "raises an error if no controller is set" do expect(screen).to receive(:setup) expect(screen).to receive(:shutdown) expect do subject.setup end.to raise_error("No active controller specified") end it "calls the setup function of the set controller" do expect(active_controller).to receive(:setup) subject.set_controller(active_controller) expect do subject.setup end.not_to raise_error end end describe "#set_controller" do it "sets the front_controller, input, and screen of the new controller" do subject.set_controller(active_controller) expect(active_controller.front_controller).to eq(subject) expect(active_controller.input).to eq(input) expect(active_controller.screen).to eq(screen) end end describe "#play" do before(:each) do allow(input).to receive(:shutdown?).and_return(true) allow(screen).to receive(:shutdown?) allow(subject).to receive(:puts) subject.set_controller(active_controller) subject.setup end it "calls the input, controller, and screen game loop" do expect(input).to receive(:game_loop) expect(active_controller).to receive(:game_loop) expect(screen).to receive(:game_loop) subject.play end it "shutsdown the controller and screen when something raises an error" do allow(input).to receive(:game_loop).and_raise "Some error" expect(active_controller).to receive(:shutdown) expect(screen).to receive(:shutdown) expect do subject.play end.to raise_error("Some error") end it "receives a resize input message" end end end
# encoding: utf-8 class SrcPlant < ActiveRecord::Base belongs_to :input_by, :class_name => 'User' has_many :projects has_many :customers attr_accessible :name, :short_name, :phone, :fax, :address, :primary_contact, :primary_cell, :tech_contact, :tech_cell, :equip, :tech_ability, :customer_service, :production_capacity, :last_eval_date, :eval_summary, :employee_num, :revenue, :about_us, :sourced_product, :web, :quality_system, :email, :src_since, :main_product, :as => :role_new attr_accessible :name, :short_name, :phone, :fax, :address, :primary_contact, :primary_cell, :tech_contact, :tech_cell, :equip, :tech_ability, :customer_service, :production_capacity, :last_eval_date, :eval_summary, :employee_num, :revenue, :about_us, :sourced_product, :web, :quality_system, :email, :src_since, :active, :main_product, :as => :role_update validates :name, :presence => true, :uniqueness => true, :if => "active" validates :short_name, :presence => true, :uniqueness => true, :if => "active" validates :phone, :presence => true validates :fax, :presence => true validates :address, :presence => true validates :primary_contact, :presence => true validates :primary_cell, :presence => true validates :quality_system, :presence => true validates :equip, :presence => true validates :tech_ability, :presence => true validates :main_product, :presence => true scope :active_plant, where(:active => true) scope :inactive_plant, where(:active => false) end
class Cal #객체 이름은 대문자여야 해 attr_reader :v1, :v2 attr_writer :v1 @@_history = [] #클래스가 정의될 때 호출되는 배열. initialize가 불릴 때마다 기록할 것 def initialize(v1, v2) #루비가 자동으로 실행하는 초기화 함수. instance가 실행될 때 꼭 실행돼. 뒤에 오는 애는 받아오는 매개변수 p v1, v2 #initialize는 생성자. @v1 = v1 #@가 있는 변수는 instance 변수. 인스턴스에 소속된 모든 method에서 사용 가능. @v2 = v2 #@가 있으면, 그 instance 내 모든 method에서 접근 가능! end #@가 없는 변수는 method 안에서만 쓸 수 있는 지역변수 #@ 안 달고 내가 initialze에만 name을 초기화한다든지 하면, 이 initialize에서만 쓸 수 있게 되는 거. def add() result = @v1 + @v2 @@_history.push("add : #{v1} + #{v2} = #{result}") #push는 배열에 어떠한 값을 추가하는 method return result #샵 중괄호 해주면, 그 안에 있는 걸 변수로 인식하겠다는 뜻 end def subtract() result = @v1 - @v2 @@_history.push("subtract : #{v1} - #{v2} = #{result}") #push는 배열에 어떠한 값을 추가하는 method return result end def setV1(v) if v.is_a?(Integer) @v1 = v end end def getV1() return @v1 end def Cal.history() for item in @@_history #히스토리 배열 안에 든 걸 하나씩 꺼내오겠다 p item end end end class CalMultiply < Cal def multiply() result = @v1 * @v2 @@_history.push("multiply : #{v1} x #{v2} = #{result}") #push는 배열에 어떠한 값을 추가하는 method return result end end c1 = CalMultiply.new(10, 10) p c1.add() p c1.multiply() class CalDivide < CalMultiply def divide() result = @v1 / @v2 @@_history.push("divide : #{v1} / #{v2} = #{result}") #push는 배열에 어떠한 값을 추가하는 method return result end end c2 = CalDivide.new(20, 10) p CalDvide.history()
class TumblrManager BLOG="khanhluc2.tumblr.com" def initialize() Tumblr.configure do |config| config.consumer_key = ENV['TUMBLR_KEY'] config.consumer_secret = ENV['TUMBLR_SECRET'] end @client = Tumblr::Client.new end def getPost(id) post = @client.posts(BLOG, :id=>id); if post['blog'] return self.filterPost(post['posts'][0]) else return nil end end def getPosts(tag=nil, include_images=true, limit=nil) blog = @client.posts(BLOG, :tag=>tag, :limit=>limit) return self.filterPosts(blog['posts'], include_images) end def filterPost(post, include_images=true) require 'rails/html/sanitizer' require 'nokogiri' sanitizer = Rails::Html::FullSanitizer.new time = Time.at(post['timestamp']) data = { :id => post['id'], :type => post['type'], :format => post['format'], :timestamp => post['timestamp'], :date => time.strftime("%B %e, %Y"), :tags => post['tags'], :slug => post['slug'] } case post['type'] when "text" data[:body] = post['body'] data[:title] = sanitizer.sanitize(post['title']) html = Nokogiri::HTML(post['body']) img = html.css("img").first data[:main_image] = img['src'] if !include_images html.search(".//img").remove data[:body] = html.to_html end when "video" data[:body] = post['player'][2]['embed_code'] data[:title] = sanitizer.sanitize(post['caption']) data[:thumbnail_url] = post['thumbnail_url'] data[:main_image] = post['thumbnail_url'] end return data end def filterPosts(posts, include_images = true) data = [] posts.each do |post| data << self.filterPost(post, include_images) end return data end end
module Flipperable def flipper_id "#{self.class.name};#{id}" end def feature_enabled?(name) Flipper.enabled?(name, self) end def enable_feature(name) Flipper.enable(name, self) end def disable_feature(name) Flipper.disable(name, self) end def set_feature(name, state) if state enable_feature(name) else disable_feature(name) end end end
require 'rails_helper' # This spec was generated by rspec-rails when you ran the scaffold generator. # It demonstrates how one might use RSpec to specify the controller code that # was generated by Rails when you ran the scaffold generator. # # It assumes that the implementation code is generated by the rails scaffold # generator. If you are using any extension libraries to generate different # controller code, this generated spec may or may not pass. # # It only uses APIs available in rails and/or rspec-rails. There are a number # of tools you can use to make these specs even more expressive, but we're # sticking to rails and rspec-rails APIs to keep things simple and stable. # # Compared to earlier versions of this generator, there is very limited use of # stubs and message expectations in this spec. Stubs are only used when there # is no simpler way to get a handle on the object needed for the example. # Message expectations are only used when there is no simpler way to specify # that an instance is receiving a specific message. # # Also compared to earlier versions of this generator, there are no longer any # expectations of assigns and templates rendered. These features have been # removed from Rails core in Rails 5, but can be added back in via the # `rails-controller-testing` gem. RSpec.describe Api::V1::ArticlesController, type: :controller do # This should return the minimal set of attributes required to create a valid # Article. As you add validations to Article, be sure to # adjust the attributes here as well. let(:source) { FactoryBot.create(:source) } let(:article) { FactoryBot.create(:article, source_id: source.id) } let(:invalid_article) { Article.new } let(:valid_attributes) do { :title => 'New Title', :url => 'www.url.com', :source_id => source.id } end let(:invalid_attributes) do { :title => 'New Title', :url => 'www.url.com' } end describe 'GET #index' do it 'returns a success response' do get :index, params: {:source_id => source.id} expect(response).to be_success end end describe 'GET #show' do it 'returns a success response' do get :show, params: {:id => article.to_param, :source_id => source.id} expect(response).to be_success end end describe 'POST #create' do context 'with valid params' do it 'creates a new Article' do expect { post :create, params: valid_attributes }.to change(Article, :count).by(1) end it 'renders a JSON response with the new article' do post :create, params: valid_attributes expect(response).to have_http_status :created expect(response.content_type).to eq 'application/json' end end context 'with invalid params' do it 'renders a JSON response with errors for the new article' do post :create, params: invalid_attributes expect(response).to have_http_status :unprocessable_entity expect(response.content_type).to eq 'application/json' end end end describe 'PUT #update' do context 'with valid params' do let(:new_attributes) do { :title => 'Something Good', :url => 'www.url.com', :summary => 'something good happened', :source_id => source.id, :id => article.id } end it 'updates the requested article' do patch :update, params: new_attributes article.reload expect(article.title).to eq 'Something Good' expect(article.url).to eq 'www.url.com' expect(article.summary).to eq 'something good happened' end it 'renders a JSON response with the article' do article = FactoryBot.create(:article, source_id: source.id) put :update, params: new_attributes expect(response).to have_http_status :ok expect(response.content_type).to eq 'application/json' end end context 'with invalid params' do let(:bad_attributes) do { :url => 'FUUUUU', :source_id => source.id, :id => article.id } end it 'renders a JSON response with errors for the article' do patch :update, params: bad_attributes expect(response).to have_http_status :unprocessable_entity expect(response.content_type).to eq 'application/json' end end end describe 'DELETE #destroy' do it 'destroys the requested article' do article = Article.create! valid_attributes expect { delete :destroy, params: {id: article.id, source_id: source.id} }.to change(Article, :count).by(-1) end it 'renders a JSON no-content response' do article = Article.create! valid_attributes delete :destroy, params: {id: article.id, source_id: source.id} expect(response).to have_http_status :no_content end end end
require "rails_helper" RSpec.feature "User can create a page" do context "When a new page form is submitted" do scenario "new action displays the page's title and content" do title = "New Page" content = "New Page Content" visit pages_path within ".top-nav-bar" do click_link "Create Page" end fill_in "Title", with: title fill_in "Content", with: content click_button "Create Page" expect(page).to have_content(title) expect(page).to have_content(content) end end end
module Qubole::Commands describe Pig do describe "initialize" do it "sets correct command type" do command = Qubole::Commands::Pig.new command.command_type = 'PigCommand' end end end end
# require 'rails_helper' RSpec.describe Announcement, type: :model do it "has a working factory" do announcement = build :announcement expect(announcement.save).to be true end it "creates an announcement with a user" do announcement = create :announcement expect(announcement.user_id).not_to be nil end it "buils and invalid announcement and doesn't save it" do announcement = build :announcement, user: nil expect(announcement.save).to be false end it "validates that announcement has a valid title" do announcement = build :announcement, title: "" expect(announcement.save).to be false end it "validates that announcement has a valid body" do announcement = build :announcement, body: "" expect(announcement.save).to be false end end
module Views RSpec.describe Screen do # let(:ncurses) { double("FFI::NCurses").as_null_object } subject { Screen.new } describe "#rect" do it "returns the expected value" do expect(subject.rect.x).to eq(0) expect(subject.rect.y).to eq(0) expect(subject.rect.width).to eq(90) expect(subject.rect.height).to eq(35) end end context "a view" do let(:child_view) do instance_double("View::Base") end it "adds a childview correctly" do expect(subject.views.length).to eq(0) subject.addview(child_view) expect(subject.views.length).to eq(1) expect(subject.views.first).to be(child_view) end it "calls the shutdown when the view is removed" do expect(child_view).to receive(:shutdown) subject.addview(child_view) subject.removeview(child_view) end it "calls the child shutdown when the screen is shutdown" do expect(child_view).to receive(:shutdown) subject.addview(child_view) subject.shutdown end end end end
# frozen_string_literal: true require 'uri' require 'net/https' module RubyPushNotifications module FCM # Encapsulates a connection to the FCM service # Responsible for final connection with the service. # # @author Carlos Alonso class FCMConnection # @private The URL of the Android FCM endpoint # Credits: https://github.com/calos0921 - for this url change to FCM std FCM_URL = 'https://fcm.googleapis.com/fcm/send' # @private Content-Type HTTP Header string CONTENT_TYPE_HEADER = 'Content-Type' # @private Application/JSON content type JSON_CONTENT_TYPE = 'application/json' # @private Authorization HTTP Header String AUTHORIZATION_HEADER = 'Authorization' # Issues a POST request to the FCM send endpoint to # submit the given notifications. # # @param notification [String]. The text to POST # @param key [String]. The FCM sender id to use # (https://developer.android.com/google/fcm/fcm.html#senderid) # @param options [Hash] optional. Options for #post. Currently supports: # * url [String]: URL of the FCM endpoint. Defaults to the official FCM URL. # * open_timeout [Integer]: Number of seconds to wait for the connection to open. Defaults to 30. # * read_timeout [Integer]: Number of seconds to wait for one block to be read. Defaults to 30. # @return [FCMResponse]. The FCMResponse that encapsulates the received response def self.post(notification, key, options = {}) headers = { CONTENT_TYPE_HEADER => JSON_CONTENT_TYPE, AUTHORIZATION_HEADER => "key=#{key}" } url = URI.parse options.fetch(:url, FCM_URL) http = Net::HTTP.new url.host, url.port http.use_ssl = url.scheme == 'https' http.verify_mode = OpenSSL::SSL::VERIFY_NONE http.open_timeout = options.fetch(:open_timeout, 30) http.read_timeout = options.fetch(:read_timeout, 30) response = http.post url.path, notification, headers FCMResponse.new response.code.to_i, response.body end end end end
class Api::Issues::CreateOp class << self def execute(user, params) ::Issue.create!(issue_params(params)) do |issue| issue.author = user end end def allowed?(current_user, *) current_user.regular? end private def issue_params(params) params.slice(:title) end end end
class AddAddressToNotes < ActiveRecord::Migration def change add_column :notes, :latitude, :float add_column :notes, :longitude, :float add_column :notes, :address, :string end end
require 'rails_helper' RSpec.describe Favorite, type: :model do before do @book = Book.create(title: "title", author: "author", price: 5000, genre: 5, released_at: "2020-12-05", story: "story", icon: "icon_URL") @user= User.new(name: "name", introduce: "introduce", icon: "icon_URL", admin: false, email: "test@e.mail", password: "password") # @user.skip_confirmation! @user.save end it "is valid with a book_id and user_id" do favorite = Favorite.create(book_id: @book.id, user_id: @user.id) expect(favorite).to be_valid end it "is invalid without a book_id" do favorite = Favorite.create(user_id: @user.id) expect(favorite).not_to be_valid end it "is invalid without an user_id" do favorite = Favorite.create(book_id: @book.id) expect(favorite).not_to be_valid end it "is invalid if book doesn't exist" do favorite = Favorite.create(book_id: @book.id + 1, user_id: @user.id) expect(favorite).not_to be_valid end it "is invalid if user doesn't exist" do favorite = Favorite.create(book_id: @book.id, user_id: @user.id + 1) expect(favorite).not_to be_valid end end
require 'spec_helper' require 'date_time_precision' describe DateTimePrecision do context 'Constructors' do it 'has no precision for unspecified date' do d = Date.new expect(d.precision).to eq(DateTimePrecision::NONE) expect(d.year?).to be false dt = DateTime.new expect(dt.precision).to eq(DateTimePrecision::NONE) expect(dt.year?).to be false end it 'has no precision for nil values' do expect(nil.precision).to eq(DateTimePrecision::NONE) end it 'has year precision when only year is supplied' do d = Date.new(1982) expect(d.precision).to eq(DateTimePrecision::YEAR) expect(d.year?).to be true expect(d.month?).to be false expect(d.day?).to be false end it 'has month precision when year and month are supplied' do d = Date.new(1982, 11) expect(d.precision).to eq(DateTimePrecision::MONTH) expect(d.year?).to be true expect(d.month?).to be true expect(d.day?).to be false end it 'has day precision when year, month, and day are passed in' do dt = DateTime.new(1987,10,19) expect(dt.precision).to eq(DateTimePrecision::DAY) expect(dt.year?).to be true expect(dt.month?).to be true expect(dt.day?).to be true expect(dt.hour?).to be false end it 'has hour precision' do dt = DateTime.new(1970, 1, 2, 3) expect(dt.precision).to eq(DateTimePrecision::HOUR) expect(dt.year?).to be true expect(dt.month?).to be true expect(dt.day?).to be true expect(dt.hour?).to be true expect(dt.min?).to be false end it 'tracks which attributes were explicitly set separately from precision' do [Date.new(nil, 11, 12), DateTime.new(nil, 10, 11, nil), Time.mktime(nil, 12, 13, nil, 14)].each do |d| expect(d.decade?).to be false expect(d.century?).to be false expect(d.year?).to be false expect(d.month?).to be true expect(d.day?).to be true expect(d.hour?).to be false expect(d.min?).to be true if d.is_a? Time expect(d.precision).to eq(DateTimePrecision::NONE) end end it 'has max precision for fully specified dates/times' do # Time.new is an alias for Time.now [Time.new, Time.now, DateTime.now, Date.today].each do |t| expect(t.precision).to eq(t.class::MAX_PRECISION) end end it 'accepts nil values in the constructor' do expect(Date.new(nil).precision).to eq(DateTimePrecision::NONE) expect(Date.new(2000, nil).precision).to eq(DateTimePrecision::YEAR) expect(DateTime.new(2000, 1, nil).precision).to eq(DateTimePrecision::MONTH) expect(Time.mktime(2000, 1, 1, nil, nil).precision).to eq(DateTimePrecision::DAY) end end context 'Time Zones' do it 'should retain precision when switching to UTC' do expect(Time.mktime(2000).utc.precision).to eq(DateTimePrecision::YEAR) expect(Time.mktime(2000).gmtime.precision).to eq(DateTimePrecision::YEAR) end it 'should track precision when creating a date, time, or datetime in UTC' do expect(Time.utc(1945, 10).precision).to eq(DateTimePrecision::MONTH) expect(Time.gm(1945, 10).precision).to eq(DateTimePrecision::MONTH) expect(Date.utc(1945, 10).precision).to eq(DateTimePrecision::MONTH) expect(DateTime.utc(1945, 10).precision).to eq(DateTimePrecision::MONTH) end it 'should track precision when creating a time in the local timezone' do expect(Time.local(2004, 5, 6).precision).to eq(DateTimePrecision::DAY) end end context 'Parsing' do it 'should have second/frac precision when parsing a timestamp' do t = Time::parse('2000-2-3 00:00:00 UTC') expect(t.precision).to eq(DateTimePrecision::SEC) expect(t.year).to eq(2000) expect(t.month).to eq(2) expect(t.day).to eq(3) end it 'should have minute precision when seconds are not in the timestamp' do dt = DateTime::parse('2000-1-1 00:00 EST') # => Sat, 01 Jan 2000 00:00:00 -0500 expect(dt.precision).to eq(DateTimePrecision::MIN) expect(dt.year).to eq(2000) expect(dt.day).to eq(1) end it 'should have day precision wehn parsing into a Date object' do d = Date::parse('2000-1-1 00:00:00 EST') # => Sat, 01 Jan 2000 expect(d.precision).to eq(DateTimePrecision::DAY) end it 'should have month precision when day is not in the parsed string' do t = Time::parse('January 2000 UTC').utc # => Sat Jan 01 00:00:00 -0800 2000 expect(t.precision).to eq(DateTimePrecision::MONTH) expect(t.year).to eq(2000) expect(t.month).to eq(1) end end context 'strptime' do it 'should have day precision when day is specified in date string' do d = Date.strptime('02/09/1968', '%m/%d/%Y') expect(d.precision).to eq(DateTimePrecision::DAY) end it 'should have minute precision when extracting down to the minute' do dt = DateTime.strptime('2011-02-03 15:14:52','%Y-%m-%d %H:%M') expect(dt.precision).to eq(DateTimePrecision::MIN) end it 'should have second precision when extracting down to the second' do t = DateTime.strptime('2011-02-03 15:14:52','%Y-%m-%d %H:%M:%S') expect(t.precision).to eq(DateTimePrecision::SEC) end end context 'Addition' do it 'should default to max precision when adding or subtracting' do d = Date.new expect(d.precision).to eq(DateTimePrecision::NONE) d += 3 expect(d.precision).to eq(Date::MAX_PRECISION) d -= 2 expect(d.precision).to eq(Date::MAX_PRECISION) dt = DateTime.new expect(dt.precision).to eq(DateTimePrecision::NONE) dt += 3 expect(dt.precision).to eq(DateTime::MAX_PRECISION) dt -= 2 expect(dt.precision).to eq(DateTime::MAX_PRECISION) t = Time::parse('January 2000 UTC').utc expect(t.precision).to eq(DateTimePrecision::MONTH) t += 10 expect(t.precision).to eq(Time::MAX_PRECISION) t -= 8 expect(t.precision).to eq(Time::MAX_PRECISION) end end context 'Partial Matching' do it 'should match when differing only in day precision' do d1 = Date.new(2001,3,2) d2 = Date.new(2001,3) expect(d1.partial_match?(d2)).to be true expect(d2.partial_match?(d1)).to be true end end context 'Decades and Centuries' do it 'should have the proper precision when outputting decades or centuries' do no_date = Date.new full_date = Date.new(1853,10,10) century_date_time = DateTime.new(1853) century_date_time.precision = DateTimePrecision::CENTURY decade_time = Time.mktime(1853) decade_time.precision = DateTimePrecision::DECADE expect(full_date.decade).to eq(1850) expect(full_date.century).to eq(1800) expect(decade_time.decade).to eq(1850) expect(decade_time.century).to eq(1800) expect(century_date_time.decade).to eq(1850) expect(century_date_time.century).to eq(1800) expect(no_date.decade?).to be false expect(full_date.decade?).to be true expect(decade_time.decade?).to be true expect(century_date_time.decade?).to be false expect(no_date.century?).to be false expect(full_date.century?).to be true expect(decade_time.century?).to be true expect(century_date_time.century?).to be true end it 'properly handles negative years' do date_bce = Date.new(-531, 10, 5) expect(date_bce.decade).to eq(-530) expect(date_bce.century).to eq(-500) end end end
ActiveAdmin.register Subject do index do column :name column :initiatives_count default_actions end end
class WeatherService class << self def weather_forecast(lat, lng) response = conn.get('/data/2.5/onecall') do |req| req.params['lat'] = lat req.params['lon'] = lng req.params['units'] = 'imperial' end parse_data(response) end private def conn Faraday.new(url: 'http://api.openweathermap.org') do |req| req.params['appid'] = ENV['weather_api_key'] end end def parse_data(response) JSON.parse(response.body, symbolize_names: true) end end end
class PigLatinizer attr_accessor :phrase # def initialize(phrase) # @phrase = phrase # end def initialize end def to_pig_latin(phrase) words = phrase.split(/\W+/) pl_words = words.collect {|word| piglatinize(word) } pl_words.join(" ") end def piglatinize(word) vowels = ['a','e','i','o','u','A','E','I','O','U'] cons = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z', 'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','X','Y','Z'] pl_word = word temp_str = "" if cons.include?(pl_word.chr) while cons.include?(pl_word.chr) temp_str += pl_word.chr pl_word = pl_word.slice(1,pl_word.length) end pl_word + temp_str+ "ay" elsif (word =~ /[aeiouAEIOU]/) == 0 word + "way" end end end
module SwellBot class BotService def self.request( message, session, args = {} ) request = SwellBot.bot_routes.build_request( message, session, args[:scope], args[:params], reply_to_id: args[:reply_to_id], reply_mode: args[:reply_mode] ) request.save responses = SwellBot::Responder.build_response( request, (args[:response] || {}) ) responses.each do | response | response.save end [request].concat( responses ) end def self.respond( message, args = {} ) response_class = ( args.delete(:response_class) || 'SwellBot::BotResponse' ).constantize if args[:session].present? session = args.delete(:session) elsif args[:session_id].present? session = SwellBot::BotSession.find( args.delete(:session_id) ) else session = SwellBot::BotSession.where( user_id: (args.delete(:user_id) || args.delete(:user).try(:id)) ).last session ||= SwellBot::BotSession.create( user: args[:user] ) if args[:user].present? session ||= SwellBot::BotSession.create( user_id: args.delete(:user_id) ) if args[:user_id].present? end response = response_class.new( session: session, content: message, slug: SecureRandom.uuid ) response.attributes = args response.thread_id = response.reply_to.try(:thread_id) || response.reply_to.try(:id) response end def self.respond!( message, args = {} ) response = self.respond( message, args ) response.save response end end end
module Mars class Rover attr_reader :state CLOCKWISE = { 'N' => 'E', 'E' => 'S', 'S' => 'W', 'W' => 'N' } COUNTER_CLOCKWISE = CLOCKWISE.invert MOVES = { 'N' => [0, 1], 'S' => [0, -1], 'E' => [1, 0], 'W' => [-1, 0] } def initialize(x: 0, y: 0, direction: 'N', actions: '') @state = { x: x.to_i, y: y.to_i, direction: direction, actions: actions } end def on_plateau(plateau) @plateau = plateau self end def move state[:actions].split('').each do |action| do_move(action) end @state[:actions] = '' self end def to_s "#{state[:x]} #{state[:y]} #{state[:direction]}" end private def do_move(action) turn_left if action == 'L' turn_right if action == 'R' move_forward if action == 'M' end def turn_left @state[:direction] = COUNTER_CLOCKWISE[state[:direction]] end def turn_right @state[:direction] = CLOCKWISE[state[:direction]] end def move_forward x, y = MOVES[state[:direction]] new_x = state[:x] + x new_y = state[:y] + y if @plateau.nil? or @plateau.not_occupied?(new_x, new_y) @state[:x] = new_x @state[:y] = new_y end end end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :task_users has_many :tasks, through: :task_users, dependent: :destroy has_many :events, dependent: :destroy extend ActiveHash::Associations::ActiveRecordExtensions belongs_to :prefecture with_options presence: true do validates :nickname validates :gender_id validates :hobby validates :comment validates :age validates :prefecture_id validates :city validates :address end has_many :user_events has_many :events, through: :user_events has_many :room_users has_many :rooms, through: :room_users has_many :messages end
require File.expand_path('../boot', __FILE__) require 'rails/all' # Need to require this so we can configure it in the Application class. require "rack-cas" Bundler.require(*Rails.groups) module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true # Set the root URL of the CAS server (e.g. CASinoApp) in such a way that the entire application # (including the login_url method/helper) can get access to it via Rails.application.cas_server_url # The CAS_SERVER_URL environment variable, in turn, is contained within the .env file that is kept # out of Git for privacy reasons (https://github.com/bkeepers/dotenv). @cas_server_url = ENV["CAS_SERVER_URL"] # Configure rack-cas to know about the CAS server root URL so that it knows where to # re-direct browser to for authentication config.rack_cas.server_url = @cas_server_url end end
require_relative 'chain' module Media class Filter class Graph attr_reader :chains def initialize(args={}, &block) @chains = args.fetch(:chains, []) block.arity < 1 ? instance_eval(&block) : block.call(self) if block_given? end def to_s chains.join('; ') end def add_chain(&block) Filter::Chain.new(&block).tap {|chain| chains << chain } end alias_method :chain, :add_chain end end end
class AddFurtherInfoToTravelPlans < ActiveRecord::Migration[5.0] def change add_column :travel_plans, :further_information, :text add_column :travel_plans, :acceptable_classes, :integer, null: false, index: true end end
require 'rails_helper' RSpec.describe User, type: :model do it 'has a valid factory' do expect(build(:user)).to be_valid end describe 'ActiveModel validations' do it { expect validate_presence_of(:email) } it { expect validate_uniqueness_of(:email) } it { expect validate_length_of(:password) } it { expect validate_presence_of(:password) } it { expect validate_presence_of(:password_confirmation) } it { expect validate_confirmation_of(:password_confirmation) } it { expect validate_presence_of(:first_name) } it { expect validate_presence_of(:last_name) } end end
class ServerSerializer < ActiveModel::Serializer attributes :id, :name, :url, :ip, :status, :created_at, :updated_at end
module Admin class BaseController < ApplicationController before_action :authenticate_user! before_action :authorize_user! layout 'application_admin' rescue_from Pundit::NotAuthorizedError, with: :handle_not_authorized private def authorize_user! authorize :admin, :show? end def handle_not_authorized redirect_to(root_path, notice: "You are not authorized to view this area") end end end
class Helpful < ActiveRecord::Base default_value_for(:source) { Source["user"] } NotHelpfulError = Class.new StandardError # == Constants NO_VALUE = -1 YES_VALUE = 1 # == Associations belongs_to :owner, :polymorphic => true belongs_to :user belongs_to :anonymous_token belongs_to :source # == Named scopes named_scope :yes, :conditions => { :value => YES_VALUE } named_scope :no, :conditions => { :value => NO_VALUE } # == Filter chain # # === Validations validates_inclusion_of :value, :in => [NO_VALUE, YES_VALUE] validates_presence_of :source # === Callbacks after_save :update_indices_and_associations class << self def create_or_update(owner, user, token, is_helpful = true) if user.blank? && token.blank? raise NotHelpfulError, "no user or token specified" end # KML commenting this out for now pending review of anti-fraud logic #if token && token.user != user # raise NotHelpfulError, "user token mismatch" #end if helpful = find_existing(owner, user, token) raise NotHelpfulError, "user mismatch" if helpful.user && helpful.user != user helpful.user = user unless user.blank? else helpful = Helpful.new :owner => owner, :user => user, :anonymous_token => token, :anonymous_token_value => token.value end helpful.value = is_helpful ? YES_VALUE : NO_VALUE helpful.save! helpful end def find_existing(owner, user, token) raise NotHelpfulError, "owner is blank" if owner.blank? if user.blank? && token.blank? raise NotHelpfulError, "user and token are blank" end helpful = Helpful.find_by_owner_id_and_owner_type_and_user_id owner.id, owner.class.name, user.id unless user.blank? return helpful if helpful helpful = Helpful.find_by_owner_id_and_owner_type_and_anonymous_token_value owner.id, owner.class.name, token.value unless token.blank? if helpful && helpful.user && helpful.user != user # two scenarios, a) user is nil or b) helpful.user was nil # this lookup validates both, that is, looks up for a nil user (not logged in user) \ # and same anonymous token helpful = Helpful.find :first, :conditions => { :owner_id => owner.id, :owner_type => owner.class.name, :anonymous_token_value => token.value, :user_id => nil } end helpful end end def helpful=(bool) self.value = bool ? YES_VALUE : NO_VALUE end def yes! write_attribute :value, YES_VALUE end def no! write_attribute :value, NO_VALUE end def yes? value == YES_VALUE end def no? value == NO_VALUE end private def update_indices_and_associations if owner_type == 'Review' EndecaEvent.fire! owner, :replace owner.product.update_helpful_count owner.user.update_helpful_count elsif owner_type == "Qa::Answer" owner.user.update_helpful_count end owner.update_helpful_count end end
class ArticlesController < ApplicationController before_action :set_article, only: [:show, :edit, :update, :destroy] def index if can? :show, Article @articles = Article.order(created_at: :desc) else redirect_to root_path, notice: 'Du kannst keine Artikel ansehen' end end def show if cannot? :show, Article redirect_to root_path, notice: 'Du kannst diesen Artikel nicht ansehen' end end def new if can? :create, Article @article = Article.new else redirect_to root_path, notice: 'Du kannst keine Artikel erstellen' end end def edit if cannot? :update, Article redirect_to root_path, notice: 'Du kannst diesen Artikel nicht bearbeiten' end end def create if can? :create, Article @article = Article.new(article_params) if @article.save redirect_to @article, notice: 'Artikel wurde erfolgreich verfasst.' else render :new end else redirect_to root_path, notice: 'Du kannst keine Artikel erstellen' end end def update if can? :update, Article if @article.update(article_params) redirect_to @article, notice: 'Article was successfully updated.' else render :edit end else redirect_to root_path, notice: 'Du kannst diesen Artikel nicht bearbeiten' end end def destroy if can? :destroy, Article @article.destroy redirect_to articles_url, notice: 'Article was successfully destroyed.' else redirect_to root_path, notice: 'Du kannst diesen Artikel nicht löschen' end end private def set_article @article = Article.find(params[:id]) end def article_params params.require(:article).permit(:title, :summary, :content, :member_id) end end
require 'fb_graph' class FacebookController < ApplicationController def upload_file uploaded_file = params[:uploadedFile] name = uploaded_file.original_filename path = "/Users/nvenky/#{name}" File.open(path, "wb") { |f| f.write(uploaded_file.read) } send_message_to_online_friends get_user(params[:access_token]).name render :text => "File has been uploaded successfully" end def upload uploaded_file_name = params[:uploaded_file_name] fb_user = get_user(params[:access_token]) user = User.find_by_facebook_id fb_user.identifier Image.new({:user => user, :file_name => uploaded_file_name}).save! p 'Uploaded Image, sending message to friends' send_message_to_online_friends user.name render :text => "File has been uploaded successfully" end def find_online_friends access_token = params[:access_token] user = get_user access_token min_online_friends_for_testing = 5 friends = user.friends.select{|friend| is_online?(friend.raw_attributes[:id], min_online_friends_for_testing-=1)} .collect{|friend| {:id => friend.raw_attributes[:id], :name => friend.raw_attributes[:name]}} json = {:id => user.id, :data => friends} render :json => json end def register_user_online fb_user = get_user params[:access_token] registration_id = params[:registration_id] user = User.find_by_facebook_id(fb_user.identifier) if user.nil? User.new({:facebook_id => fb_user.identifier, :name => fb_user.name, :device_registration_id => registration_id}).save! else user.device_registration_id = registration_id user.save! end render :json => {'status' => 'Success'} end #private def get_user(access_token) FbGraph::User.me(access_token).fetch end def is_online?(id, min) min >=0 || online_users.has_key?(id) end end
class Model < ActiveRecord::Base belongs_to :piece scope :active, -> { where(archived: false) } scope :archived, -> { where(archived: true) } def all_pieces Piece.where(model: self) end def pieces all_pieces.where(archived: false) end def sizes pieces.map(&:size) end def archive self.archived = true self.save end def unarchive self.archived = false self.save end end
class PasswordResetsController < ApplicationController skip_before_action :authenticate_user def forgot if params[:email].blank? return render json: {error: 'Please provide a valid email address.'} end user_email = params[:email].downcase.strip user = User.find_by(email: user_email) if user.present? user.generate_password_token! user.send_password_reset_email render json: { status: 'ok' }, status: :ok else render json: { error: ['Email address provided is not valid. Please try again.'] }, status: :not_found end end def reset token = params[:token].to_s if params[:email].blank? render json: { error: 'Token not provided.' } end user = User.find_by(reset_password_token: token) if user.present? && user.password_token_valid? if user.reset_password!(params[:password]) render json: { status: 'ok' }, status: :ok else render json: { error: user.errors.full_messages }, status: :unprocessable_entity end else render json: { error: ['Invalid link or link has expired.'] }, status: :not_found end end end
class Product < ApplicationRecord has_attached_file :product_image, styles: { product_index: "250x300>", product_show: "325x475>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :product_image, content_type: /\Aimage\/.*\z/ end
require 'rubygems' require 'yaml' require 'ap' class Konsole def initialize(title) @session_id = `qdbus org.kde.konsole /Konsole newSession`.strip! self.title = title end def title=(title) system %{qdbus org.kde.konsole /Sessions/#{@session_id} setTitle 1 "#{title}"} end def commands(cmds) cmds.each {|cmd| command(cmd)} end def command(cmd) send_text(cmd, "\n") end def send_text(*parts) parts.each {|text| system %{qdbus org.kde.konsole /Sessions/#{@session_id} sendText '#{text}'} } end def self.prev_tab system "qdbus org.kde.konsole /Konsole prevSession" end end class Kassets CONFIG_FILE = '.kassets' def run tabs.each {|hash| Konsole.new(hash.keys.first).commands(hash.values.first) } open_first_tab end def tabs config['tabs'] end def open_first_tab (tabs.count - 1).times { Konsole.prev_tab } end private def config @config ||= YAML.load_file(locate_config) end def locate_config File.join(File.dirname(__FILE__), CONFIG_FILE) end end Kassets.new.run
class Api::ApplicationController < ActionController::API include ActionController::Caching include ApiErrorsHandlers include Authorization def execute_operation(op, *args) if op.allowed?(current_user, *args) result = op.execute(*args) if block_given? yield(result) else result end else raise Auth::ForbiddenError.new end end def respond_with(model, serializer: nil, status: 200) if model.respond_to?(:errors) && model.errors.any? render status: 422, json: model.errors else render json: serializer ? serializer.to_json(model) : model, status: status end end end
class CreateUserizations < ActiveRecord::Migration def change create_table :userizations do |t| t.references :video, index: true t.references :user, index: true t.timestamps null: false end add_foreign_key :userizations, :videos add_foreign_key :userizations, :users end end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'chain-reactor/version' Gem::Specification.new do |gem| gem.name = "chain-reactor" gem.version = ChainReactor::VERSION gem.license = 'MIT' gem.authors = ["Jon Cairns"] gem.email = ["jon@joncairns.com"] gem.description = %q{Trigger events across networks using TCP/IP sockets} gem.summary = %q{A TCP/IP server that triggers code on connection} gem.homepage = "http://github.com/joonty/chain-reactor" gem.add_runtime_dependency 'rake', '~> 0.8.7' gem.add_runtime_dependency 'main', '~> 5.1.1' gem.add_runtime_dependency 'json', '~> 1.7.5' gem.add_runtime_dependency 'dante', '~> 0.1.5' gem.add_runtime_dependency 'log4r', '~> 1.1.10' gem.add_runtime_dependency 'rdoc', '~> 3.12' gem.add_runtime_dependency 'xml-simple', '~> 1.1.2' gem.add_development_dependency 'test-unit', '~> 2.5.3' gem.add_development_dependency 'mocha', '~> 0.13.1' gem.files = `git ls-files`.split($/) gem.executables = %w(chain-reactor chain-reactor-client) gem.test_files = `git ls-files -- test/test_`.split($/) gem.require_paths = ["lib"] end
class Booking < ApplicationRecord belongs_to :user belongs_to :camping_car end
require 'pry' def dictionary dictionary = { "hello" => 'hi', "to" => '2', "two" => '2', "too" => '2', "for, four" => '4', 'be' => 'b', 'you' => 'u', "at" => "@", "and" => "&" } end def word_substituter(tweet) new_array = tweet.split new_array.each_with_index do |word, index| if dictionary.keys.include?(word) new_array[index] = dictionary[word] else word end end.join(' ') end def bulk_tweet_shortener(array) end def selective_tweet_shortener(tweet) # does not shorten tweets that are less than 130 characters if tweet.length > 130 word_substituter(tweet) end end def shortened_tweet_truncator(tweet) # truncates tweets over 140 characters after shortening # does not shorten tweets shorter than 140 characters. end
module Fog module Compute class ProfitBricks class Real # Blacklists the user, disabling them. # The user is not completely purged, therefore if you anticipate needing to create # a user with the same name in the future, we suggest renaming the user before you delete it. # # ==== Parameters # * user_id<~String> - UUID of the user # # ==== Returns # * response<~Excon::Response> - No response parameters # (HTTP/1.1 202 Accepted) # # {ProfitBricks API Documentation}[https://devops.profitbricks.com/api/cloud/v4/#delete-a-user] def delete_user(user_id) request( :expects => [202], :method => 'DELETE', :path => "/um/users/#{user_id}" ) end end class Mock def delete_user(user_id) response = Excon::Response.new response.status = 202 if user = data[:users]['items'].find do |usr| usr['id'] == user_id end else raise Fog::Errors::NotFound, "The requested resource could not be found" end response end end end end end
class BlockFieldsController < ApplicationController before_action :authenticate_user! before_action :set_block_field, only: [:show, :edit, :update, :destroy] # GET /block_fields def index @block_fields = BlockField.all end # GET /block_fields/1 def show end # GET /block_fields/new def new @block_field = BlockField.new end # GET /block_fields/1/edit def edit end # POST /block_fields def create @block_field = BlockField.new(block_field_params) respond_to do |format| if @block_field.save format.html { redirect_to @block_field, notice: t(:operation_successful) } else format.html { render :new } end end end # PATCH/PUT /block_fields/1 def update respond_to do |format| if @block_field.update(block_field_params) format.html { redirect_to @block_field, notice: t(:operation_successful) } else format.html { render :edit } end end end # DELETE /block_fields/1 def destroy @block_field.destroy respond_to do |format| format.html { redirect_to block_fields_url, notice: t(:operation_successful) } end end private # Use callbacks to share common setup or constraints between actions. def set_block_field @block_field = BlockField.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def block_field_params params.require(:block_field).permit(:name, :text, :weight, :data_type, :marker) end end
# # Copyright:: Copyright (c) 2012 Opscode, Inc. # 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. # require 'singleton' module Omnibus class Config include Singleton def self.default_values @default_values ||= [] end def self.configurable(name, opts={}) attr_accessor name default_values << [name, opts[:default]] if opts[:default] end def reset! self.class.default_values.each do |option, default| send("#{option}=", default) end end def initialize reset! end configurable :cache_dir, :default => "/var/cache/omnibus/cache" configurable :source_dir, :default => "/var/cache/omnibus/src" configurable :build_dir, :default => "/var/cache/omnibus/build" configurable :package_dir, :default => "/var/cache/omnibus/pkg" configurable :install_dir, :default => "/opt/chef" configurable :use_s3_caching, :default => false configurable :s3_bucket configurable :s3_access_key configurable :s3_secret_key configurable :solaris_compiler end def self.config Config.instance end def self.configure yield config end end
# frozen_string_literal: true class CustomerSeeds def initialize(db) @db = db @city_ids = @db["SELECT * FROM GlobalConfig.Cities"].to_a.map { |city| city[:id] } end def run @city_ids.each do |city_id| 100.times do customer_id = create_customer() create_customer_address(customer_id, city_id) end end end def create_customer customer_params = { firstName: Faker::Name.first_name[0..49], lastName: Faker::Name.last_name[0..49], email: Faker::Internet.email[0..99], phoneNumber: Faker::PhoneNumber.phone_number[0..14], blocked: [0, 1].sample, } data_set = @db["INSERT INTO Clients.Customers (firstName, lastName, email, phoneNumber) VALUES (:firstName, :lastName, :email, :phoneNumber)", customer_params] data_set.insert end def create_customer_address(customer_id, city_id) addressParams = { addressOne: Faker::Address.street_address[0..99], addressTwo: Faker::Address.secondary_address[0..99], zipCode: Faker::Address.zip_code[0..4], description: Faker::Address.community[0..99], customerId: customer_id, cityId: city_id, } data_set = @db["INSERT INTO Clients.Addresses (addressOne, addressTwo, zipCode, description, customerId, cityId) VALUES (:addressOne, :addressTwo, :zipCode, :description, :customerId, :cityId)", addressParams] data_set.insert end end
class IntercodeSchema < GraphQL::Schema class NotAuthorizedError < GraphQL::ExecutionError attr_reader :current_user def self.from_error(error, message, **args) new(message, current_user: error.context[:current_user], **args) end def initialize(message, current_user:, **args) super(message, **args) @current_user = current_user end def message if current_user super else 'Not logged in' end end def code if current_user 'NOT_AUTHORIZED' else 'NOT_AUTHENTICATED' end end def to_h super.merge( 'extensions' => { 'code' => code, "current_user_id": current_user&.id } ) end end mutation(Types::MutationType) query(Types::QueryType) use GraphQL::Batch rescue_from ActiveRecord::RecordInvalid do |err, _obj, _args, _ctx, _field| raise GraphQL::ExecutionError.new( "Validation failed for #{err.record.class.name}: \ #{err.record.errors.full_messages.join(', ')}", extensions: { validationErrors: err.record.errors.as_json } ) end rescue_from ActiveRecord::RecordNotFound do |_err, _obj, _args, _ctx, field| type_name = field.type.unwrap.graphql_name if type_name == 'Boolean' raise GraphQL::ExecutionError, "Record not found while evaluating #{field.name}" end raise GraphQL::ExecutionError, "#{field.type.unwrap.graphql_name} not found" end rescue_from Liquid::SyntaxError do |err, _obj, _args, _ctx, _field| IntercodeSchema.log_error(err) raise GraphQL::ExecutionError.new( err.message, extensions: { backtrace: err.backtrace } ) end rescue_from CivilService::ServiceFailure do |err, _obj, _args, _ctx, _field| Rollbar.error(err) IntercodeSchema.log_error(err) raise GraphQL::ExecutionError.new( err.result.errors.full_messages.join(', '), extensions: { backtrace: err.backtrace } ) end # Catch-all for unhandled errors rescue_from StandardError do |err, _obj, _args, _ctx, _field| Rollbar.error(err) IntercodeSchema.log_error(err) raise GraphQL::ExecutionError.new( err.message, extensions: { backtrace: err.backtrace } ) end def self.log_error(err) backtrace = Rails.backtrace_cleaner.clean(err.backtrace) Rails.logger.error([err.message, *backtrace].join($INPUT_RECORD_SEPARATOR)) end def self.resolve_type(_abstract_type, object, _context) case object when MailingListsPresenter then Types::MailingListsType end end def self.object_from_id(node_id, ctx) end def self.id_from_object(object, type, ctx) end def self.unauthorized_object(error) # Add a top-level error to the response instead of returning nil: raise NotAuthorizedError.from_error( error, "An object of type #{error.type.graphql_name} was hidden due to permissions" ) end def self.unauthorized_field(error) # It should be safe to query for admin_notes even if you can't see them return nil if error.field.graphql_name == 'admin_notes' # Add a top-level error to the response instead of returning nil: raise NotAuthorizedError.from_error( error, "The field #{error.field.graphql_name} on an object of type #{error.type.graphql_name} \ was hidden due to permissions" ) end end IntercodeSchema.graphql_definition
class SessionCouncilman < ApplicationRecord belongs_to :meeting belongs_to :councilman # validate :hour_presents def hour_presents errors.add(:arrival, I18n.t('errors.messages.date.less_hour_presents')) if !arrival.nil? && arrival >= leaving end end
Rails.application.routes.draw do root to: 'users#index' resources :users, except: [:new, :edit] end
require 'spec_helper' describe JobList do describe '#new' do it "returns an instance of JobList object" do expect(JobList.new "a =>").to be_instance_of(JobList) end it "takes only 1 argument" do expect{JobList.new "a =>", "bad_arg"}.to raise_error(ArgumentError) end end describe '#jobs' do it "returns an empty sequence given no jobs" do job_list = JobList.new "" expect(job_list.jobs).to eql "" end it "returns the job when only given 1 job" do job_list = JobList.new "a =>\n" expect(job_list.jobs).to eql "a" end it "returns a sequence of jobs when there are no dependencies" do job_list = JobList.new "a =>\nb =>\nc =>\n" expect(job_list.jobs).to eql "abc" end it "returns a sequence where 'c' is before 'b' when 'b' is dependant on 'c'" do job_list = JobList.new "a =>\nb => c\nc =>\n" expect(job_list.jobs).to eql "acb" end it "returns a sequence where 'c' is before 'b', 'f' is before 'c', 'a' is before 'd', and 'b' is before 'e' when there are multiple dependencies" do job_list = JobList.new "a =>\nb => c\nc => f\nd => a\ne => b\nf =>\n" expect(job_list.jobs).to eql "afcbde" end context "job_id and dependancy_id are the same" do it "exits the application when a SelfDependancyError is raised" do expect{JobList.new "a => a\n"}.to raise_error(SystemExit) end it "outputs a message to stdout" do expect{ begin JobList.new "a => a\n" rescue SystemExit end }.to output("Sorry, a can't be dependant on itself\n").to_stdout end end context "jobs with circular dependencies" do it "exits the application when a CircularDependancyError is raised with a simple circular dependancy" do expect{JobList.new "a => b\nb => c\nc => a\n"}.to raise_error(SystemExit) end it "exits the application when a CircularDependancyError is raised with a longer circular dependancy" do expect{JobList.new "a =>\nb => c\nc => f\nd => a\ne =>\nf => b"}.to raise_error(SystemExit) end it "outputs the exception message to stdout" do expect{ begin JobList.new "a => b\nb => c\nc => a\n" rescue SystemExit end }.to output("Circular dependancy detected!\n").to_stdout end end end end
require 'slugify' require 'sec/firms/version' require 'sec/firms/helpers' require 'sec/firms/configuration' require 'sec/firms/downloader' require 'sec/firms/xml_parser' require 'sec/firms/firm_entry_parser' require 'sec/firms/firm_parser' require 'sec/firms/lists' module Sec module Firms class << self attr_writer :configuration end def self.configuration @configuration ||= Configuration.new end def self.configure yield(configuration) end end end
require_relative 'Player.rb' class Hero < Player def initialize(name, hitpoint, damage, rate_deflect) super(name, hitpoint, damage) @rate_deflect = rate_deflect end def take_hitpoint(damage) if rand < @rate_deflect puts "#{@name} deflects the attack" else @hitpoint -= damage end end end
require_relative '../spec_helper' describe docker_container('consul') do it { should exist } it { should be_running } end describe port(8301) do it { should be_listening.with('tcp') } end describe port(8400) do it { should be_listening.with('tcp6') } end describe port(8500) do it { should be_listening.with('tcp6') } end describe port(8600) do it { should be_listening.with('tcp6') } end describe command("docker exec -t consul consul members") do its(:stdout) { should match /alive/ } end describe command("docker exec -t consul consul info") do its(:stdout) { should match /server = true/ } its(:stdout) { should match /failed = 0/ } its(:stdout) { should_not match /failed = [1-9]/ } # there are 2 instances of failed, make sure neither > 0 its(:stdout) { should match /state = [Leader|Follower]/ } its(:stdout) { should_not match /state = Candidate/ } end
module Peramable extend Memorable, Findable def to_param name.downcase.gsub(' ', '-') end end
class CreateFolios < ActiveRecord::Migration def up create_table :folios do |t| t.integer :house_id, null: false t.integer :user_id t.string :state, default: "to_watch" t.boolean :visited, default: false t.string :email t.string :phone t.timestamps end add_index :folios, [ :house_id, :user_id ] # Moving dreams to folios Folio.skip_callback("save",:after,:send_create_mail) Folio.skip_callback("save",:after,:send_visit_mails) Dream.all.each do |d| if (d.user.nil? || d.house.nil?) d.destroy #cleanup of unused dreams next end Folio.create! user_id: d.user_id, house_id: d.house_id, state: "to_dig" end Visit.all.each do |v| if (v.user.nil? || v.house.nil?) v.destroy #cleanup of unused visits next end Folio.where(user_id: v.user_id, house_id: v.house_id) .first_or_initialize(user_id: v.user_id, house_id: v.house_id, state: "to_visit", visited: true) .save(validate: false) end Folio.set_callback("save",:after,:send_create_mail) Folio.set_callback("save",:after,:send_visit_mails) end def down drop_table :folios end end
# encoding: utf-8 execute "apt-get update" do action :nothing command "apt-get update" end packages = %w{gcc make build-essential bash vim git curl libfreetype6 libfreetype6-dev libfontconfig1 libfontconfig1-dev} packages.each do |pkg| package pkg do options "-o Dpkg::Options::='--force-confold' -f --force-yes" action [:install, :upgrade] version node[:versions][pkg] end end service 'apache2' do action :stop end Execute "gem install sass" do not_if "which sass" end template "/home/vagrant/.npmrc" do owner "vagrant" group "vagrant" mode 0644 source ".npmrc" end template "/home/vagrant/.bashrc" do owner "vagrant" group "vagrant" mode 0644 source ".bashrc" end template "/home/vagrant/.bash_profile" do owner "vagrant" group "vagrant" mode 0644 source ".bash_profile" end npm_global_pacages = %w{bower} npm_global_pacages.each do |npm_pkg| nodejs_npm npm_pkg end execute 'npm global package install' do command "su vagrant -l -c 'npm i -g node-gyp grunt-cli yo gulp mean-cli'" end
module Gravatarify # Provides the two available helpers: `gravatar_attrs` and `gravatar_tag`. # # The helper should be loaded as helper for your specific view framework: # # # e.g. for Sinatra # helpers Gravatarify::Helper # # # or include for Haml # Haml::Helpers.send(:include, Gravatarify::Helper) # module Helper include Gravatarify::Base # Helper method for HAML to return a neat hash to be used as attributes in an image tag. # # Now it's as simple as doing something like: # # %img{ gravatar_attrs(@user.mail, :size => 20) }/ # # This is also the base method for +gravatar_tag+. # # @param [String, #email, #mail, #gravatar_url] email a string or an object used # to generate to gravatar url for. # @param [Symbol, Hash] *params other gravatar or html options for building the resulting # hash. # @return [Hash] all html attributes required to build an +img+ tag. def gravatar_attrs(email, *params) url_options = Gravatarify::Utils.merge_gravatar_options(*params) options = url_options[:html] || {} options[:src] = gravatar_url(email, false, url_options) options[:width] = options[:height] = (url_options[:size] || 80) # customize size { :alt => '' }.merge!(options) # to ensure validity merge with :alt => ''! end # Takes care of creating an <tt><img/></tt>-tag based on a gravatar url, it no longer # makes use of any Rails helper, so is totally useable in any other library. # # @param [String, #email, #mail, #gravatar_url] email a string or an object used # to generate the gravatar url from # @param [Symbol, Hash] *params other gravatar or html options for building the resulting # image tag. # @return [String] a complete and hopefully valid +img+ tag. def gravatar_tag(email, *params) html_attrs = gravatar_attrs(email, *params).map { |key,value| "#{key}=\"#{CGI.escapeHTML(value.to_s)}\"" }.sort.join(" ") Gravatarify::Utils.make_html_safe_if_available("<img #{html_attrs} />"); end end end
# Our puppet plugin which contains the agent & device proxy classes used for hand off # TODO - Make broker properties open rather than rigid require "erb" require "net/ssh" # Root namespace for ProjectRazor module ProjectRazor::BrokerPlugin # Root namespace for Puppet Broker plugin defined in ProjectRazor for node handoff class Puppet < ProjectRazor::BrokerPlugin::Base include(ProjectRazor::Logging) def initialize(hash) super(hash) @plugin = :puppet @description = "PuppetLabs PuppetMaster" @hidden = false from_hash(hash) if hash end def agent_hand_off(options = {}) @options = options @options[:server] = @servers.first @options[:ca_server] = @options[:server] @options[:puppetagent_certname] ||= @options[:uuid].base62_decode.to_s(16) return false unless validate_options(@options, [:username, :password, :server, :ca_server, :puppetagent_certname, :ipaddress]) @puppet_script = compile_template init_agent(options) end def proxy_hand_off(options = {}) res = " @@vc_host { '#{options[:ipaddress]}': ensure => 'present', username => '#{options[:username]}', password => '#{options[:password]}', tag => '#{options[:vcenter_name]}', } " system("puppet apply --certname=#{options[:hostname]} --report -e \"#{res}\"") :broker_success end # Method call for validating that a Broker instance successfully received the node def validate_hand_off(options = {}) # Return true until we add validation true end def init_agent(options={}) @run_script_str = "" begin Net::SSH.start(options[:ipaddress], options[:username], { :password => options[:password], :user_known_hosts_file => '/dev/null'} ) do |session| logger.debug "Copy: #{session.exec! "echo \"#{@puppet_script}\" > /tmp/puppet_init.sh" }" logger.debug "Chmod: #{session.exec! "chmod +x /tmp/puppet_init.sh"}" @run_script_str << session.exec!("bash /tmp/puppet_init.sh") @run_script_str.split("\n").each do |line| logger.debug "puppet script: #{line}" end end rescue => e logger.error "puppet agent error: #{p e}" return :broker_fail end # set return to fail by default ret = :broker_fail # set to wait ret = :broker_wait if @run_script_str.include?("Exiting; no certificate found and waitforcert is disabled") # set to success (this meant autosign was likely on) ret = :broker_success if @run_script_str.include?("Finished catalog run") ret end def compile_template logger.debug "Compiling template" install_script = File.join(File.dirname(__FILE__), "puppet/agent_install.erb") contents = ERB.new(File.read(install_script)).result(binding) logger.debug("Compiled installation script:") logger.error install_script #contents.split("\n").each {|x| logger.error x} contents end def validate_options(options, req_list) missing_opts = req_list.select do |opt| options[opt] == nil end unless missing_opts.empty? false end true end end end
=begin #1 Repeat Yourself Write a method that takes 2 arguments, a string and a #positive integer, and prints the string as many times as the integer #indicates #PEDAC #Understand the problem :identify input/output #:make requirements explicit #:identify the rules #Mental Model the Problem #P # Write a method with 2 arguments, a string and an integer #it prints the string as many times as the given integer #I have what is going to be printed and how many times it is #name of method is repeat def repeat(string, integer) #my default for the arguments is (a,b), but considering someone may look at the code, I should #make the argument a little clearer integer.times do puts string end end repeat('Hello', 3) #2 Odd Write a method that takes a 1 integer argument, + - or 0 #method will return true if absolutel value is odd #assume the argument is valid integer value...no #odd? or #even? method calls allowed! =begin PEDAC P Understanding the Problem inputs- an integer as the input, could be positive negative or zero no use of #odd? or #even? method calls the method call will return true or false (boolean value) how to code for an absolute value? (.abs call!) how about zero? Zero has neither odd nor even value, how to code? #do we code at all, or can I create a condition where 0 is inclusive? #All we need to output is zero is false, so no special condition. E:xamples a number 2 goes through the method definition and output as even Edge Cases: negatives, so attend to absolute value in code Edge Cases: 0, attend to an argument 0 in code D:ata Structure a single integer, also output for a boolean can be puts We can use MOdulo % 2 for a remainder == 1 A:lgorithim method defintion arguments method defintiion parametns end of method variable inputs .abs method call for an absolute value covers negatives C:ode. def is_odd?(num) num.abs % 2 == 1 end puts is_odd?(2) puts is_odd?(5) puts is_odd?(-17) puts is_odd?(-8) puts is_odd?(0) puts is_odd?(7) #3 List of Digits Write a Method that takes on argument, #and returns a list of digits in the number #PEDAC #P:roblem - take a sincgle integer, and convert it to an array that consists of the list of digits in order #E:xamples # The number 1001 gets put through the method I make and it reutns "1", "0", "0", "1" #Data structure - our arguments begin as a single integer and get returned in an Array #Algorithim Convert the input to the output #The method definition digits would work on th einteger, hwoever digits returns the array with the lowest value first #digits will need modification fi I use it for the third item in the arguments given #How can I code a number like 7688431? #I can code it to remove and put numbers back in #I could take numbers out and put them back in using push? or .last to index[0], reversing a counter for each one? #I can find a method that works to reverse an array...like .reverse! #But remember, it must return a Boolean def digit_list(integer) return integer.digits.reverse end puts digit_list(12345) == [1, 2, 3, 4, 5] puts digit_list(7) == [7] puts digit_list(375290) == [3, 7, 5, 2, 9, 0] puts digit_list(444) == [4, 4, 4] #4 How Many? write a method that counts the number of occurances in the array vehicles = ['car', 'car', 'truck', 'car', 'SUV', 'truck', 'motorcycle', 'motorcycle', 'car', 'truck'] #The words in the array are case-sensitive: 'suv' != 'SUV'. # Once counted, print each element alongside the number of occurrences. #iterate over the array, for strings that equal certain instances #P:roblem # write a method # th method counts EACh fo the elements in the array # once the elements ave been counted, print each element alongside the numebr of occurances # due to the 'print each element along side the number of occurences' i know i need to convert # those elements into a container for the number of occurences... a hash #E"xample ['car', 'car', 'bike'] car => 2 bike => 1 #Data Structures I need a hash to contain the key adn the number of occurances array the counts the number of occurences that array will need to be iterated through to count the total number of occurences of the element #A:lgorithim define the method count_occurecnes with the argument array create a new hash iterate through the array, as each item in the array create the hash = the count of the items in the array iterate over the hash for its key, value pairs print out the key => value end #C:ode vehicles = ['car', 'car', 'truck', 'car', 'SUV', 'truck', 'motorcycle', 'motorcycle', 'car', 'truck'] def count_occurences(array) occurences = {} array.uniq.each do |element| occurences[element] = array.count(element) end occurences.each do |key, value| puts "#{key} => #{value}" end end count_occurences(vehicles) # 5 Reverse IT Part 1 RETURN TO THIS AT 4pm! P:roblem write a method that takes an argument that argument is a string it will return a new string in reverse order by word, not b character E:xample sentence = "melt banana" ....iterate through magical beeping program..... returns: "banana melt" D:ata Structure it is a string and a sentence for a method definition inputs: a string through the method definition output: that same things with the words reversed in order A:lgoritihim Are there methods I can use to make the words swap position? the ones that come to mind to check are .reverse, .split (converts to an array) .join as well, which is def reverse_sentence(sentence) sentence.split(' ').reverse.join(' ') end puts reverse_sentence('') == '' puts reverse_sentence('Hello World') == 'World Hello' puts reverse_sentence('Reverse these words') == 'words these Reverse' #Reverse It Part 2 Write a method that takes one arguement, a string containing 1 or more words and returns the given wstring with words that contain 5 or more characters reveresed Each string consists of only letters and spaces Spaces should be included when one or more than 1 word is present P:roblem write a method that takes a single argument the argument is a string of 1 or more words return the string, under the condition that any worrrd with 5 or more characters is reversed spaces are included, hould be included with the final outcome if more than 1 word is present E:xample 'I have thirteen cats.' wil run through the meth def 'I have neetriht cats.' D:ata Structure a string, I might have to move into an array, but I will see input string of characters that may contain spaces output the same string, however words that have 5 or more characters will be reversed A:lgorithim write a method defintion that takes a (parameter) convert the object to an array with the split method iterate through each object in the array if that object has 5 or more characters (.length method call) reverse the word join the array back together iterate through each item in the array, if the item has 5 or more characters, reverse it def reverse_words(sentence) sentence = sentence.split(' ') sentence.each do |word| if word.length >= 5 word.reverse! end end sentence.join(' ') end puts reverse_words('Professional') puts reverse_words("Walk around the block") puts reverse_words('Launch School') #STringy Strings Write a method that takes one argument, a positive integer, and retunrs a string of alternating ones and zeros, that always starts with 1 Length of the sstring should match the given integer P:roblem #Write a method that takes a single argument, a positive integer # It returns a string of 1's and 0's # Always begins with a 1, length of string matchs the value fo the integer E:xample method(4) == '1010' D:ata Structure(s) input: integer output string of 1's and 0's deconstruct the integer into something that can be counted .times - will run a number the amount of times based on its value and put thru a block that can then be in an index value that is recognized as even or odd that even/odd can indicate the 1 or 0 that 1 or 0 can be PUT into a blank array ... once the array is done it can be put together A:lgorithim make a new array to hold the value of the block take the number of times of the integer and iterate iteration determines t or f and assigns a 1 for true and a 0 for false 1 or 0 gets pushed into the array end the block array variable is the final line in the method definiton, but it needs to be conJOINed end def stringy(number) array = [] number.times do |index| string = index.even? ? "1" : "0" array << index end array end C:ode =end def stringy(number) array = [] number.times do |index| string = index.even? ? 1 : 0 array << string end array.join end puts stringy(6) == '101010' puts stringy(9) == '101010101' puts stringy(4) == '1010' puts stringy(7) == '1010101' =begin # Array Average Write a method that takes an argument, an array of integers, and returns the average of all the numbers in the array the array will neve rbe empty, and the numbers will always be positive integers P:roblem write a method the argument will be an array of integers it will return the average of all the numbers in the array all numbers will be postiive integers, and no empty arrays are the argument E:xamples example([4, 6, 8, 10, 12]) == 8 D:ata Structures inputs: an array of various positive integers we will need to add all of the integers together SUM through this process we will need to COUNT the array for a denominator in order to get the average we will need to add all the values of the array together output: a single integer A:lgorithim definte the method average(parameter) get the sum of the array total = parameter.sum denominator = parameter.count total / denominator end C;ode def average(array) total = array.sum denominator = array.count total/denominator end puts average([1, 5, 87, 45, 8, 8]) == 25 puts average([9, 47, 23, 95, 16, 52]) == 40 # Sum of Digits Write a method that takes a positive integer as an argument and returns the sum of its digits P:roblem Write a method method takes an integer the method returns the sum of the digits in the integer E:xample method(14) == 1 + 4 == 5 D:ata Structures beginning as an integer an array structure could deconstruct the integer with .digits sum of the array A:lgorithim def sum(integer) array = integer.digits array.sum C:ode def sum(number) array = number.digits array.reduce(:+) end puts sum(23) == 5 puts sum(496) == 19 puts sum(123_456_789) == 45 #What's my bonus? Write a metod that takes two arguments, a positive integer and a boolean and calculates the bonus of a given salary. If the boolean is true bonus is 1/2 the salary, if false it is 0 P:roblem method that takes two arguments one is an integer the other is a boolean the method will calculate 1/2 the integer if true, and 0 if false E:xample bonus(2800, true) == 1400 D:ata Structures inputs: integer boolean outputs: integer A:lgorithim bonus(number, boolean) boolean? ? number/2 : 0 (#does false return false or true?) end =end def calculate_bonus(salary, t_or_f) t_or_f ? salary / 2 : 0 end puts calculate_bonus(2800, true) == 1400 puts calculate_bonus(1000, false) == 0 puts calculate_bonus(50000, true) == 25000
#!/usr/bin/env ruby $:.unshift(File.dirname(__FILE__)+"/../lib") require 'format/bake_format' begin if ARGV.size == 2 indent = ' ' input = ARGV[0] output = ARGV[1] elsif ARGV.size == 3 indent = ARGV[0] indent = indent.split('=') raise 'indent must have =' unless indent.size == 2 raise 'indent must start with --indent' unless indent.first == '--indent' indent = indent.last input = ARGV[1] output = ARGV[2] else raise 'cannot understand' end rescue puts [ "Usage: #{__FILE__} [--indent=string] input output", " --indent=string, indent defaults to two spaces.", " Note, you can escape a tab in bash by ctrl-vTAB with sourrounding \" e.g. \"--input= \"", " input, filename or '-' for stdin", " output, filename, '-' for stdout, '--' for same as input file" ].join("\n") exit 1 end data = if input == '-' STDIN.read else File.read(input) end out = if output == '-' STDOUT elsif output == '--' out = input == STDIN ? STDOUT : File.open(input, 'w') else File.open(output, 'w') end bake_format(data, out, indent)
require 'spec_helper' describe Puppet::Type.type(:nis).provider(:solaris) do let(:instances) do described_class.expects(:svcprop).with( "-p", "config", Client_fmri).returns File.read( my_fixture('svcsprop_p_config_Client_fmri.txt')) described_class.expects(:svcprop).with( "-p", "config", Domain_fmri).returns File.read( my_fixture('svcsprop_p_config_Domain_fmri.txt')) described_class.instances.map { |inst| hsh = {} [ :domainname, :ypservers, :securenets, :use_broadcast, :use_ypsetme, :ensure, :name ].each { |prop| hsh[prop] = inst.get(prop) } hsh } end let(:resource) do Puppet::Type.type(:nis).new( :name => "current", :ensure => :present ) end let(:provider) do described_class.new(resource) end context "responds to" do [:domainname, :ypservers, :securenets, :use_broadcast, :use_ypsetme].each { |method| it method do is_expected.to respond_to(method) end it "#{method}=" do is_expected.to respond_to("#{method}=".to_sym) end } # No Setters [ :ensure, :flush ].each {| method| it method do is_expected.to respond_to(:method) end } end # ensure we have all listed properties, addition of new properties will result # in an error here and require the various property arrays to be updated it "has only expected methods" do expect([:domainname, :ypservers, :securenets, :use_broadcast, :use_ypsetme]).to eq(Puppet::Type.type(:nis).validproperties - [:ensure]) end describe ".instances" do it "returns one instance" do expect(instances.size).to eq(1) end describe "resource has expected SMF properties" do #Puppet::Type.type(:nis).validproperties.each do |field| { :domainname => %q(oracle.com), :ypservers => :absent, :securenets => :absent, :use_broadcast => :absent, :use_ypsetme => :absent }.each_pair { |field, value| pg = "config" it "#{pg}/#{field}" do expect(instances[0][field]).to eq(value) end } end # validating instances describe "property=" do it "formats string arguments" do resource[:domainname] = %q(oracle.com) newval = %q(foo.com) testval = %q^foo.com^ described_class.expects(:svccfg).with("-s", Domain_fmri, "setprop", "config/domainname=", testval ) expect(provider.domainname=newval).to eq(newval) end it "formats array arguments" do newval = %w(1.2.3.4 2.3.4.5) testval = %w^( 1.2.3.4 2.3.4.5 )^ described_class.expects(:svccfg).with("-s", Domain_fmri, "setprop", "config/ypservers=", testval ) expect(provider.ypservers=newval).to eq(newval) end it "formats array of arrays arguments" do inval = [['host','127.0.0.1'],['255.255.255.0','1.1.1.1']] testval = [ '(', ['host','127.0.0.1'],['255.255.255.0','1.1.1.1'], ')'] described_class.expects(:svccfg).with("-s", Domain_fmri, "setprop", "config/securenets=", testval ) expect(provider.securenets=inval).to eq(inval) end it "formats empty arguments" do testval = %q^\'\'^ described_class.expects(:svccfg).with("-s", Client_fmri, "setprop", "config/use_broadcast=", testval ) expect(provider.send(:use_broadcast=,:absent)).to eq(:absent) end end end end