text
stringlengths
10
2.61M
require 'rails_helper' RSpec.describe AuthorizeApiRequest do let(:user) { create(:user) } let(:header) { { Authorization: token_generator(user.email) } } subject(:invalid_request_object) { described_class.new({}) } subject(:valid_request_object) { described_class.new(header) } describe '#call' do context 'when valid request' do it 'returns user object' do result = valid_request_object.call expect(result[:user]).to eq(user) end end context 'when invalid request' do context 'when missing token' do it 'raises MissingTokenError' do expect { invalid_request_object.call } .to raise_error( ExceptionHandler::MissingToken, 'Missing token.' ) end end end context 'when invalid token' do subject(:invalid_request_object) do described_class.new(Authorization: token_generator(5)) end it 'raises InvalidToken error' do expect { invalid_request_object.call } .to raise_error(ExceptionHandler::InvalidToken, /Invalid token/) end end context 'when token is expired' do let(:header) { { Authorization: expired_token_generator(user.email) } } subject(:request_object) { described_class.new(header) } it 'raises ExceptionHandle::ExpiredSignature error' do expect { request_object.call } .to raise_error( ExceptionHandler::InvalidToken, /Signature has expired/ ) end end context 'fake token' do let(:header) { { Authorization: 'foobar' } } subject(:invalid_request_object) { described_class.new(header) } it 'handles JWT::DecodeToken error' do expect { invalid_request_object.call } .to raise_error( ExceptionHandler::InvalidToken, /Not enough or too many segments/ ) end end end end
And(/^the user selects Canadian French as the language "([^"]*)"$/) do |locale_lang| on (MoreServicePage) do |page| DataMagic.load("moreservices.yml") page.wait_for_page_to_load page.french_language end end And(/^the user click on the plus option from the service menu drop down$/) do # on(NavigationBar).go_to("more") on (NavigationBar) do |page| page.go_to("more") end end Then(/^the user will view the text Manage your account "([^"]*)"$/) do |arg| visit MoreServicePage on (MoreServicePage) do |page| # page.wait_for_page_to_load page.cos_page DataMagic.load("moreservices.yml") puts expect(page.header_element.text).to eq (data_for(:more_services)['french_header']) end end And(/^the user is on the Digital Servicing "([^"]*)" Section of the More Services Page$/) do |arg| on (MoreServicePage) do |page| DataMagic.load("moreservices.yml") expect(page.digital_servicing).to eq(data_for(:more_services)['french_digital_header']) end end And(/^the user is on the Card Services "([^"]*)" section$/) do |arg| on(MoreServicePage) do |page| DataMagic.load("moreservices.yml") expect(page.card_services_title_element.text).to eq (data_for(:more_services)['french_digital_card']) end end When(/^user clicks the link named Manage Authorized Users "([^"]*)"$/) do |arg| on(MoreServicePage) do |page| expect(page.manage_authorized_element.text).to eq (data_for(:more_services)['french_manage_auth_user']) page.manage_authorized end end Then(/^the user will be presented with the functionality to manage authorized users Manage Authorized Users "([^"]*)"$/) do |arg| on(MoreServicePage) do |page| page.wait_for_few_sec page.french_page expect(page.manage_authorized_user_element.text).to eq (data_for(:more_services)['french_manage_auth_user_page']) end end When(/^the canada user clicks the link named as Set Alerts "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.set_alerts_element.text).to eq (data_for(:more_services)['french_can_set_alert']) page.set_alerts end end Then(/^the canada user will be presented with the functionality to set alerts "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| page.wait_for_few_sec page.french_page expect(page.set_alerts_title_element.text).to eq (data_for(:more_services)['french_set_alert_page']) end end When(/^the user clicks the link name Manage Account Nick Names "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.manage_nick_names_element.text).to eq (data_for(:more_services)['french_manage_nick_names']) page.manage_nick_names end end Then(/^the following text will be displayed on the Manage Nick Name page Manage Account Nickname "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| page.wait_for_few_sec page.french_page expect(page.manage_nick_names_title_element.text).to eq (data_for(:more_services)['french_manage_nick_names_page']) end end When(/^the user clicks the link Set Travel Notifications "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.travel_notification_element.text).to eq (data_for(:more_services)['french_travel_notification']) page.travel_notification end end Then(/^the user will be presented with the functionality to set travel notifications Set Travel Notification "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| page.wait_for_few_sec page.french_page expect(page.set_travel_notification_element.text).to eq (data_for(:more_services)['french_travel_notification_page']) end end When(/^the canada user clicks the link named Link a Card Account "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.link_account_element.text).to eq (data_for(:more_services)['french_link_account']) page.link_account end end Then(/^the user will be presented with the functionality to link accounts Link a Card Account "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| page.wait_for_few_sec page.french_page expect(page.link_accounts_element.text).to eq (data_for(:more_services)['french_link_account_page']) end end When(/^the user clicks the link named Transfer a Balance "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.transfer_balance_element.text).to eq (data_for(:more_services)['french_transfer_balance']) page.transfer_balance end end Then(/^the user will be presented with the functionality to Transfer A Balance"([^"]*)"$/) do |arg| on (MoreServicePage) do |page| @browser.windows.last.use page.french_page puts expect(page.transfer_a_balance_page_element.text).to eq (data_for(:more_services)['french_transfer_balance_page']) end end And(/^the user is on Mobile Banking "([^"]*)" Section of the More Services Page$/) do |arg| on (MoreServicePage) do |page| expect(page.mobile_banking_element.text).to eq (data_for(:more_services)['french_mob_header']) end end When(/^clicks the link named Download Mobile Apps "([^"]*)"$/) do |arg| DataMagic.load("moreservices.yml") on (MoreServicePage) do |page| expect(page.mobile_download_apps_element.text).to eq (data_for(:more_services)['french_mob_download']) page.mobile_download_apps end end Then(/^the canadian user will be presented with the functionality to download mobile applications Capital One Mobile Solutions "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| @browser.windows.last.use expect(page.download_mobile_element.text).to eq (data_for(:more_services)['french_canada_mob_download_page']) end end When(/^click the link named Manage Text Messaging "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.manage_text_messaging_element.text).to eq (data_for(:more_services)['french_mob_text_message']) page.manage_text_messaging end end Then(/^the user will be presented with the functionality to Manage Text Messaging "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| page.french_page expect(page.manage_text_mobile_element.text).to eq (data_for(:more_services)['french_mob_text_message_page']) end end And(/^the user is on the Customer Service "([^"]*)" section of the More Services Page$/) do |arg| on (MoreServicePage) do |page| DataMagic.load("moreservices.yml") expect(page.customer_services).to eq (data_for(:more_services)['french_customer_header']) end end And(/^the user select the one option under Get Help "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.get_help).to eq(data_for(:more_services)['french_get_help_header']) end end And(/^the user clicks on the Canada more service link named Report Lost Stolen Card "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.canada_lost_stolen_element.text).to eq(data_for(:more_services)['french_can_report_lstln']) page.canada_lost_stolen end end Then(/^the canada user will be presented with information Report a Lost or Stolen Card "([^"]*)" on the process for handling lost or stolen cards\.$/) do |arg| on(MoreServicePage) do |page| expect(page.canada_lost_stolen_title_element.text).to eq (data_for(:more_services)['french_can_report_lstln_page']) end end Then(/^the user click the link Request a Replacement Card "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.canada_request_replacement_element.text).to eq (data_for(:more_services)['french_can_replacement']) page.canada_request_replacement end end And(/^the user will be presented with information on the process for Request a Replacement Card "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.canada_request_replacement_title_element.text).to eq (data_for(:more_services)['can_replacement_page']) end end Then(/^the canada user clicks on Dispute a Charge link "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| puts expect(page.canada_dispute_a_charge_element.text).to eq (data_for(:more_services)['french_dispute_a_charge']) page.canada_dispute_a_charge end end And(/^the user will be presented with information on the process for Disputing a Charge Transactions & Details "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.can_dispute_a_charge_title_element.text).to eq (data_for(:more_services)['french_dispute_a_charge_page']) end end And(/^the user is on the Account Info "([^"]*)" section of the services Page$/) do |arg| on (MoreServicePage) do |page| expect(page.accountInfo).to eq (data_for(:more_services)['french_account_info']) end end When(/^the user click the link named Online Banking Terms and Conditions "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.onlineBankingTermsAndConditions_element.text).to eq (data_for(:more_services)['french_online_bank']) page.onlineBankingTermsAndConditions end end Then(/^the user will be presented with the online banking terms and conditions (\d+)\. Introduction$/) do |arg| on (MoreServicePage) do |page| page.wait_for_few_sec @browser.windows.last.use page.french_page expect(page.eos_onlineBanking_element.text).to eq (data_for(:more_services)['french_online_bank_page']) end end And(/^the canadian user is on the Financial Education "([^"]*)" section of the more Services Page$/) do |arg| on (MoreServicePage) do |page| expect(page.financialInfo_element.text).to eq (data_for(:more_services)['french_canada_financial_info']) end end When(/^the canadian user clicks the Credit (\d+) "([^"]*)" link$/) do |arg1, arg2| on (MoreServicePage) do |page| expect(page.financialeducation_element.text).to eq (data_for(:more_services)['french_canada_credit_101']) page.financialeducation end end Then(/^the canadian user will be routed to financial education information Credit (\d+) "([^"]*)"$/) do |arg1, arg2| on (MoreServicePage) do |page| @browser.windows.last.use expect(page.financial_education_element.text).to eq (data_for(:more_services)['french_canada_credit_101_page']) end end And(/^the user is on the Contact Us "([^"]*)" Section of the CANADA More Services Page\.$/) do |arg| on (MoreServicePage) do |page| expect(page.contact_us_element.text).to eq (data_for(:more_services)['french_contact_header']) end end Then(/^text TDD \(for hearing impaired\) ATME \(pour malentendants\) will display on the More Services Page$/) do on(MoreServicePage) do |page| page.wait_for_few_sec expect(page.hearing_impaired_element.text).to eq (data_for(:more_services)['french_can_tdd_hearing']) end end Then(/^the text International Collect Numรฉro international appels ร  frais virรฉs will display on the More Services Page$/) do on (MoreServicePage) do |page| expect(page.international_collect_element.text).to eq (data_for(:more_services)['french_can_international_collect']) end end Then(/^the text Rewards Center "([^"]*)" will display on the More Services Page$/) do |arg| on (MoreServicePage) do |page| expect(page.rewards_center_text_element.text).to eq (data_for(:more_services)['french_can_rewards_text']) end end Then(/^the user clicks the link named View all contact options "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| page.wait_for_few_sec expect(page.viewAllContactOptions_element.text).to eq (data_for(:more_services)['french_view_all_contact']) page.viewAllContactOptions end end And(/^the user will see title Contact Us About Personal Credit Card Accounts "([^"]*)" on a page$/) do |arg| on (MoreServicePage) do |page| @browser.windows.last.use expect(page.canada_contact_us_element.text).to eq(data_for(:more_services)['french_can_view_all_contact_page']) end end
class MarkdownContent < ActiveRecord::Base attr_accessor :component_parent, :component_parent_id has_many :markdown_content_image has_many :images, through: :markdown_content_image before_validation :set_content_to_string def content_blank? content.to_s.strip.blank? end def parent @parent ||= component_parent.titleize.constantize.find_by_id(component_parent_id) end def parent_title parent.title end private def set_content_to_string self.content ||= "" end end
namespace :client do desc "handle requests from active amqp accruers" task fetch_client_messages: :environment do AmqpAccrual::Config.clients.each do |client| AmqpAccrual::Receiver.handle_responses(client) 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 devise :omniauthable, omniauth_providers: %i[doorkeeper] def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.email = auth.info.email user.password = Devise.friendly_token[0, 20] user.firstname = auth.info.firstname user.lastname = auth.info.lastname end end def update_doorkeeper_credentials(auth) update( doorkeeper_access_token: auth.credentials.token, doorkeeper_refresh_token: auth.credentials.refresh_token ) end end
class Review < ApplicationRecord belongs_to :book belongs_to :user validates_presence_of :title validates_presence_of :review_text validates :rating, presence: true, numericality: {only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 5} end
class Triangle attr_accessor :a1, :a2, :a3 def initialize(a1, a2, a3) @a1 = a1 @a2 = a2 @a3 = a3 end def kind validate_triangle if a1 == a2 && a2 == a3 :equilateral elsif a1 == a2 || a2 == a3 || a1 == a3 :isosceles else :scalene end end def validate_triangle valid_triangle = [(a1 + a2 > a3), (a1 + a3 > a2), (a2 + a3 > a1)] [a1, a2, a3].each { |s| valid_triangle << false if s <= 0 } if valid_triangle.include?(false) raise TriangleError end end end class TriangleError < StandardError end
# frozen_string_literal: true FactoryBot.define do factory :account do client_id { FactoryBot.create(:client).id } balance { Faker::Number.number(4) } a_type { 'Saving' } number { Faker::Bank.account_number } end end
class AddFitnessGoalPaymentMethodSubscriptionPlanToMember < ActiveRecord::Migration[5.1] def change add_reference :members, :fitness_goal, index: true, foreign_key: true add_reference :members, :payment_method, index: true, foreign_key: true add_reference :members, :subscription_plan, index: true, foreign_key: true end end
class PublishedsController < ApplicationController before_action :set_contact before_action :set_contact_published, only: [:show, :update, :destroy] def index json_response(@contact.publisheds) end def show json_response(@published) end def create @contact.publisheds.create!(published_params) json_response(@contact, :created) end def update @published.update(published_params) head :no_content end def destroy @published.destroy head :no_content end private def published_params params.permit(:text, :published_image, :post_rating) end def set_contact @contact = Contact.find(params[:contact_id]) end def set_contact_published @published = @contact.publisheds.find_by!(id: params[:id]) if @contact end end
require "spec_helper" describe Clockwork::Test do let(:clock_file) { "spec/fixtures/clock.rb" } let(:test_job_name) { "Run a job" } let(:test_job_output) { "Here's a running job" } it "has a version number" do expect(Clockwork::Test::VERSION).not_to be nil end describe ".run" do before { Clockwork::Test.run(file: clock_file, max_ticks: 1) } after { Clockwork::Test.clear! } it "runs the test job in the file" do expect(Clockwork::Test.ran_job?(test_job_name)).to be_truthy end it "knows the job ran a single time" do expect(Clockwork::Test.times_run(test_job_name)).to eq 1 end it "retains a record of the work that the job would have done" do expect(Clockwork::Test.block_for(test_job_name).call).to eq test_job_output end end end
require "test_helper" class FeedsControllerTest < ActionController::TestCase include OrganisationFeedHelpers test "routing handles paths with just format" do assert_routing( "/government/organisations/ministry-of-magic.atom", controller: "feeds", action: "organisation", organisation_name: "ministry-of-magic", format: "atom", ) end test "routing handles paths with format and locale" do assert_routing( "/government/organisations/ministry-of-magic.cy.atom", controller: "feeds", action: "organisation", organisation_name: "ministry-of-magic", format: "atom", locale: "cy", ) end test "renders atom feeds" do content_item = content_store_has_schema_example("organisation") stub_content_for_organisation_feed("ministry-of-magic", []) get :organisation, params: { organisation_name: organisation_slug(content_item), format: "atom" } assert_response :success assert_select "feed title", "Ministry of Magic - Activity on GOV.UK" end test "sets the Access-Control-Allow-Origin header for atom pages" do content_item = content_store_has_schema_example("organisation") stub_content_for_organisation_feed("ministry-of-magic", []) get :organisation, params: { organisation_name: organisation_slug(content_item), format: "atom" } assert_equal "*", response.headers["Access-Control-Allow-Origin"] end def organisation_slug(content_item) File.basename(content_item["base_path"]) end def content_store_has_schema_example(schema_name) document = GovukSchemas::Example.find(schema_name, example_name: schema_name) document["base_path"] = "/government/organisations/ministry-of-magic" document["title"] = "Ministry of Magic" stub_content_store_has_item(document["base_path"], document) document end end
# coding: utf-8 require 'spec_helper' feature 'Visitor signs up', js: true do scenario 'with valid data' do user = factory(:user) sign_in_with user.email, '123456' expect(page).to have_content('ะ’ั‹ั…ะพะด') end end
doctype html html head title Rails App = csrf_meta_tags = csp_meta_tag = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' //! Fonts and icons // Font Awesome link crossorigin="anonymous" href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" integrity="sha384-3AB7yXWz4OeoZcPbieVW64vVXEwADiYyAEhwilzWsLw+9FgqpyjjStpPnpBO8o8S" rel="stylesheet" / // Google API fonts link href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel="stylesheet" // Bootstrap style link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous" /! Material Kit CSS link href="/material-dashboard.css?v=2.1.2" rel="stylesheet" link href="/dashboard.css" rel="stylesheet" = javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0" body class="#{controller_name } #{action_name}" .row.position-relative.container-fluid .position-absolute.zIndex1000 - flash.each do |title, value| - if title == "notice" p.flash.alert.alert-success = value - elsif title == "alert" p.flash.alert.alert-danger = value = yield //script script src="https://code.jquery.com/jquery-1.12.4.min.js" script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js" script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js" script crossorigin="anonymous" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" script crossorigin="anonymous" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
class FlowersController < ApplicationController def index; end def new @flower = Flower.new end def create @flower = Flower.new flower_params if @flower.save flash[:success] = t ".flash" redirect_to @flower else render :new end end def show @flower = Flower.find_by id: params[:id] return if @flower flash[:success] = t :not_flash redirect_to new_flower_path end def edit; end private def flower_params params.require(:flower).permit :name, :description, :image, :price, :discount end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root 'home#index' get 'signup' => 'users#new' get 'login' => 'sessions#new' post 'login' => 'sessions#create' delete 'logout' => 'sessions#destroy' get 'posts/new' => 'posts#new' post 'posts' => 'posts#create' get 'posts' => 'posts#home' get 'myposts' => 'posts#myposts' patch 'posts' => 'posts#update' get 'profile' => 'profiles#show' get 'profile/new' => 'profiles#new' post 'profile' => 'profiles#create' patch 'profile' => 'profiles#update' post 'interest' => 'interests#create' get 'myinterests' => 'interests#myinterests' delete 'interests' => 'interests#destroy' get 'sharedwithme' => 'posts#sharedwithme' delete 'sharedwithme' => 'posts#decline' resources :users, :posts, :profiles, :interests end
class AddSentOnColumnToAppointments < ActiveRecord::Migration def change add_column :appointments, :sent_on, :text end end
require 'hammerspace' ## # Hammerspace-backed Store designed for BasicCache module HammerStore class << self ## # Insert a helper .new() method for creating a new Store object def new(*args) self::Store.new(*args) end end ## # Hammerspace-backed store object class Store attr_reader :data, :file ## # Generate an empty store def initialize(params = {}) @file = params[:file] || raise('You must specify a file') @data = Hammerspace.new(@file) end ## # Clears a specified key or the whole store def clear!(key = nil) if key.nil? @data.clear && {} else key = prep(key) value = @data[key] @data.delete key parse value end end ## # Retrieve a key def [](key) parse @data[prep(key)] end ## # Set a key def []=(key, value) @data[prep(key)] = prep(value) end ## # Return the size of the store def size @data.size end ## # Check for a key in the store def include?(key) @data.key? prep(key) end ## # Array of keys in the store def keys @data.keys.map { |x| parse x } end private def prep(object) Marshal.dump object end def parse(object) # rubocop:disable Security/MarshalLoad object.nil? ? nil : Marshal.load(object) # rubocop:enable Security/MarshalLoad end end end
# frozen_string_literal: true module ParallelRunner CONCURRENT_REQUESTS = 3 private # TODO(uwe): Use concurrent-ruby instead? def in_parallel(values) queue = Queue.new values.each { |value| queue << value } threads = Array.new(CONCURRENT_REQUESTS) do Thread.start { Rails.application.executor.wrap { yield(queue.pop(true), queue) until queue.empty? } } end threads.each(&:join) end end
Dado("que eu tenho {int} laranjas na bolsa.") do |valor| @laranja = valor end Quando("eu coloco {int} laranjas na bolsa.") do |valor2| @coloquei = valor2 @resultado = @laranja + @coloquei end Entรฃo("eu verifico se o total de laranjas รฉ {int}.") do |total| expect(@resultado).to eq total end Quando("eu tiro {int} laranjas da bolsa.") do |valor3| @retirei = valor3 @resultado = @laranja - @retirei end Entรฃo("eu verifico com quantas laranjas eu fiquei na bolsa.") do expect(@resultado).to eq 8 end
require 'spec_helper' describe SPV::Fixtures::Modifiers::ShortcutPath do describe '#modify' do let(:path) { 'some home path' } let(:shortcut_path) { 'some shortcut' } let(:options) { instance_double('SPV::Options') } let(:fixture) do instance_double( 'SPV::Fixture', name: 'test_with_home_path', shortcut_path: shortcut_path ) end subject { described_class.new(options).modify(fixture) } context 'when a name of the fixture has a shortcut path' do context 'when a given shortcut path is defined' do it 'writes a proper path to the fixture' do expect(options).to receive(:shortcut_path).with(shortcut_path).and_return(path) expect(fixture).to receive(:set_home_path).with(path) subject end end context 'when a given shortcut path is not defined' do before do allow(options).to receive(:shortcut_path).and_return(nil) end it 'raises an argument error about wrong way of defining fixtures' do msg = "You are trying to use the 'some shortcut' shortcut path " \ "for test_with_home_path fixture. This shortcut path cannot be " \ "used since it is not defined, please refer to the documentation to make " \ "sure you properly define the shortcut path." expect { subject }.to raise_error( ArgumentError, msg ) end end end context 'when a name of the fixture has not a shortcut path' do let(:fixture) do instance_double( 'SPV::Fixture', shortcut_path: nil ) end it 'does not set any home path' do expect(fixture).to_not receive(:set_home_path) subject end end end end
class Section < ApplicationRecord acts_as_paranoid has_paper_trail belongs_to :status belongs_to :visibility belongs_to :document belongs_to :created_by, :class_name => "User", :foreign_key => "created_by_id" belongs_to :updated_by, :class_name => "User", :foreign_key => "updated_by_id", optional: true belongs_to :deleted_by, :class_name => "User", :foreign_key => "deleted_by_id", optional: true belongs_to :template, :class_name => "Section", :foreign_key => "template_id", optional: true belongs_to :clone_source, :class_name => "Section", :foreign_key => "clone_source_id", optional: true has_many :contexts, as: :item attr_accessor :relevance_score default_scope { order('sections.order') } def sync_to_template self.title = template.title self.description = template.description self.content = template.content end def sync_to_clone self.title = clone_source.title self.description = clone_source.description self.content = clone_source.content end def suppress_collapse? self.display_format != nil && self.display_format["suppress_collapse"] == "1" end def default_collapsed? self.display_format != nil && self.display_format["collapse_default"] == "1" end end
# -*- encoding: utf-8 -*- # stub: omniauth-moves 0.0.2 ruby lib Gem::Specification.new do |s| s.name = "omniauth-moves" s.version = "0.0.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Nick Elser"] s.date = "2014-08-15" s.description = "OmniAuth strategy for Moves." s.email = ["nick.elser@gmail.com"] s.homepage = "https://github.com/nickelser/omniauth-moves" s.rubygems_version = "2.4.5" s.summary = "OmniAuth strategy for Moves." s.installed_by_version = "2.4.5" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<omniauth>, ["~> 1.0"]) s.add_runtime_dependency(%q<omniauth-oauth2>, ["~> 1.0"]) s.add_runtime_dependency(%q<multi_json>, ["~> 1.0"]) s.add_development_dependency(%q<rspec>, ["~> 2.7"]) s.add_development_dependency(%q<rack-test>, [">= 0"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) else s.add_dependency(%q<omniauth>, ["~> 1.0"]) s.add_dependency(%q<omniauth-oauth2>, ["~> 1.0"]) s.add_dependency(%q<multi_json>, ["~> 1.0"]) s.add_dependency(%q<rspec>, ["~> 2.7"]) s.add_dependency(%q<rack-test>, [">= 0"]) s.add_dependency(%q<simplecov>, [">= 0"]) end else s.add_dependency(%q<omniauth>, ["~> 1.0"]) s.add_dependency(%q<omniauth-oauth2>, ["~> 1.0"]) s.add_dependency(%q<multi_json>, ["~> 1.0"]) s.add_dependency(%q<rspec>, ["~> 2.7"]) s.add_dependency(%q<rack-test>, [">= 0"]) s.add_dependency(%q<simplecov>, [">= 0"]) end end
class CartsController < ApplicationController before_filter :current_cart def add CartItem.create(:product_id => params[:id], :cart_id => current_cart.id) redirect_to cart_path(current_cart) end def show @cart = Cart.find(params[:id]) @cart_items = CartItem.all.includes(:product) total= 0 @cart_items.each do |item| total += item.product.hardcover_price_in_cents end @total = "$#{Money.new(total, "USD")}" end end
require 'spec_helper' describe ProjectPolicy do describe 'for a user' do subject { ProjectPolicy.new(user, project) } let(:user) { FactoryGirl.create(:user, :with_company) } describe 'for valid project' do let(:project) { FactoryGirl.create(:project, user: user) } it { should permit_action(:create) } it { should permit_action(:new) } it { should permit_action(:update) } it { should permit_action(:edit) } it { should permit_action(:show) } it { should permit_action(:not_pursuing) } it { should permit_action(:offer) } it { should_not permit_action(:agree_to_terms) } it { should_not permit_action(:not_interested) } it { should_not permit_action(:reject_terms) } it { should_not permit_action(:destroy) } end describe 'for another project' do let(:project) { FactoryGirl.create(:project) } it { should_not permit_action(:show) } it { should_not permit_action(:create) } it { should_not permit_action(:new) } it { should_not permit_action(:update) } it { should_not permit_action(:edit) } it { should_not permit_action(:not_pursuing) } it { should_not permit_action(:offer) } it { should_not permit_action(:agree_to_terms) } it { should_not permit_action(:not_interested) } it { should_not permit_action(:reject_terms) } it { should_not permit_action(:destroy) } end end describe 'for a consultant' do subject { ProjectPolicy.new(consultant, project) } let(:consultant) { FactoryGirl.create(:consultant) } describe 'for valid project' do let(:project) { FactoryGirl.create(:project, consultant: consultant) } it { should permit_action(:show) } it { should permit_action(:agree_to_terms) } it { should permit_action(:not_interested) } it { should permit_action(:reject_terms) } it { should_not permit_action(:not_pursuing) } it { should_not permit_action(:offer) } it { should_not permit_action(:create) } it { should_not permit_action(:new) } it { should_not permit_action(:update) } it { should_not permit_action(:edit) } it { should_not permit_action(:destroy) } end describe 'for another project' do let(:project) { FactoryGirl.create(:project) } it { should_not permit_action(:show) } it { should_not permit_action(:agree_to_terms) } it { should_not permit_action(:not_interested) } it { should_not permit_action(:reject_terms) } it { should_not permit_action(:not_pursuing) } it { should_not permit_action(:offer) } it { should_not permit_action(:create) } it { should_not permit_action(:new) } it { should_not permit_action(:update) } it { should_not permit_action(:edit) } it { should_not permit_action(:destroy) } end end describe 'for a visitor' do subject { ProjectPolicy.new(consultant, project) } let(:consultant) { nil } it ' raises an error ' do expect { subject }.to raise_error end end end
require_relative 'spec_helper' require_relative '../lib/Ebook' describe Ebook do before(:context) do @ebook1 = Ebook.new("The Life-Changing Magic of Not Giving a F**k", 11.99, 125, "Sarah Knight") end describe "Initialization" do it "is a kind of the Item class" do expect(@ebook1).to be_a_kind_of(Item) end it "is a kind of the Digital_item class" do expect(@ebook1).to be_a_kind_of(Digital_item) end it "is an instance of the Ebook class" do expect(@ebook1).to be_instance_of(Ebook) end it "is assigned a name" do expect(@ebook1.name).to eq("The Life-Changing Magic of Not Giving a F**k") end it "is assigned a price" do expect(@ebook1.price).to eq(11.99) end it "is assigned a number of pages" do expect(@ebook1.pages).to eq(125) end it "is assigned an author" do expect(@ebook1.author).to eq("Sarah Knight") end end describe "Accessors" do it "quatity of digital item should always be 1" do expect(@ebook1.quantity).to eq(1) end it "should be able to get and set name" do @ebook1.name="New Name" expect(@ebook1.name).to eq("New Name") end it "should be able to get and set price" do @ebook1.price=44.99 expect(@ebook1.price).to eq(44.99) end it "should be able to get and set description" do expect(@ebook1.description).to eq("") @ebook1.description="test" expect(@ebook1.description).to eq("test") end end describe "Methods" do it "should be able to stock, quantity should stay as 1" do result = @ebook1.stock 5 expect(result).to eq(true) expect(@ebook1.quantity).to eq(1) end it "should able to sell items regardless of stock since it's always 1" do result = @ebook1.sell 6 expect(result).to eq(true) expect(@ebook1.quantity).to eq(1) end it "should be able to sell items and quantity should stay as 1" do result = @ebook1.sell 3 expect(result).to eq(true) expect(@ebook1.quantity).to eq(1) end end describe "Part 2 Methods" do it "should be able to return, digital items wont change the quantity" do result = @ebook1.return 2 expect(result).to eq(true) expect(@ebook1.quantity).to eq(1) end it "should have a default weight of -1 for digital items" do expect(@ebook1.weight).to eq(-1) end it "should not be able to set a new weight" do @ebook1.weight = 1 expect(@ebook1.weight).to eq(-1) end it "should not be to report a ship_price" do expect(@ebook1.ship_price).to eq(false) end end end
class Timetrap::Github def login octokit.user.login end def create_gist(display) gist = octokit.create_gist( description: 'Timetrap sheet', files: { 'overview.txt' => { content: display }} ) gist[:html_url] end # private def octokit token = config['access_token'] @octokit ||= Octokit::Client.new(access_token: token) end # TODO: change static access def config Timetrap::Config['github'] || fail('Github settings missing in config file') end def user octokit.user.login end end
module XClarityClient # # Exposes NodeManagement features # module Mixins::NodeMixin def discover_nodes(opts = {}) node_management.fetch_all(opts) end def fetch_nodes(uuids = nil, include_attributes = nil, exclude_attributes = nil) node_management.get_object( uuids, include_attributes, exclude_attributes ) end def blink_loc_led(uuid = '', name = 'Identify') node_management.set_loc_led_state(uuid, 'Blinking', name) end def turn_on_loc_led(uuid = '', name = 'Identify') node_management.set_loc_led_state(uuid, 'On', name) end def turn_off_loc_led(uuid = '', name = 'Identify') node_management.set_loc_led_state(uuid, 'Off', name) end def power_on_node(uuid = '') node_management.set_power_state(uuid, :powerOn) end def power_off_node(uuid = '') node_management.set_power_state(uuid, :powerOffSoftGraceful) end def power_off_node_now(uuid = '') node_management.set_power_state(uuid, :powerOff) end def power_restart_node(uuid = '') node_management.set_power_state(uuid, :powerCycleSoftGrace) end def power_restart_node_now(uuid = '') node_management.set_power_state(uuid, :powerCycleSoft) end def power_restart_node_controller(uuid = '') node_management.set_bmc_power_state(uuid, :restart) end def power_restart_node_to_setup(uuid = '') node_management.set_power_state(uuid, :bootToF1) end private def node_management NodeManagement.new(@config) end end end
#============================================================================== # ** Theread Assist #------------------------------------------------------------------------------ # This defined the method for assist thread #============================================================================== #tag: 3( Thread Assist module Thread_Assist #---------------------------------------------------------------------------- # * Constants #---------------------------------------------------------------------------- Uwait = 0.03 # Time wait until next update @work = 0 @work_args = [] # >> Work type definiation WorkTable = { :BCmine => 1, :BCquery => 2, :SoundPlay => 3, } #---------------------------------------------------------------------------- module_function #---------------------------------------------------------------------------- # * Assign work #---------------------------------------------------------------------------- def assign_work(*args) return unless @work == 0 type = args[0] puts "[Thread]: Work assigned: #{type}" @work = WorkTable[type] args.shift rescue [] @work_args = args end #---------------------------------------------------------------------------- # * Main entry access #---------------------------------------------------------------------------- def assist_main @work = 0 begin loop do update_assist sleep(Uwait) end rescue Exception => e PONY::ERRNO.mutex_error e end end #---------------------------------------------------------------------------- # * Check wether need to pause #---------------------------------------------------------------------------- def pause? return true if Graphics.transitioning? return true if BattleManager.in_battle? return false end #---------------------------------------------------------------------------- # * Main update process #---------------------------------------------------------------------------- def update_assist return if @work == 0 case @work when WorkTable[:BCmine] && !BlockChain.locked? puts "[Thread]: Assist mining" $mutex.synchronize{BlockChain.mining(true)} when WorkTable[:SoundPlay] $mutex.synchronize{PONY.PlayAudio('sound.wav',8,0,0,0,0,0)} end @work = 0 end #---------------------------------------------------------------------------- def work?(symbol) @work == WorkTable[symbol] end #---------------------------------------------------------------------------- def yield @work = 0 File.open("test.txt", 'a'){|file| file.write("Kill Thread: #{$thassist}\n")} Thread.kill($thassist) puts "[Thread]: #{Time.now} #{$thassist.stop?}" end end
class Round < ActiveRecord::Base NUMBER_OF_TRICKS = 10 belongs_to :game, touch: true has_many :cards, dependent: :destroy has_many :tricks, dependent: :destroy has_many :bids, dependent: :destroy validates :game, presence: true validates :order_in_game, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :odd_players_score, :even_players_score, presence: true, numericality: { only_integer: true } scope :in_playing_order, -> { order(order_in_game: :asc) } def in_bidding_stage? bids.passes.count < game.players.count - 1 end def in_playing_stage? !in_bidding_stage? && tricks.active.any? end def finished? tricks.active.none? end def current_trick tricks.active.in_playing_order.first end def previous_trick tricks.inactive.in_playing_order.last end def highest_bid bids.non_passes.in_ranked_order.first end def has_no_bids_yet? bids.count.zero? end end
class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [ :last_name, :first_name, :last_name_kana, :first_name_kana, :postal_code, :prefecture_name, :telephone_number, :address ]) end def after_sign_out_path_for(resource) case resource when :admin new_admin_session_path when :public new_public_session_path end end end
require './src/tokenizer/reader/file_reader' require './src/tokenizer/errors' require './spec/contexts/test_file' RSpec.describe Tokenizer::Reader::FileReader, 'file reading in chunks' do include_context 'test_file' def init_reader_with_contents(contents) write_test_file contents @reader = Tokenizer::Reader::FileReader.new filename: test_file_path end describe '#next_chunk' do it 'can read and consume chunks' do init_reader_with_contents 'hello world' expect(@reader.next_chunk).to eq 'hello' expect(@reader.next_chunk).to eq ' ' end it 'can read chunks without consuming them' do init_reader_with_contents 'hello world' expect(@reader.next_chunk(consume?: false)).to eq 'hello' expect(@reader.next_chunk(consume?: false)).to eq 'hello' end it 'reads a whole string as one chunk' do init_reader_with_contents 'ใ€Œใ‚ ใ„ ใ† ใˆ ใŠใ€' expect(@reader.next_chunk).to eq 'ใ€Œใ‚ ใ„ ใ† ใˆ ใŠใ€' end it 'discards entire block comments' do init_reader_with_contents '(ใ‚ ใ„ ใ† ใˆ ใŠ)' expect(@reader.next_chunk).to be_nil end it 'reads a whole string as one chunk even if it contains a block comment' do init_reader_with_contents 'ใ€Œ(ใ‚ ใ„ ใ† ใˆ ใŠ)ใ€' expect(@reader.next_chunk).to eq 'ใ€Œ(ใ‚ ใ„ ใ† ใˆ ใŠ)ใ€' end it 'reads a whole string as one chunk even if it contains a newline' do init_reader_with_contents "ใ€Œใ‚\nใ„\nใ†\nใˆ\nใŠใ€" expect(@reader.next_chunk).to eq "ใ€Œใ‚\nใ„\nใ†\nใˆ\nใŠใ€" end it 'discards entire block comments as one chunk even if it contains a string' do init_reader_with_contents '(ใ€Œใ‚ ใ„ ใ† ใˆ ใŠใ€)' expect(@reader.next_chunk).to be_nil end it 'discards entire block comments as one chunk even if it contains a newline' do init_reader_with_contents '(ใ‚\nใ„\nใ†\nใˆ\nใŠ)' expect(@reader.next_chunk).to be_nil end it 'reads until EOL when it sees an inline comment' do init_reader_with_contents "โ€ปใ‚ ใ„ ใ† ใˆ ใŠ\n" expect(@reader.next_chunk).to eq "\n" end it 'raises an error on an unclosed string' do init_reader_with_contents 'ใ€Œใ‚' expect { @reader.next_chunk } .to raise_error Tokenizer::Errors::UnclosedString end it 'raises an error on an unclosed block comment' do init_reader_with_contents '(ใ‚' expect { @reader.next_chunk } .to raise_error Tokenizer::Errors::UnclosedBlockComment end it 'does not raise an error when discarding to EOL and EOF is not found' do init_reader_with_contents 'โ€ปใ‚' expect { @reader.next_chunk } .to_not raise_error end it 'does not raise an error when reading to next non-whitespace and EOF is found' do init_reader_with_contents ' ' expect { @reader.next_chunk } .to_not raise_error end end describe '#peek_next_chunk' do it 'returns the next chunk without consuming it' do init_reader_with_contents 'hello world' @reader.next_chunk # hello expect(@reader.peek_next_chunk).to eq 'world' expect(@reader.next_chunk).to eq ' ' expect(@reader.next_chunk).to eq 'world' end it 'returns the next non-whitespace chunk' do init_reader_with_contents 'hello ใ€€ world' @reader.next_chunk # hello expect(@reader.peek_next_chunk).to eq 'world' end it 'can return the next whitespace chunk' do init_reader_with_contents 'hello ใ€€ world' @reader.next_chunk # hello expect(@reader.peek_next_chunk(skip_whitespace?: false)).to eq ' ใ€€ ' end it 'returns an empty string when all remaining whitespace is skipped' do init_reader_with_contents 'hello ' @reader.next_chunk # hello expect(@reader.peek_next_chunk).to eq '' end end describe '#finished?' do it 'finishes when it can no longer read' do init_reader_with_contents 'hello world' 3.times { @reader.next_chunk } expect(@reader.finished?).to be_truthy end end end
require 'test/unit' require 'action_view' require 'entitlement/view_helpers' class View include Entitlement::ViewHelpers end class ViewHelpersTest < Test::Unit::TestCase def setup @view = View.new end # # tee # def test_tee_with_one_argument out = @view.tee 'My page' assert_equal 'My page', out end def test_tee_with_two_arguments out = @view.tee 'My page', 'Some section' assert_equal 'My page', out end def test_tee_is_html_safe out = @view.tee 'My page' assert out.html_safe? end # # title as tee # def test_title_as_tee_alias_with_one_argument out = @view.title 'My page' assert_equal out, 'My page' end def test_title_as_tee_alias_with_two_arguments out = @view.title 'My page', 'Some section' assert_equal 'My page', out end def test_title_as_tee_alias_is_html_safe out = @view.title 'My page' assert out.html_safe? end # # title rendering # def test_title_without_arguments @view.tee 'My page' out = @view.title assert_equal 'My page', out end def test_title_without_arguments_via_title @view.title 'My page' out = @view.title assert_equal 'My page', out end def test_title_with_site @view.tee 'My page' out = @view.title :site => 'My site' assert_equal 'My page - My site', out end def test_title_with_site_via_title @view.title 'My page' out = @view.title :site => 'My site' assert_equal 'My page - My site', out end def test_title_with_sections @view.tee 'My page', 'Some section' out = @view.title assert_equal 'My page - Some section', out end def test_title_with_sections_via_title @view.title 'My page', 'Some section' out = @view.title assert_equal 'My page - Some section', out end def test_title_with_site_and_sections @view.tee 'My page', 'Some section' out = @view.title :site => 'My site' assert_equal 'My page - Some section - My site', out end def test_title_with_site_and_sections_via_title @view.title 'My page', 'Some section' out = @view.title :site => 'My site' assert_equal 'My page - Some section - My site', out end def test_title_with_custom_separator @view.tee 'My page' out = @view.title :site => 'My site', :separator => ': ' assert_equal 'My page: My site', out end def test_title_with_custom_separator_via_title @view.title 'My page' out = @view.title :site => 'My site', :separator => ': ' assert_equal 'My page: My site', out end def test_title_big_endian @view.tee 'My page', 'Some section' out = @view.title :site => 'My site', :big_endian => true assert_equal 'My site - Some section - My page', out end def test_title_big_endian_via_title @view.title 'My page', 'Some section' out = @view.title :site => 'My site', :big_endian => true assert_equal 'My site - Some section - My page', out end def test_title_is_html_safe @view.tee 'My page' out = @view.title assert out.html_safe? end def test_title_is_html_safe_via_title @view.title 'My page' out = @view.title assert out.html_safe? end end
class AddColumnProdIdToExpenseProduct < ActiveRecord::Migration def change add_column :expense_products, :prod_id, :string end end
class RemoveCatFromAccompaniments < ActiveRecord::Migration def change remove_column :accompaniments, :cat, :string remove_column :accompaniments, :bearing_id, :integer end end
# frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'coverage/badge/version' Gem::Specification.new do |spec| spec.name = 'coverage-badge' spec.version = Coverage::Badge::VERSION spec.authors = ['Andrey Orsoev'] spec.email = ['andrey.orsoev@gmail.com'] spec.summary = 'Generate a SVG badge with coverage data' spec.description = 'Provide a coverage information for your codebase' spec.homepage = 'https://github.com/andreyors/coverage-badge' unless spec.respond_to?(:metadata) raise 'RubyGems 2.0+ is required to protect against public gem pushes.' end spec.metadata['allowed_push_host'] = 'https://github.com/andreyors/coverage-badge' spec.metadata['homepage_uri'] = spec.homepage spec.metadata['source_code_uri'] = 'https://github.com/andreyors/coverage-badge' spec.metadata['changelog_uri'] = 'https://github.com/andreyors/coverage-badge/CHANGELOG.md' spec.files = Dir.chdir(File.expand_path(__dir__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(spec)/}) } end spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 2.2' spec.add_development_dependency 'rake', '~> 13.0' spec.add_development_dependency 'rspec', '~> 3.8.0' spec.add_development_dependency 'rspec-core', '~> 3.8.0' spec.add_development_dependency 'rubocop', '~> 1.37.1' spec.add_development_dependency 'simplecov', '~> 0.21.2' end
class UserMailer < ActionMailer::Base default from: 'popr.mailer@gmail.com' def activation_needed_email(user) @user = user @url = "http://popr.ca/users/#{@user.activation_token}/activate" mail(to: @user.email, subject: 'Activate Your Popr Account') end def activation_success_email(user) @user = user @url = "http://popr.ca/" mail(to: @user.email, subject: 'Popr Account Activated') end end
Deface::Override.new( virtual_path: "spree/admin/orders/_line_items", name: "add_additional_line_item_fields_partial_to_admin_order_view", insert_bottom: ".line-item-name", text: "<%= render partial: 'spree/shared/additional_line_item_fields', locals: {item: item} %>" )
FactoryBot.define do factory :team, class: Team do name { Faker::Name.unique.name } short_name { Faker::Name.unique.first_name } code { Faker::Number.unique.number(5) } end end
require 'rspec' require 'rack/test' require 'byebug' require_relative "../model/procesador_de_json" require "json" describe ProcesadorDeJson do include Rack::Test::Methods def app Sinatra::Application end describe "covertir el json de entrada a un hash" do it "debe devolver el json como un hash" do json_de_entrada = '{ "template":"Hola <nombre>,\n\r Por medio del presente mail te estamos invitando a <nombre_evento>, que se desarrollarรก en <lugar_del_evento>, el dรญa <fecha_del_evento>. Por favor confirmar su participaciรณn enviando un mail a <mail_de_confirmacion>.\n\rSin otro particular.La direccion", "contactos":[ { "nombre":"juan", "apellido":"perez", "mail":"juanperez@test.com" }, { "nombre":"maria", "apellido":"gonzalez", "mail":"mariagonzalez@test.com" } ], "datos":{ "remitente":"universidad@untref.com", "asunto":"Invitaciรณn a fiesta de fin de aรฑo", "nombre_evento":"la cena de fin de aรฑo de la UNTREF", "lugar_evento":"el Centro de estudios (avenida Directorio 887, Caseros)", "fecha_del_evento":"5 de diciembre", "Mail_de_confirmacion":"fiesta@untref.com" } }' hash = JSON.parse(json_de_entrada) expect(hash["template"]).to eq "Hola <nombre>,\n\r Por medio del presente mail te estamos invitando a <nombre_evento>, que se desarrollarรก en <lugar_del_evento>, el dรญa <fecha_del_evento>. Por favor confirmar su participaciรณn enviando un mail a <mail_de_confirmacion>.\n\rSin otro particular.La direccion" expect(hash["contactos"][0]["nombre"]).to eq "juan" expect(hash["datos"]["Mail_de_confirmacion"]).to eq "fiesta@untref.com" end end describe "Parsear el JSON de entrada y que cuente la cantidad de contactos que tiene" do it "El length del Hash del JSON parseado deberรญa devolver 2 por que tiene 2 contactos nada mรกs" do json = '{ "template":"Hola <nombre>,\n\r Por medio del presente mail te estamos invitando a <nombre_evento>, que se desarrollarรก en <lugar_del_evento>, el dรญa <fecha_del_evento>. Por favor confirmar su participaciรณn enviando un mail a <mail_de_confirmacion>.\n\rSin otro particular.La direccion", "contactos":[ { "nombre":"juan", "apellido":"perez", "mail":"juanperez@test.com" }, { "nombre":"maria", "apellido":"gonzalez", "mail":"mariagonzalez@test.com" } ], "datos":{ "remitente":"universidad@untref.com", "asunto":"Invitaciรณn a fiesta de fin de aรฑo", "nombre_evento":"la cena de fin de aรฑo de la UNTREF", "lugar_evento":"el Centro de estudios (avenida Directorio 887, Caseros)", "fecha_del_evento":"5 de diciembre", "Mail_de_confirmacion":"fiesta@untref.com" } }' hash_entrada = JSON.parse(json) expect(hash_entrada["contactos"].length).to eq 2 expect(hash_entrada["contactos"][0]["nombre"]).to eq "juan" end end describe "Json sin contactos" do it "deberia tirar error" do json = '{ "template":"Template test", "datos": {"remitente": "universidad@untref.com"} }' expect {ProcesadorDeJson.new(JSON.parse(json))}.to raise_error(ExcepcionJSONIncompleto) end end describe "ProcesadorDeJson" do it "probar la devolucion del procesador de json" do end end end
class Card < ActiveRecord::Base has_one :list has_many :members, class_name: "User" has_many :activities end
require_relative '../interface/iship' ## # The ship class holds the crew and is the main component on which # all the actions are invoked. It can't be directly accessed by the # crew. They can only use an interface for the ship. # class Ship attr_reader :interface, :data, :crew, :owner attr_accessor :result, :id ## # Creates the new ship. A crew can pass on any amount of data to # the new ship, as long as this is an hash. # def initialize( data = {} ) unless data.is_a? Hash raise TypeError.new "Data has to be a hash!" end ## # The resources of the ship # @resources = { :deuterium => { :value => 500, :capacity => 5000 } } ## # The components of the ship # @components = {} @components[ :command_center ] = build_command_center() @components[ :engine ] = build_engine() @components[ :reactor ] = build_reactor() @components[ :scanner ] = build_scanner() @components[ :collector ] = build_collector() @components[ :weapons_rack ] = build_weapons_rack() ## # The installed upgrades of the ship # @upgrades = {} @data = data @id = self.identifier end ## # # def rand( n = nil ) return @randomizer.rand if n.nil? return @randomizer.rand n end ## # # def bytes( n ) @randomizer.bytes n end ## # The ship identifier # def identifier self.object_id end ## # The ship dead status # def dead?() not alive?() end ## # The ship alive status # def alive?() amount_of( :deuterium ) > 0 end ## # The ship busy status # def busy?() command_center.busy? end ## # The ship location # def location() command_center.location end ## # Donates the ship to the owner and crew # def donate( owner, crew ) @owner = owner @crew = crew @randomizer = Random.new Space::Universe.rand( 2 ** 32 ) @interface = Interface.new self @crew.board @interface end ## # Checks the amount of resource # def amount_of( resource = :deuterium ) @resources[ resource ][ :value ] end ## # Checks the capacity of resource # def capacity( resource = :deuterium ) @resources[ resource ][ :capacity ] end ## # Collects the amount of resource # def collect( amount, resource = :deuterium ) before_amount = amount_of( resource ) @resources[ resource ][ :value ] = [ amount_of( resource ) + amount, capacity( resource ) ].min return amount_of( resource ) - before_amount end ## # Consumes the amount of resource # def consume( amount, resource = :deuterium ) before_amount = amount_of( resource ) @resources[ resource ][ :value ] = [ amount_of( resource ) - amount, 0 ].max return before_amount - amount_of( resource ) end ## # Damages the ship # def damage( value ) consume value, :deuterium end ## # Gets the command center # def command_center @components[ :command_center ] end ## # Gets the enige # def engine @components[ :engine ] end ## # Gets the reactor # def reactor @components[ :reactor ] end ## # Gets the scanner # def scanner @components[ :scanner ] end ## # Gets the collector # def collector @components[ :collector ] end ## # Gets the weapons rack # def weapons_rack @components[ :weapons_rack ] end ## # Scans this ship # def scan( scanner = nil ) return { :identifier => identifier, :owner => owner.identifier #:components => foreach component, scan it! } end ## # # def event( event ) #check if traveling TODO non_abortable = false result = @crew.event event if non_abortable or result return true end command_center.kill return false end def snapshot snapshot = self.clone #snapshot.components.map! { |c| c.snapshot } snapshot.id = self.id return snapshot end ## # Returns the string representation # def to_s @interface.to_s end protected def build_command_center CommandCenter.new self end def build_engine Engine.new self end def build_reactor Reactor.new self end def build_scanner Scanner.new self end def build_collector Collector.new self end def build_weapons_rack WeaponsRack.new self end end
require 'rails_helper' RSpec.describe BuyForm, type: :model do describe '#create' do before do @user = FactoryBot.create(:user) @item = FactoryBot.create(:item) @buy_form = FactoryBot.build(:buy_form, user_id: @user.id, item_id: @item.id) sleep 0.5 end context 'ๅ•†ๅ“ใŒ่ณผๅ…ฅใงใใ‚‹ๆ™‚' do it 'ๅฟ…่ฆใชๆƒ…ๅ ฑใ‚’้ฉๅˆ‡ใซๅ…ฅๅŠ›ใ™ใ‚‹ใจๅ•†ๅ“ใฎ่ณผๅ…ฅใŒใงใใ‚‹ใ“ใจ' do expect(@buy_form).to be_valid end it 'ๅปบ็‰ฉๅใŒๆŠœใ‘ใฆใ„ใฆใ‚‚ๅ•†ๅ“ใฎ่ณผๅ…ฅใŒใงใใ‚‹ใ“ใจ' do @buy_form.building_name = '' expect(@buy_form).to be_valid end end context 'ๅ•†ๅ“ใŒ่ณผๅ…ฅใงใใชใ„ๆ™‚' do it "tokenใŒ็ฉบใงใฏๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ" do @buy_form.token = '' @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Token can't be blank") end it "user_idใŒ็ฉบใงใฏๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ" do @buy_form.user_id = '' @buy_form.valid? expect(@buy_form.errors.full_messages).to include("User can't be blank") end it "item_idใŒ็ฉบใงใฏๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ" do @buy_form.item_id = '' @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Item can't be blank") end it '้ƒตไพฟ็•ชๅทใŒๅŠ่ง’่‹ฑๆ•ฐๅญ—ๆททๅˆใงใฏๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ' do @buy_form.postal_code = '111-aaaa' @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Postal code is invalid") end it '้ƒตไพฟ็•ชๅทใŒ็ฉบใงใฏๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ' do @buy_form.postal_code = '' @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Postal code can't be blank") end it '้ƒตไพฟ็•ชๅทใซใƒใ‚คใƒ•ใƒณใŒ็„กใ„ใจๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ' do @buy_form.postal_code = '1112222' @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Postal code is invalid") end it '้ƒฝ้“ๅบœ็œŒใŒๆœช้ธๆŠžใงใฏๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ' do @buy_form.shipping_area_id = 1 @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Shipping area must be other than 1") end it 'ๅธ‚ๅŒบ็”บๆ‘ใŒ็ฉบใงใฏๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ' do @buy_form.city = '' @buy_form.valid? expect(@buy_form.errors.full_messages).to include("City can't be blank") end it '็•ชๅœฐใŒ็ฉบใงใฏๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ' do @buy_form.address = '' @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Address can't be blank") end it '้›ป่ฉฑ็•ชๅทใŒ็ฉบใงใฏๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ' do @buy_form.phone_number = '' @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Phone number can't be blank") end it '้›ป่ฉฑ็•ชๅทใซใฏใƒใ‚คใƒ•ใƒณใ‚’ๅซใพใชใ„ๆญฃใ—ใ„ๅฝขๅผใงใชใ„ใจๅ•†ๅ“ใจ่ณผๅ…ฅใงใใชใ„ใ“ใจ' do @buy_form.phone_number = '090-1111-1111' @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Phone number is invalid") end it '้›ป่ฉฑ็•ชๅทใฏ11ๆกไปฅๅ†…ใงใชใ„ใจๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ' do @buy_form.phone_number = ('1' * 12) @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Phone number is invalid") end it '้›ป่ฉฑ็•ชๅทใฏๅ…จ่ง’ๆ•ฐๅญ—ใงใฏๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ' do @buy_form.phone_number = ('๏ผ‘' * 11) @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Phone number is invalid") end it '้›ป่ฉฑ็•ชๅทใŒๅŠ่ง’่‹ฑๆ–‡ๅญ—ใงใฏๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ' do @buy_form.phone_number = ('a' * 11) @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Phone number is invalid") end it '้›ป่ฉฑ็•ชๅทใŒๅŠ่ง’่‹ฑๆ•ฐๆททๅˆใงใฏๅ•†ๅ“ใ‚’่ณผๅ…ฅใงใใชใ„ใ“ใจ' do @buy_form.phone_number = 'a1a1a1a1a1a' @buy_form.valid? expect(@buy_form.errors.full_messages).to include("Phone number is invalid") end end end end
class User < ActiveRecord::Base has_many :user_beers has_many :beers, through: :user_beers def add_beer_to_favorites(beer) fav_beer = Beer.all.find_or_create_by(name: beer) self.beers << fav_beer unless self.get_favorite_beer_names.include?(beer) end def get_favorite_beer_names self.beers.map {|beer| beer.name} end def remove_beer_from_favorites(beer) self.beers.each do |fav| self.beers.delete(fav) if fav.name == beer end end end
class User < ActiveRecord::Base belongs_to :rating has_one :order has_one :task def as_json(options={}) super(:only => [:name,:phone,:rating], :include => { :rating => {:only => [:value]}, } ) end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception acts_as_token_authentication_handler_for User private def after_successful_token_authentication # renew_authentication_token! end end
require 'aws-sdk-s3' module OHOLFamilyTrees class FilesystemS3 attr_reader :bucket attr_reader :client attr_reader :default_metadata def initialize(bucket, metadata = {}) @bucket = bucket @client = Aws::S3::Client.new @default_metadata = metadata end def with_metadata(metadata) self.class.new(bucket, default_metadata.merge(metadata)) end def write(path, metadata = {}, &block) meta = default_metadata.merge(metadata) cache_control = meta.delete(:cache_control) content_type = meta.delete(:content_type) out = StringIO.new yield out #p [bucket, path] out.rewind client.put_object({ :body => out, :bucket => bucket, :key => path, :cache_control => cache_control, :content_type => content_type, :metadata => meta, }) end def read(path, &block) response = client.get_object({ :bucket => bucket, :key => path, }) yield response.body return true rescue Aws::S3::Errors::NoSuchKey p ['not found', path] return false end def open(path, &block) response = client.get_object({ :bucket => bucket, :key => path, }) return response.body rescue Aws::S3::Errors::NoSuchKey p ['not found', path] nil end def delete(path) client.delete_object({ :bucket => bucket, :key => path, }) rescue Aws::S3::Errors::NoSuchKey p ['not found', path] nil end def list(path) paths = [] response = client.list_objects_v2({ :bucket => bucket, :prefix => path, }) crazy = 0 token = nil begin response = client.list_objects_v2({ :bucket => bucket, :prefix => path, :continuation_token => token }) token = response.next_continuation_token paths += response.contents.map { |entry| entry.key } crazy += 1 end while response.is_truncated && crazy <= 200 return paths end end end
# U2.W4: Cipher Challenge # I worked on this challenge with: . # 1. Solution # Write your comments on what each thing is doing. # If you have difficulty, go into IRB and play with the methods. # Takes a string called coded_message then converts each character into a new element in an array # Outputs decoded message as string applying the cipher # The cipher is the index of the letter in the alphabet + cipher def north_korean_cipher(coded_message, cipher) input = coded_message.downcase.split("") # Converts coded_message string into array with each character as a new element decoded_sentence = [] # Initialize empty array alphabet = ("a".."z").to_a # If we wanted to use a Hash we could have incorporated .rotate whitespace = ['@', '#', '$', '%', '^', '&', '*'] input.each do |character| # Each is determining if a char in input is in the cipher or the whitespace array if alphabet.include?(character) decoded_sentence << alphabet[(alphabet.index(character) - cipher) % 26] # Add the letter four letters behind elsif whitespace.include?(character) decoded_sentence << " " else decoded_sentence << character end end decoded_sentence = decoded_sentence.join("") decoded_sentence.gsub!(/\d+/) { |num| num.to_i / 100 } #He's been known to exaggerate... return decoded_sentence # Returns the original message end # Your Refactored Solution # Driver Code: p north_korean_cipher("m^aerx%e&gsoi!", 4) == "i want a coke!" #This is driver code and should print true # Find out what Kim Jong Un is saying below and turn it into driver code as well. Driver Code statements should always return "true" p north_korean_cipher("syv@tistpi$iex#xli*qswx*hipmgmsyw*erh*ryxvmxmsyw%jsshw^jvsq^syv#1000000#tvsjmxefpi$jevqw.", 4)=="our people eat the most delicious and nutritious foods from our 10000 profitable farms." p north_korean_cipher("syv%ryoiw#evi#liph^xskixliv@fc^kveti-jpezsvih@xsjjii.*hsr'x%xipp&xli#yw!", 4)=="our nukes are held together by grape-flavored toffee. don't tell the us!" p north_korean_cipher("mj^csy&qeoi^sri*qmwxeoi,%kir.*vm@csrk-kmp,&csy^ampp*fi&vitpegih*fc@hirrmw&vshqer.", 4)=="if you make one mistake, gen. ri yong-gil, you will be replaced by dennis rodman." p north_korean_cipher("ribx^wxst:$wsyxl%osvie,$xlir$neter,#xlir%xli%asvph!", 4)=="next stop: south korea, then japan, then the world!" p north_korean_cipher("ger^wsqifshc*nywx^kix^qi&10000*fekw@sj$gssp%vergl@hsvmxsw?", 4)=="can somebody just get me 100 bags of cool ranch doritos?" # Reflection # .invert swaps hashes and keys # .rotate on array # .cycle # .shuffle array mixes up elements
require 'sinatra' get '/' do "Hello World #{params[:name]}".strip end # ENV['RACK_ENV'] = 'test' # # # require 'hello_world' # # require 'test/unit' # require 'rack/test' # # class HelloWorldTest < Test::Unit::TestCase # include Rack::Test::Methods # # def app # Sinatra::Application # end # # def test_it_says_hello_world # get '/' # assert last_response.ok? # assert_equal 'Hello World', last_response.body # end # # def test_it_says_hello_to_a_person # get '/', :name => 'Simon' # assert last_response.body.include?('Simon') # end # end # require 'sinatra' # require 'json' # # get "/people" do # "hi class" # end
class CompanyInformationController < ApplicationController before_action :authenticate_user! def index @company_information = CompanyInformation.first() end end
# ะผะพะดะตะปัŒ ัะปะตะผะตะฝั‚ะฐ ะผะตะฝัŽ class MenuItem < ActiveRecord::Base include MultilingualModel include AutotitleableModel default_scope { order('weight') } translates :title belongs_to :page belongs_to :menu has_many :menu_items belongs_to :menu_item validates :name, presence: true # ะฐะปะธะฐั: ะฒะปะพะถะตะฝะฝั‹ะต ัะปะตะผะตะฝั‚ั‹ def items menu_items end # ั€ะพัƒั‚ั‹ ะฟั€ะธะฒัะทะฐะฝะฝะพะน ัั‚ั€ะฐะฝะธั†ั‹ def routes page.routes end # ัƒั€ะป ะฟั€ะธะฒัะทะฐะฝะฝะพะน ัั‚ั€ะฐะฝะธั†ั‹ def url unless page.nil? page.url else self[:url] end end # ะณะตะฝะตั€ะฐั†ะธั ะผะตั‚ะพะดะฐ ั…ะตะปะฟะตั€ะฐ ั€ะพัƒั‚ะฐ ะฟะพ ะฟั€ะธะฒัะทะฐะฝะฝะพะน ัั‚ั€ะฐะฝะธั†ะต def path unless page.nil? page.routes.first[:as] + '_path' end end end
class AddDefaultRecords < ActiveRecord::Migration[6.0] def change User.create(:id => 1, :user_name => '--') ['New', 'In Progress', 'Finished'].each_with_index do |state, index| State.create(:id => index + 1, :state_name => state) end end end
class Httest < Formula desc "Provides a large variety of HTTP-related test functionality." homepage "https://htt.sourceforge.io/" url "https://downloads.sourceforge.net/project/htt/htt2.4/httest-2.4.19/httest-2.4.19.tar.gz" sha256 "0cf2454de50995c14c460040cdf29863dd49082805e2bc61fb6938a7042b2dbd" bottle do cellar :any sha256 "a87b607ce09404d86f282acb62eb0481c8a2932396453fa4c9ce7cf1fb353d2d" => :high_sierra sha256 "639ccc35988ae5df41ee3774343df00c447698453fcd9958a247ce81f0a24de2" => :sierra sha256 "8d69771ad06e4d2e2bdd692255d8e55f272338414e5998b106dac669d96bba96" => :el_capitan sha256 "9d738b97356995a8e8cf68aa25cb7ebba74c659ffbf0d8f33f9a8984482ec36a" => :yosemite end depends_on "apr" depends_on "apr-util" depends_on "openssl" depends_on "pcre" depends_on "lua" def install # Fix "fatal error: 'pcre/pcre.h' file not found" # Reported 9 Mar 2017 https://sourceforge.net/p/htt/tickets/4/ (buildpath/"brew_include").install_symlink Formula["pcre"].opt_include => "pcre" ENV.prepend "CPPFLAGS", "-I#{buildpath}/brew_include" system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--with-apr=#{Formula["apr"].opt_bin}", "--enable-lua-module" system "make", "install" end test do (testpath/"test.htt").write <<~EOS CLIENT 5 _TIME time END EOS system bin/"httest", "--debug", testpath/"test.htt" end end
Rails.application.routes.draw do resources :news_items root 'news_items#index' end
๏ปฟ#coding:utf-8 require 'selenium-webdriver' require 'cucumber/rb_support/rb_dsl' module Mgl module Test module Helper # ๅฏๅŠจWebdriver # @return driver def self.setup_selenium profile_name='',url = 'http://localhost:4444/wd/hub',timeouts = 5,&profile_settings profile = Selenium::WebDriver::Firefox::Profile.from_name profile_name profile = Selenium::WebDriver::Firefox::Profile.new if profile.nil? profile["intl.accept_languages"] = "zh-cn,zh" profile_settings.call(profile) unless profile_settings.nil? caps = Selenium::WebDriver::Remote::Capabilities.firefox(:firefox_profile => profile) client = Selenium::WebDriver::Remote::Http::Default.new client.timeout = 180 # seconds driver = Selenium::WebDriver.for(:remote,:url => url,:http_client => client,:desired_capabilities => caps) driver.manage.timeouts.implicit_wait = timeouts return driver end #ๅœบๆ™ฏๅคฑ่ดฅๅฐฑๆˆชๅ›พไฟๅญ˜ไธ‹ๆฅ def self.screenshot_for_failed scenario,driver if scenario.failed? url = driver.current_url unless url.empty? puts "้”™่ฏฏ็š„ๆˆชๅ›พ็š„url = #{url}" #ๆ‰“ๅฐๅ‡บurl๏ผŒไพฟไบŽๅคๆŸฅ screenshot_name = url.gsub(/[\.\/:,?|]/,'_') + '.png' #ๅŽป้™ค็‰นๆฎŠ็ฌฆๅท๏ผŒ็”จ_ไปฃๆ›ฟ filePath = File.join("..","Reports",ENV['BUILD_NUMBER'],"screenshot",screenshot_name) #ๆณจๆ„:ๆˆชๅ›พ่ทฏๅพ„ไธŽrake_helper.rbๅŒๆญฅไฟฎๆ”น driver.save_screenshot(filePath) end end end #ๅ…ณ้—ญๆต‹่ฏ•ไธญๆ‰“ๅผ€็š„็ช—ๅฃ๏ผŒๅ›žๅˆฐไธป็ช—ๅฃ def self.back_mainwindow driver,main_handle for handle in driver.window_handles driver.switch_to.window handle if handle != main_handle driver.close end end driver.switch_to.window main_handle return driver end #ๆฃ€ๆŸฅurlๆ˜ฏๅฆ้œ€่ฆๆต‹่ฏ• def self.valid_url url,all_test_urls,step @url_valid = false all_test_urls.each do |oneline| @url_valid = true if oneline.include? url end step.pending "#{url}ไธๅœจๆต‹่ฏ•่Œƒๅ›ด" unless @url_valid end end # Helper end # Test end # Mgl
# Class Maglev::System is identically Smalltalk System # # == Persistent Shared Counters # # Maglev::System maintins a set of persistent shared counters. # # Persistent shared counters provide a means for multiple sessions to share # common integer values. There are 128 persistent shared counters, # numbered from 1 to 128 (the index of the first counter is 1. # # Each update to a persistent shared counter causes a roundtrip to the # stone process. However reading the value of a counter is handled by the # gem (and its page server, if any) and does not cause a roundtrip to the # stone. # # Persistent shared counters are globally visible to all sessions on all # shared page caches. # # Persistent shared counters hold 64 bit values and may be set to any # signed 64 bit integer value. No limit checks are done when incrementing # or decrementing a counter. Attempts to increment/decrement the counter # above/below the minimum/maximum value of a signed 64-bit integer will # cause the counter to 'roll over'. # # Persistent shared counters are independent of database transactions. # Updates to counters are visible immediately and aborts have no effect on # them. # # The values of all persistent shared counters are written to the primary # database extent at checkpoint time. Updates between checkpoints are # written to the transaction log by the stone. Therefore the state of the # persistent shared counters is recoverable after a crash, restore from # backup, and restore from transaction logs. # # Persistent shared counter performance is affected by the stone # configuration option STN_COMMITS_ASYNC. Setting this option to TRUE will # result in faster update performance because the stone will respond to # update requests after the tranlog write has been queued but before it # completes. Operating in this mode leaves a small chance of losing data # should the stone or host machine crash after the tranlog write was queued # but before it completes. If this value is set to FALSE, the stone will # only respond to update requests after the tranlog write has completed." # module Maglev # System resolved to Smalltalk class in System1.rb class System # Transaction support class_primitive '__commitTransaction', 'commitTransaction' class_primitive '__abortTransaction', 'abortTransaction' class_primitive '__beginTransaction', 'beginTransaction' def self.commit_transaction __commitTransaction end def self.abort_transaction __abortTransaction end def self.begin_transaction __beginTransaction end # Raise an exception if specified temporary object is added to the # closure list during an attempt to commit. Useful in debugging # errors due to attempt to commit not-commitable objects or classes. # The exception details will include the parent object which triggered # the add to closure list. # Takes a single argument, a not-committed object. # An argument of nil shuts off a previous trap . # # Should be used with maglev-ruby -d . After control returns # topaz prompt with an error use 'stack save' # and then SEND of Object>>findReferencesInMemory: to navigate upwards # from the object given by the error argument. class_primitive 'trap_add_to_closure_list', 'trapAddToClosureList:' class_primitive_nobridge '__object_for_oop', '_objectForOop:' # used by ObjectSpace # implementation is Object>>_objectForOop: but putting class_prim directives # in Object or Fixnum may upset results of Object.singleton_methods ... class_primitive 'session_temp' , '_sessionTempsAt:' # returns nil if not found class_primitive 'session_temp_put', '_sessionTempsAt:put:' # returns value stored # _processInfo includes getuid getgid, getpid, kill and related functions class_primitive_nobridge '__process_info', '_processInfo:with:with:' class_primitive_nobridge '__host_times', '_hostTimes' # Return the real uid for the server process def self.getuid __process_info(0, nil, nil) end # Return the effective uid for the server process def self.geteuid __process_info(1, nil, nil) end # Return the real group id for the server process def self.getgid __process_info(2, nil, nil) end # Return the effective group id for the server process def self.getegid __process_info(3, nil, nil) end # Return the process id for the server process def self.getpid __process_info(8, nil, nil) end # Return the process group id for the server process def self.getpgrp __process_info(9, nil, nil) end # Return the parent process id for the server process def self.getppid __process_info(10, nil, nil) end class_primitive_nobridge '__increment_pcounter', 'persistentCounterAt:incrementBy:' class_primitive_nobridge '__decrement_pcounter', 'persistentCounterAt:decrementBy:' # Get the value of the persistent counter +arg+. +arg+ must be in # range 1 <= arg <= 128. # # See Maglev::System class comments for details on persistent counters. class_primitive_nobridge 'pcounter', 'persistentCounterAt:' # Sets the persistent shared counter at index to the specified # value. value must be a SmallInteger or LargeInteger. # For a LargeInteger, amount must be representable as a signed # 64-bit integer (between -9223372036854775808 and 9223372036854775807). # # Returns value, the new value of the counter. # # See Maglev::System class comments for details on persistent counters. class_primitive_nobridge 'set_pcounter', 'persistentCounterAt:put:' # Increments the persistent shared counter at index by the specified # amount. Amount must be a SmallInteger or LargeInteger. For a # LargeInteger, amount must be representable as a signed 64-bit integer # (between -9223372036854775808 and 9223372036854775807). # # Returns the new value of the counter after the increment. # # See Maglev::System class comments for details on persistent counters. def self.increment_pcounter(counter, by=1) __increment_pcounter(counter, by) end # Decrements the persistent shared counter at index by the specified # amount. amount. Amount must be a SmallInteger or LargeInteger. For a # LargeInteger, amount must be representable as a signed 64-bit integer # (between -9223372036854775808 and 9223372036854775807). # # Returns the new value of the counter after the decrement. # # See Maglev::System class comments for details on persistent counters. def self.decrement_pcounter(counter, by=1) __decrement_pcounter(counter, by) end # Methods for looking at the size of Temporary Object Space (a major # contributer to the VM memory footprint) # Returns the approximate number of bytes of temporary object memory # being used to store objects. class_primitive 'temp_obj_space_used', '_tempObjSpaceUsed' # Returns the approximate maximum number of bytes of temporary object # memory which is usable for storing objects. class_primitive 'temp_obj_space_max', '_tempObjSpaceMax' # Returns the approximate percentage of temporary object memory which # is in use to store temporary objects. This is equivalent to the # expression: # # (System.temp_obj_space_used * 100) / (System.temp_obj_space_max) # # Note that it is possible for the result to be slightly greater than # 100%. This result indicates temporary memory is almost completely # full. class_primitive 'temp_obj_space_percent_used', '_tempObjSpacePercentUsed' end end
class Meme < ApplicationRecord belongs_to :memer, class_name: "User" has_many :captions has_many :comments, as: :commentable has_many :votes, as: :voteable validates :photo, presence: true validates :memer_id, presence: true def total_votes vote_total = 0 self.votes.each do |vote| vote_total += vote.value end vote_total end def order_captions self.captions.order('favorite DESC, created_at') end def more_than_one_favorite? self.captions.select { |caption| caption.favorite == true }.length == 1 end def unfavorite_all_captions self.captions.each do |caption| caption.favorite = false caption.save end end end
require 'forwardable' # An object representing a Marketo Lead record. class MarketoAPI::Lead extend Forwardable include Enumerable NAMED_KEYS = { #:nodoc: id: :IDNUM, cookie: :COOKIE, email: :EMAIL, lead_owner_email: :LEADOWNEREMAIL, salesforce_account_id: :SFDCACCOUNTID, salesforce_contact_id: :SFDCCONTACTID, salesforce_lead_id: :SFDCLEADID, salesforce_lead_owner_id: :SFDCLEADOWNERID, salesforce_opportunity_id: :SFDCOPPTYID }.freeze KEY_TYPES = MarketoAPI.freeze(*NAMED_KEYS.values) #:nodoc: private_constant :KEY_TYPES # The Marketo ID. This value cannot be set by consumers. attr_reader :id # The Marketo tracking cookie. Optional. attr_accessor :cookie # The attributes for the Lead. attr_reader :attributes # The types for the Lead attributes. attr_reader :types # The proxy object for this class. attr_reader :proxy def_delegators :@attributes, :[], :each, :each_pair, :each_key, :each_value, :keys, :values ## # :method: [](hash) # :call-seq: # lead[attribute_key] # # Looks up the provided attribute. ## # :method: each # :call-seq: # each { |key, value| block } # # Iterates over the attributes. ## # :method: each_pair # :call-seq: # each_pair { |key, value| block } # # Iterates over the attributes. ## # :method: each_key # :call-seq: # each_key { |key| block } # # Iterates over the attribute keys. ## # :method: each_value # :call-seq: # each_value { |value| block } # # Iterates over the attribute values. ## # :method: keys # :call-seq: # keys() -> array # # Returns the attribute keys. ## # :method: values # :call-seq: # values() -> array # # Returns the attribute values. def initialize(options = {}) @id = options[:id] @attributes = {} @types = {} @foreign = {} self[:Email] = options[:email] self.proxy = options[:proxy] yield self if block_given? end ## # :method: []=(hash, value) # :call-seq: # lead[key] = value -> value # # Looks up the provided attribute. def []=(key, value) @attributes[key] = value @types[key] ||= infer_value_type(value) end # :attr_writer: # :call-seq: # lead.proxy = proxy -> proxy # # Assign a proxy object. Once set, the proxy cannot be unset, but it can be # changed. def proxy=(value) @proxy = case value when nil defined?(@proxy) && @proxy when MarketoAPI::Leads value when MarketoAPI::ClientProxy value.instance_variable_get(:@client).leads when MarketoAPI::Client value.leads else raise ArgumentError, "Invalid proxy type" end end # :call-seq: # lead.foreign -> nil # lead.foreign(type, id) -> { type: type, id: id } # lead.foreign -> { type: type, id: id } # # Sets or returns the foreign system type and person ID. def foreign(type = nil, id = nil) @foreign = { type: type.to_sym, id: id } if type and id @foreign end # :attr_reader: email def email self[:Email] end # :attr_writer: email def email=(value) self[:Email] = value end # Performs a Lead sync and returns the new Lead object, or +nil+ if the # sync failed. # # Raises an ArgumentError if a proxy has not been configured with # Lead#proxy=. def sync raise ArgumentError, "No proxy configured" unless proxy proxy.sync(self) end # Performs a Lead sync and updates this Lead object in-place, or +nil+ if # the sync failed. # # Raises an ArgumentError if a proxy has not been configured with # Lead#proxy=. def sync! if lead = sync @id = lead.id @cookie = lead.cookie @foreign = lead.foreign @proxy = lead.proxy removed = self.keys - lead.keys lead.each_pair { |k, v| @attributes[k] = v @types[k] = lead.types[k] } removed.each { |k| @attributes.delete(k) @types.delete(k) } self end end # Returns a lead key structure suitable for use with # MarketoAPI::Leads#get. def params_for_get self.class.key(:IDNUM, id) end # Returns the parameters required for use with MarketoAPI::Leads#sync. def params_for_sync { returnLead: true, marketoCookie: cookie, leadRecord: { Email: email, Id: id, ForeignSysPersonId: foreign[:id], ForeignSysType: foreign[:type], leadAttributeList: { attribute: attributes.map { |key, value| { attrName: key.to_s, attrType: types[key], attrValue: value } } } }.delete_if(&MarketoAPI::MINIMIZE_HASH) }.delete_if(&MarketoAPI::MINIMIZE_HASH) end class << self # Creates a new Lead from a SOAP response hash (from Leads#get, # Leads#get_multiple, Leads#sync, or Leads#sync_multiple). def from_soap_hash(hash) #:nodoc: lead = new(id: hash[:id].to_i, email: hash[:email]) do |lr| if type = hash[:foreign_sys_type] lr.foreign(type, hash[:foreign_sys_person_id]) end hash[:lead_attribute_list][:attribute].each do |attribute| name = attribute[:attr_name].to_sym lr.attributes[name] = attribute[:attr_value] lr.types[name] = attribute[:attr_type] end end yield lead if block_given? lead end # Creates a new Lead key hash suitable for use in a number of Marketo # API calls. def key(key, value) { leadKey: { keyType: key_type(key), keyValue: value } } end private def key_type(key) key = key.to_sym res = if KEY_TYPES.include? key key else NAMED_KEYS[key] end raise ArgumentError, "Invalid key #{key}" unless res res end end def ==(other) id == other.id && cookie == other.cookie && foreign == other.foreign && attributes == other.attributes && types == other.types end def inspect "#<#{self.class} id=#{id} cookie=#{cookie} foreign=#{foreign.inspect} attributes=#{attributes.inspect} types=#{types.inspect}>" end private def infer_value_type(value) case value when Integer 'integer' when Time, DateTime 'datetime' else 'string' end end end
class CargoWagon < Wagon validate :total_volume, :max, 80 def to_s "ะ“ั€ัƒะทะพะฒะพะน ะฒะฐะณะพะฝ ั ะดะพัั‚ัƒะฟะฝั‹ะผ ะพะฑัŠะตะผะพะผ: #{available_volume} ะผ3 (#{occupied_volume} ะผ3 ะทะฐะฝัั‚ะพ)" end end
class Event < ActiveRecord::Base has_many :event_dates, :order=>:event_date has_many :roles, :dependent =>:destroy has_many :users, :through => :roles has_many :domains def admin?(user) user && roles.admin.where(:user_id=>user.id).size > 0 end def creator?(user) user && roles.creator.where(:user_id=>user.id).size > 0 end def self.find_by_host(host) Event.joins(:domains).where('domains.domain'=>host).includes(:event_dates).first end end
class RegistrationsController < ApplicationController before_filter :authenticate_user! before_action :set_open_mat def index @registrations = @open_mat.registrations end def new @registration = @open_mat.registrations.new end def create @registration = @open_mat.registrations.new @registration.user = current_user if @registration.save redirect_to @open_mat, notice: "Thanks for your registration!" else render :new end end private def registration_params params.require(:registration).permit(:user_id) end def set_open_mat @open_mat = OpenMat.find(params[:open_mat_id]) end end
module CapybaraSelenium module AppServer class BaseConfigurator < Server::Configurator def apply Capybara.server_host = host Capybara.server_port = port Capybara.app_host = url end end # Class responsible for applying to Capybara the configuration of a Rack # Web Application class RackConfigurator < BaseConfigurator def apply super fail 'Invalid config.ru file path' unless File.exist? config_ru_path Capybara.app = Rack::Builder.parse_file(config_ru_path).first end end end end
require_relative 'card' require_relative 'view' class Controller attr_accessor :card_counter, :correct_answer_counter def initialize @deck = Deck.new @view = View.new @input = "" @current_answer = nil @correct_answer_counter = 0 @card_counter = 0 @total_cards = deck.size end def run! view.greet show_flashcard end private def show_flashcard self.card_counter += 1 give_definition parse_user_input end def give_definition new_card = get_new_card self.current_answer = new_card.answer view.show_definition(new_card, card_counter) end def get_new_card new_card = deck.new_card new_card == "empty" ? view.game_over(total_cards, correct_answer_counter) : new_card end def parse_user_input self.input = view.get_input if input == "exit" view.game_over(total_cards, correct_answer_counter) elsif input == "skip" view.skip_card deck.put_back_in_deck show_flashcard else check_answer end end def check_answer if current_answer == input self.correct_answer_counter += 1 view.correct_answer show_flashcard else view.incorrect_answer parse_user_input end end attr_reader :deck, :view attr_accessor :input, :current_answer, :total_cards end Controller.new.run!
module Components module Button class ButtonComponent < Middleman::Extension helpers do def button(opts) return link_to(opts[:text], opts[:href], build_button_html(opts)) if opts[:link] content_tag(:button, opts[:text], build_button_html(opts)) end def build_button_html(opts) additional_classes = opts.dig(:html, :class) ? " #{opts[:html][:class]}" : '' combined_classes = "p-4 h-auto font-medium transition-all border-2 border-solid #{button_type(opts[:type].to_s)}#{additional_classes} motion-reduce:transition-none motion-reduce:transform-none" opts[:html] ||= {} opts[:html][:class] = combined_classes opts[:html] end def button_type(type) lists = { 'default' => 'bg-transparent text-green-default border-green-default hover:text-green-darker hover:border-green-darker', 'default_white' => 'bg-transparent text-white border-white hover:text-gray-100 hover:border-gray-100', 'default_gray' => 'bg-gray-400 border-gray-400 text-white hover:bg-gray-500 hover:border-gray-500', 'primary' => 'bg-green-default border-green-default text-white hover:bg-green-darker hover:border-green-darker' } lists[type] end end end end end ::Middleman::Extensions.register(:button_component, Components::Button::ButtonComponent)
module LEDENET module Functions VALUES = [ SEVEN_COLOR_CROSS_FADE = 0x25, RED_GRADUAL_CHANGE = 0x26, GREEN_GRADUAL_CHANGE = 0x27, BLUE_GRADUAL_CHANGE = 0x28, YELLOW_GRADUAL_CHANGE = 0x29, CYAN_GRADUAL_CHANGE = 0x2A, PURPLE_GRADUAL_CHANGE = 0x2B, WHITE_GRADUAL_CHANGE = 0x2C, RED_GREEN_CROSS_FADE = 0x2D, RED_BLUE_CROSS_FADE = 0x2E, GREEN_BLUE_CROSS_FADE = 0x2F, SEVEN_COLOR_STROBE_FLASH = 0x30, RED_STROBE_FLASH = 0x31, GREEN_STROBE_FLASH = 0x32, BLUE_STROBE_FLASH = 0x33, YELLOW_STROBE_FLASH = 0x34, CYAN_STROBE_FLASH = 0x35, PURPLE_STROBE_FLASH = 0x36, WHITE_STROBE_FLASH = 0x37, SEVEN_COLOR_JUMPING_CHANGE = 0x38, NO_FUNCTION = 0x61 ] def self.all_functions LEDENET::Functions.constants.reject { |x| x == :VALUES } end def self.value_of(i) all_functions.select { |x| self.const_get(x) == i }.first end end end
class CreateOrganizations < ActiveRecord::Migration[5.2] def change create_table :organizations do |t| t.string :name t.string :email t.string :phone t.string :address t.string :website t.string :scales t.text :description t.attachment :avatar t.string :website t.integer :founded t.attachment :form_cv t.boolean :verified, default: false t.timestamps end end end
module EasyRakeTasksHelper def task_period_caption(task) l(:"easy_rake_tasks.periods.#{task.period}", :interval => task.interval) end def task_info_status(task_info) case task_info.status when EasyRakeTaskInfo::STATUS_RUNNING l(:'easy_rake_task_infos.status.running') when EasyRakeTaskInfo::STATUS_ENDED_OK l(:'easy_rake_task_infos.status.ended_ok') when EasyRakeTaskInfo::STATUS_ENDED_FAILED l(:'easy_rake_task_infos.status.ended_failed') end end end
class RemoveImageUrLfromCacheResources < ActiveRecord::Migration[5.2] def change remove_column :cache_resources, :image_url end end
class Plug::SockJS def initialize @handlers = {} end def on(message, &block) (@handlers[message] ||= []) << block end def send(action, param) hash = { "a" => action, "p" => param, "t" => DateTime.now.strftime('%Q') } #puts ">> #{hash.to_json}" @socket.send([hash.to_json].to_json) end def connect(token) disconnect id = rand(1..999) sessionid = "btsune#{Time.now.to_i}" @socket = Faye::WebSocket::Client.new( "wss://shalamar.plug.dj/socket/#{id}/#{sessionid}/websocket", nil, :tls => {:ssl_version => :TLSv1}) @socket.on(:open) { process_open(token) } @socket.on(:message) { |f| process_frame(f.data) } @socket.on(:close) { |f| process_close(f.code) } @socket.on(:error) { puts "Error" } end def disconnect @socket.close if @socket end private def process_open(token) puts "[SockJS] Socket Opened" send("auth", token) call_handler("socketOpen") end def process_frame(frame) message_type = frame[0] case message_type when "o" # Open: NOOP when "a" data = JSON.parse(frame[3..-3]) call_handler("socketMessage", data) when "h" # ping pong circulate when "c" call_handler("socketClose") end end def process_close(code) puts "[SockJS] Socket Closed (#{code})" call_handler("socketClose") end def call_handler(handler_name, data=nil) if @handlers.has_key?(handler_name) @handlers[handler_name].each do |handler| handler.call(data) end end end end
RouteTranslator.config do |config| config.generate_unnamed_unlocalized_routes = true end
require 'thor' require 'rugged' module Relsr class Issue < Thor desc 'checkout ISSUE_NO', 'Checkout an issue locally. Creates a new branch if required' def checkout(issue) local_branch_for(issue) || remote_branch_for(issue) end map co: :checkout private def local_branch_for(issue) git.branches.each(:local) do |branch| if branch.name.start_with? "feature/##{issue}-" puts "Checking out local branch '#{branch}'".green git.checkout(branch.name) return true end end false end def remote_branch_for(issue) git.fetch('origin') return git.branches.each(:remote) do |branch| local_name = branch.name[branch.remote_name.size+1..-1] if local_name.start_with? "feature/##{issue}-" puts "Checking out and tracking remote branch '#{local_name}'".green new_branch = git.branches.create(local_name, branch.name) new_branch.upstream = branch git.checkout(local_name) return true end end false end def git @git ||= Rugged::Repository.new(Dir.pwd) end def fetch puts "fetching..." git.remotes.each { |remote| remote.fetch } end end end
require "rails_helper" describe "add project" do it "adds a new project to category" do admin = FactoryGirl.create(:admin) login_as(admin, :scope => :admin) category = FactoryGirl.create(:category) visit '/' click_on 'Add a Category' click_link('Rails', match: :first) click_on 'Add a Project' fill_in 'Project Name', with: 'pizza' fill_in 'Description of Project', with: 'it has pepperoni' fill_in 'Link to GitHub', with: 'git_something' click_on 'Create Project' expect(page).to have_content 'pizza' end it "gives error when no name is entered" do admin = FactoryGirl.create(:admin) login_as(admin, :scope => :admin) category = FactoryGirl.create(:category) visit '/' click_on 'Add a Category' click_link('Rails', match: :first) click_on 'Add a Project' fill_in 'Project Name', with: '' fill_in 'Description of Project', with: '' fill_in 'Link to GitHub', with: '' click_on 'Create Project' expect(page).to have_content 'errors' end end
class SessionsController < ApplicationController def new redirect_to root_path if logged_in? end def create @user = User.find_by(name: params[:name]) if @user && @user.authenticate(params[:password]) cookies.signed[:user_id] = @user.id flash[:success] = "You are now logged in." redirect_to root_path else flash[:error] = "Something went wrong." redirect_to sign_in_path end end def destroy cookies.delete :user_id flash[:success] = "You are now logged out." redirect_to sign_in_path end end
require_relative "../require/macfuse" class WdfsMac < Formula desc "Webdav file system" homepage "http://noedler.de/projekte/wdfs/" url "http://noedler.de/projekte/wdfs/wdfs-1.4.2.tar.gz" sha256 "fcf2e1584568b07c7f3683a983a9be26fae6534b8109e09167e5dff9114ba2e5" license "GPL-2.0-or-later" bottle do root_url "https://github.com/gromgit/homebrew-fuse/releases/download/wdfs-mac-1.4.2" sha256 cellar: :any, big_sur: "8e9cbe0059e88abf08f411c3b30b63c6a5b73e57a2d150a4cdfcded9e02863ac" sha256 cellar: :any, catalina: "ff22c3b38115e75154a5bfd334481acc8594f04486cd667ab5f0a78fd9be67b9" sha256 cellar: :any, mojave: "a8a7c080c4e56fe4b8eebaf6f66d594ebd72f5155ae01aa33e704883625e615b" end depends_on "pkg-config" => :build depends_on "glib" depends_on MacfuseRequirement depends_on :macos depends_on "neon" def install setup_fuse system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do system "#{bin}/wdfs", "-v" end end
class ConsumersController < ApplicationController load_and_authorize_resource def update @consumer.update!(update_params) render json: { consumer: ConsumerSerializer.new(@consumer) }, status: :ok end private def update_params params.require(:consumer).permit(:first_name, :last_name) end end
card_number = "4024007136512380" valid = false card = card_number.reverse.split("") double_card = card.map.with_index do |n, i| if i.odd? (n.to_i) * 2 else n.to_i end end def sum_digits(number) number.map do |n| n.to_i end .reduce(:+) end sum_products = double_card.map do |n| if n > 9 sum_digits(n.to_s.split("")) else n end end total = sum_products.reduce(:+) if total % 10 == 0 p "The number is valid!" else p "The number is invalid" end
require './lib/craft' RSpec.describe Craft do let(:craft) { Craft.new('knitting', {yarn: 20, scissors: 1, knitting_needles: 2}) } describe '#initialize' do it 'exists' do expect(craft).to be_a(Craft) end it 'has a name' do expect(craft.name).to eq('knitting') end it 'has required supplies' do expect(craft.supplies_required).to eq({:yarn => 20, :scissors => 1, :knitting_needles => 2}) end end end
module Log::Filter def write_level?(message_level) if message_level.nil? && !logger_level? return true end if message_level.nil? || !logger_level? return false end precedent?(message_level) end def precedent?(message_level) ordinal(message_level) <= logger_ordinal end def write_tag?(message_tags) message_tags ||= [] if message_tags.empty? && !logger_tags? return true end if log_all_tags? return true end if message_tags.empty? && log_untagged? return true end if !message_tags.empty? && logger_tags? if logger_tags_intersect?(message_tags) return true end end false end def log_all_tags? logger_tag?(:_all) end def log_untagged? logger_tag?(:_untagged) end def tags_intersect?(message_tags) if !(message_tags & logger_excluded_tags).empty? return false end !(logger_included_tags & message_tags).empty? end alias :logger_tags_intersect? :tags_intersect? end
#Override Jeweler's classes for properly configure a BioRuby Development Environment/Layout. # This module should only include methods that are overridden in Jeweler (by # breaking open the Jeweler::Generator class require 'bio-gem/mod/jeweler/options' require 'bio-gem/mod/jeweler/github_mixin' require 'bio-gem/mod/biogem' class Jeweler class Generator include Biogem::Naming include Biogem::Path include Biogem::Render include Biogem::Github alias original_initialize initialize def initialize(options = {}) original_initialize(options) # RCov is not properly supported in Ruby 1.9.2, so we remove it development_dependencies.delete_if { |k,v| k == "rcov" } # Jeweler has a bug for bundler development_dependencies.delete_if { |k,v| k == "bundler" } development_dependencies.delete_if { |k,v| k == "jeweler" } development_dependencies << ["jeweler",'~> 1.8.4", :git => "https://github.com/technicalpickles/jeweler.git'] development_dependencies << ["bundler", ">= 1.0.21"] # development_dependencies << ["bio-logger"] development_dependencies << ["bio", ">= 1.4.2"] # we add rdoc because of an upgrade of rake RDocTask causing errors development_dependencies << ["rdoc","~> 3.12"] if options[:biogem_db] development_dependencies << ["activerecord", ">= 3.0.7"] development_dependencies << ["activesupport", ">= 3.0.7"] development_dependencies << ["sqlite3", ">= 1.3.3"] end development_dependencies << ['systemu', '>=2.5.2'] if options[:wrapper] end alias original_project_name project_name def project_name name = original_project_name return 'bio-'+name if name !~ /^bio-/ name end alias original_render_template render_template def render_template(source) buf = original_render_template(source) # call hook (returns edited buf) after_render_template(source,buf) end def target_dir project_name.sub('bio','bioruby') end alias github_repo_name target_dir alias original_create_files create_files # this is the default directory for storing library datasets # creates a data directory for every needs. #the options are defined in mod/jeweler/options.rb def create_files create_plugin_files end def puts_template_message(message, length=70, padding=4) puts "*"*(length+padding*2+2) puts "*"+" "*(length+padding*2)+"*" message=message.join("\n") if message.kind_of? Array message.scan(/.{1,70}/).map do |sub_message| puts "*"+" "*padding+sub_message+" "*(length-sub_message.size+padding)+"*" end puts "*"+" "*(length+padding*2)+"*" puts "*"*(length+padding*2+2) end def create_and_push_repo puts "Please provide your Github password to create the Github repository" begin login = github_username password = ask("Password: ") { |q| q.echo = false } github = Github.new(:login => login.strip, :password => password.strip) github.repos.create(:name => github_repo_name, :description => summary) rescue Github::Error::Unauthorized puts "Wrong login/password! Please try again" retry rescue Github::Error::UnprocessableEntity raise GitRepoCreationFailed, "Can't create that repo. Does it already exist?" end # TODO do a HEAD request to see when it's ready? @repo.push('origin') end end #Generator end #Jeweler
# frozen_string_literal: true describe Facts::Macosx::Identity::Group do describe '#call_the_resolver' do subject(:fact) { Facts::Macosx::Identity::Group.new } let(:value) { 'staff' } let(:expected_resolved_fact) { double(Facter::ResolvedFact, name: 'identity.group', value: value) } before do expect(Facter::Resolvers::PosxIdentity).to receive(:resolve).with(:group).and_return(value) expect(Facter::ResolvedFact).to receive(:new).with('identity.group', value).and_return(expected_resolved_fact) end it 'returns identity.group fact' do expect(fact.call_the_resolver).to eq(expected_resolved_fact) end end end
#Building Class class Building #attr_accessor :building_name, :building_address attr_accessor :apartments def initialize @apartments = ["building_name", "building_address"] end def initialize(building_name, building_address) @building_name = building_name @building_address = building_address end def to_s @building_name + ", " + @building_address end end # end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :sanitize_params, :if => :has_unit_price? def invoice Invoice.find(params[:id]) end def invoice_item InvoiceItem.find(params[:id]) end def merchant Merchant.find(params[:id]) end def item Item.find(params[:id]) end def transaction Transaction.find(params[:id]) end def customer Customer.find(params[:id]) end private def sanitize_params params[:unit_price] = params_string_to_integer end def params_string_to_integer unit_price = params[:unit_price] (unit_price.to_f * 100).round end def has_unit_price? params.has_key?(:unit_price) end end
class BookshelfBook < ActiveRecord::Base belongs_to :bookshelf belongs_to :book end
require 'test_helper' class BrodosControllerTest < ActionController::TestCase setup do @brodo = brodos(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:brodos) end test "should get new" do get :new assert_response :success end test "should create brodo" do assert_difference('Brodo.count') do post :create, brodo: { description: @brodo.description, title: @brodo.title } end assert_redirected_to brodo_path(assigns(:brodo)) end test "should show brodo" do get :show, id: @brodo assert_response :success end test "should get edit" do get :edit, id: @brodo assert_response :success end test "should update brodo" do patch :update, id: @brodo, brodo: { description: @brodo.description, title: @brodo.title } assert_redirected_to brodo_path(assigns(:brodo)) end test "should destroy brodo" do assert_difference('Brodo.count', -1) do delete :destroy, id: @brodo end assert_redirected_to brodos_path end end
module RethinkAPI class Template attr_reader :name, :static_attrs, :dynamic_attrs, :has_many_relations def initialize(name, host_name = nil) @name = name @host_name = host_name @static_attrs = [] @dynamic_attrs = [] @has_many_relations = [] end def attribute(name, opts = {}) opts = opts.with_indifferent_access if name.kind_of?(Proc) raise 'If name is a lambda, must have a key option.' if opts[:key].nil? @dynamic_attrs << {method_name: name, alias_name: opts[:key].to_s} else alias_name = opts[:key] || name @static_attrs << {method_name: name.to_s, alias_name: alias_name.to_s} end end def attributes(*names) names.each { |name| attribute(name) } end def attribute_names static_attrs.map { |attrs| attrs[:alias_name] } end # has_many :foos, class_name: 'Foo', foreign_key: 'foo_id', template: :lala, key: 'bar' def has_many(name, opts = {}) opts = opts.with_indifferent_access alias_name = opts[:key] || name class_name = opts[:class_name] || name.to_s.classify foreign_key = opts[:foreign_key] || @host_name.to_s.singularize.foreign_key template_name = opts[:template] || @name @has_many_relations << {alias_name: alias_name.to_s, class_name: class_name, foreign_key: foreign_key, template_name: template_name} end # TODO: after callback def after(&block) return unless block_given? end def api_json(api, opts = {}) # Static attributes attrs = api.pluck(attribute_names) # Dynamic attributes self.dynamic_attrs.each do |attr| attrs[ attr[:alias_name] ] = attr[:method_name].call(api.obj, opts) end # Has many relations self.has_many_relations.each do |relation| const = relation[:class_name].safe_constantize attrs[ relation[:alias_name] ] = const.rethink_api_const.table \ .pluck(const.rethink_api_templates[ relation[:template_name] ].attribute_names) \ .eq_join(relation[:foreign_key], api.table).zip.run(const.rethink_api_const.conn).to_a end attrs end end end
class AuthenticationsController < ApplicationController def sign_in @user = User.new end def login email = params[:user][:email] password = params[:user][:password] user = User.authenticate(email, password) if user session[:user_id] = user.id redirect_to :root else flash.now[:error] = 'Please check your username and password.' @user = User.new render :action => "sign_in" end end def sign_out session[:user_id] = nil flash[:notice] = "You have successfully logged out." redirect_to sign_in_path end private def user_params params.require(:user).permit(:email, :password) end end
class CreateVetProfiles < ActiveRecord::Migration[5.2] def change create_table :vet_profiles do |t| t.text :clinic_name t.text :address t.string :postalcode t.string :phone t.string :hours t.text :services t.references :vet, foreign_key: true t.text :image t.timestamps end end end
class Comment include Mongoid::Document include Mongoid::Timestamps belongs_to :post belongs_to :user field :text, type: String validates :text, presence: true end
class Task < ApplicationRecord belongs_to :user belongs_to :job has_many :comments end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception include SessionsHelper private def require_login if @user login(@user) redirect_to @user else redirect_to login_path end end end
class Comment < ActiveRecord::Migration[5.0] def change t.string :author end end
Gem.find_files("minitest/*_plugin.rb").each do |plugin_path| name = File.basename plugin_path, "_plugin.rb" next if seen[name] seen[name] = true require plugin_path self.extensions << name end
# Daily summary of notebook click actions # # Each day, we record the number of unique users ans executors of each notebook. # We also compute a score reflecting the relative popularity of each notebook # on this particular day. These daily stats are are used for the activity # sparkline and are the main component of the notebook trendiness score. class NotebookDaily < ApplicationRecord belongs_to :notebook validates :notebook, presence: true def self.compute_all(days_ago=1) # maps of notebook_id => unique users, unique executors day = days_ago.days.ago.to_date users = user_set(Click, day) executors = user_set(ExecutionHistory, day) # merge executors into users executors.each do |nb, s| users[nb] ||= Set.new users[nb].merge(s) end max_count = users.map(&:second).map(&:count).max || 1.0 log_max = Math.log(1.0 + max_count) # save to db records = users.map do |nb, s| NotebookDaily.new( notebook_id: nb, day: day, unique_users: s.count, unique_executors: executors[nb]&.count || 0, daily_score: Math.log(1.0 + s.count.to_f) / log_max ) end NotebookDaily.transaction do NotebookDaily.where(day: day).delete_all # no callbacks NotebookDaily.import(records, validate: false, batch_size: 250) end end def self.age_off(days_ago=90) day = days_ago.days.ago.to_date NotebookDaily.where('day < ?', day).delete_all # no callbacks end def self.user_set(table, day) table .where('DATE(updated_at) = ?', day) .group(:notebook_id, :user_id) .map {|e| [e.notebook_id, e.user_id]} .group_by(&:first) .map {|nb, users| [nb, Set.new(users.map(&:second))]} .to_h end end
class AdminController < ApplicationController before_filter :admin_lecturer_only! before_filter :gchart_attendance_this_week, :if => Proc.new { current_user.admin? } before_filter :gchart_attendance_last_week, :if => Proc.new { current_user.admin? } def index if current_user.admin? render :index else render :"lecturer/index" end end private def gchart_attendance_this_week attendance = { 1 => [], 2 => [], 3 => [], 4 => [], 5 => [] } Lecture.this_week.each do |l| attendance[l.start_time.wday].push(l.attendance) if l.start_time.wday <= 5 and l.students.any? end attendance = attendance.map do |key, value| if value.count > 0 ((value.sum.to_f / (value.count * 100).to_f) * 100.0) else 0.0 end end legends = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"].each_with_index.map{ |x, index| "#{x} (#{attendance[index].to_i}%)" } colours = ["535aac", "825959", "843e01", "0a7061", "17334a", "6320df", "f40b59"].first(7).join(',') @gchart_attendance_this_week = Gchart.line( :size => '500x200', :title => "Total Attendance This Week", :bg => "FFF", :line_colors => colours, :legend => legends, :data => attendance) end def gchart_attendance_last_week attendance = { 1 => [], 2 => [], 3 => [], 4 => [], 5 => [] } Lecture.last_week.each do |l| attendance[l.start_time.wday].push(l.attendance) if l.start_time.wday <= 5 and l.students.any? end attendance = attendance.map do |key, value| if value.count > 0 ((value.sum.to_f / (value.count * 100).to_f) * 100.0) else 0.0 end end legends = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"].each_with_index.map{ |x, index| "#{x} (#{attendance[index].to_i}%)" } colours = ["535aac", "825959", "843e01", "0a7061", "17334a", "6320df", "f40b59"].first(7).join(',') @gchart_attendance_last_week = Gchart.line( :size => '500x200', :title => "Total Attendance Last Week", :bg => "FFF", :line_colors => colours, :legend => legends, :data => attendance) end end
require 'nokogiri' require 'open-uri' require 'pry' class Bestsellers::Category attr_accessor :name, :titles, :category, :books @@all = [] def initialize(name) @name = name @@all << self @books = [] end def self.all @@all end def find_book_by_category_and_index(index) self.books[index] end def books_by_category self.books end def list_books_by_category books_by_category.each.with_index(1) do |book, index| puts "#{index}. #{book.fixed_title}" end end def self.find_by_index(index) @@all[index] end def add_book(new_book) self.books << new_book end end
require 'spec_helper' describe "customer_services/index" do before(:each) do assign(:customer_services, [ stub_model(CustomerService, :partner => nil, :active_record => false ), stub_model(CustomerService, :partner => nil, :active_record => false ) ]) end it "renders a list of customer_services" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "tr>td", :text => nil.to_s, :count => 2 assert_select "tr>td", :text => false.to_s, :count => 2 end end
require "helpers/test_helper" class UnitTestPubsubCollections < MiniTest::Test def setup Fog.mock! @client = Fog::Google::Pubsub.new(google_project: "foo") # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class) @collections = descendants.select { |d| d.name.match(/Fog::Google::Pubsub/) } end def teardown Fog.unmock! end def test_common_methods # This tests whether Fog::Compute::Google collections have common lifecycle methods @collections.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments @collections.each do |klass| obj = klass.new assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end end
require "./lib/product.rb" require "./lib/greengrocer.rb" require "./lib/user.rb" # ๅ•†ๅ“ใƒ‡ใƒผใ‚ฟ product_params1 = [ {name: "ใƒˆใƒžใƒˆ", price: 100}, {name: "ใใ‚…ใ†ใ‚Š", price: 200}, {name: "็މใญใŽ", price: 300}, {name: "ใชใ™", price: 400} ] # product_params1 ใฎๅ•†ๅ“ใ‚’ๆŒใคๅ…ซ็™พๅฑ‹ใฎ้–‹ๅบ— greengrocer1 = Greengrocer.new(product_params1) # ่ฟฝๅŠ ๅ•†ๅ“ใƒ‡ใƒผใ‚ฟ adding_products1 = [ {name: "ใ”ใผใ†", price: 250}, {name: "ใ‚Œใ‚“ใ“ใ‚“", price: 350} ] # ๅ•†ๅ“ใ‚’็™ป้Œฒ๏ผˆadding_products1 ใฎๅ•†ๅ“ใ‚’่ฟฝๅŠ ๏ผ‰ greengrocer1.register_product(adding_products1) # ใŠๅฎขใ•ใ‚“ใฎๆฅๅบ— user = User.new # ๅ•†ๅ“ใ‚’่กจ็คบ greengrocer1.disp_products # ๅ•†ๅ“ใ‚’้ธๆŠž user.choose_product(greengrocer1.products) # ๅ€‹ๆ•ฐใ‚’่ณชๅ• greengrocer1.ask_quantity(user.chosen_product) # ๅ€‹ๆ•ฐใ‚’ๆฑบๅฎš user.decide_quantity # ้‡‘้ก้‡‘้กใ‚’่จˆ็ฎ— greengrocer1.calculate_charges(user)
class BillsController < ApplicationController include BillFinder before_action :authenticate_user!, only: [:follow, :unfollow] def show @bill = bill_details end def follow find_or_create_alert render json: @alert, status: 201 end def unfollow find_and_delete_alert render json: @alert, status: 202 end private def find_or_create_alert @alert = current_user.find_alert_for_bill(bill_id) @alert ||= current_user.create_alert_for_bill(bill_params) end def find_and_delete_alert @alert = current_user.find_alert_for_bill(bill_id) @alert.destroy! if @alert.present? end def bill_params params.permit(:billId, :billName, :billDescription) end end
class CommentSerializer < ActiveModel::Serializer attributes :id,:body,:user_id end