text
stringlengths
10
2.61M
# Multiple Signatures # What do each of these puts statements output? a = %w(a b c d e) puts a.fetch(7) puts a.fetch(7, 'beats me') puts a.fetch(7) { |index| index**2 } # The first puts will return: "index 7 outside of array bounds -5...5" # The second will puts: "Beats me" # The third will puts: 49
class Piece attr_reader :color attr_accessor :pos, :board def initialize(color, board, pos) @king = false @color = color @board = board @pos = pos end def symbol if @king == true 'K' else '*' end end def move_dirs return [[1,1], [1, -1]] unless @king re...
# frozen_string_literal: true require 'json' require 'httparty' require 'parallel' # BambooHR API Gateway class Bamboo THREAD_COUNT = 10 def initialize(company, api_key) self.company = company self.api_key = api_key end def jobs get_json('applicant_tracking/jobs') end def detailed_jobs ...
require 'faraday' require 'json' require 'ostruct' require 'uploadcare/api/project' require 'uploadcare/api/file' module Uploadcare class Api attr_reader :options def initialize(options = {}) @options = Uploadcare::default_settings.merge(options) end # Get project info def project ...
require 'spec_helper' describe ShortUrl do # pending "add some examples to (or delete) #{__FILE__}" describe "validations" do context "long url" do it "should pass when included" do short_url = ShortUrl.create( :long_url => website, :url_hash => "google") short_url.should be_valid e...
class User < ActiveRecord::Base require 'securerandom' # If you add some languages in locale files, add them here too. ;) LANGUAGES = ["fr", "en"] LANGUAGES_FOR_SELECT = [[ "Francais", "fr"], [ "English", "en" ]] attr_accessible :created_at, :email, :login, :password, :salt, :time_...
class Post < ActiveRecord::Base attr_accessible :body, :publish_on, :published, :status, :title, :category_ids, :author, :blog_id has_many :categorizations has_many :categories, through: :categorizations accepts_nested_attributes_for :categorizations belongs_to :blog validates_presence_of :title validat...
class CreateDatarecords < ActiveRecord::Migration def change create_table :datarecords do |t| t.integer :update_time t.string :record_source t.string :record_type t.timestamps null: false end end end
require 'rails_helper' describe "user can add a company" do it "and then see pending approval" do VCR.use_cassette('second_denver_location') do industry = Industry.create(name: "Applesauce") user = create(:user) stub_login(user) visit '/companies' click_on "Add Company" fill...
class AddAttachmentToEvents < ActiveRecord::Migration def change add_attachment :events, :profile end end
class AddProductArticleRefToProductSizes < ActiveRecord::Migration[6.0] def change add_reference :product_sizes, :product_article, null: false, foreign_key: true end end
$:.unshift File.expand_path(File.dirname(__FILE__) + "/../../lib") $:.unshift File.expand_path(File.dirname(__FILE__) + "/../../ext") require 'ray' class Triangles < Ray::Drawable def initialize super self.vertex_count = 3 end def fill_vertices [ Ray::Vertex.new([0, 0], Ray::Color.red), R...
class FontMuseo < Formula version "2.002" url "https://abstractfonts-downloads.s3.amazonaws.com/zips/1/4/8/9/0/contents/museo-300.zip", verified: "abstractfonts-downloads.s3.amazonaws.com/" desc "Museo" homepage "http://www.abstractfonts.com/font/14890" def install (share/"fonts").install "Museo300-Regula...
require_relative 'github' require_relative 'workers' require 'chronic' require 'date' require 'sinatra/base' require 'fileutils' require 'json' require 'octokit' require 'rest-client' require 'securerandom' require 'sinatra/config_file' require 'whedon' require 'yaml' require 'pry' include GitHub class WhedonApi < Si...
class HomeController < ApplicationController def index end # Redirect to the latest official release. def latest if latest = self.class.latest redirect_to "/" + latest else raise ActiveRecord::RecordNotFound end end private # Find the path within `public` of the latest official ...
class Page include Mongoid::Document field :title, type: String field :body, type: String field :is_home, :type => Boolean, :default => false field :page_type, :type => String field :part_ids, :type => Array scope :home, ->{where(page_type: "Home")} validates :title, :presence => true validates :b...
# -*- mode: ruby -*- # vi: set ft=ruby : # Vagrant.require_plugin 'vagrant-aws' # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.co...
require 'tackle_box/organization' require 'tackle_box/email/template' require 'tackle_box/link' require 'tackle_box/attachment' require 'chars' require 'mail' module TackleBox class Campaign # Headers for common email mailers HEADERS = { 'outlook' => {'X-Mailer' => 'Microsoft Office Outlook, Buil...
FactoryBot.define do factory :about do description { FFaker::Lorem.paragraph } portfolio end end
GmapCoordinatesPicker.configure do |config| config.lat_column = :latitude config.lng_column = :longitude config.default_coordinates = [23.727666666, 90.410550] #Dhaka (my home town) center point :) config.map_handler = 'gMapObj' #javascript map object config.zoom_level = 10 config.map_container_class = 'gma...
module ApplicationHelper def link_to_country(name,align="left") align = align.to_sym output = "" output += country_with_flag(name,align) output.html_safe end def country_with_flag(name,align=(:left)) output="" begin output += icon("countries",name) if align == :left rescue e...
# frozen_string_literal: true FactoryBot.define do factory :history do comment { 'Aprovado com sucesso. Obrigado.' } ticket end end
# frozen_string_literal: true if Discipline.count.zero? puts 'Seeding Disciplines' %w[Графіка Програмування].each do |name| Discipline.create!(name: name) end end
class LessonplansController < ApplicationController before_action :signed_in_teacher, only: [:index, :new, :create, :destroy] before_action :correct_teacher, only: :destroy def index @lessonplans = Lessonplan.all end def new @lessonplan = Lessonplan.new end def create @lessonplan = curren...
require 'rails_helper' RSpec.describe 'The Mechanic Index Page' do before :each do @mechanic1 = Mechanic.create!(name: 'John', years_experience: 2) @mechanic2 = Mechanic.create!(name: 'Jill', years_experience: 4) @mechanic3 = Mechanic.create!(name: 'Jack', years_experience: 6) @mechanic4 = Mechani...
$:.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'cybersourcery_testing/version' Gem::Specification.new do |spec| spec.name = 'cybersourcery_testing' spec.version = CybersourceryTesting::VERSION spec.authors = ['Michael Toppa'] spec.email = ['pub...
class UserSerializer < ActiveModel::Serializer attributes :id, :username, :email, :first_name, :last_name, :follower_count, :following_count, :followers, :all_following, :post_count, :bio has_many :photos has_many :homepage_photos has_many :boards def homepage_photos userIds = object.all_following.ma...
class FontRobotoMonoForPowerline < Formula head "https://github.com/powerline/fonts.git", branch: "master", only_path: "RobotoMono" desc "Roboto Mono for Powerline" homepage "https://github.com/powerline/fonts/tree/master/RobotoMono" def install (share/"fonts").install "Roboto Mono Bold Italic for Powerline...
Vagrant.configure(2) do |config| config.vm.box = "ubuntu/trusty64" config.vm.network "private_network", ip: "192.168.17.21" config.vm.network "forwarded_port", guest: 5432, host: 5432 end
class Address < ActiveRecord::Base belongs_to :user validates :address_line_one, presence: true validates :city, presence: true validates :state, presence: true validates :state, length: { is: 2 } validates :postal_code, presence: true validates :postal_code, length: { is: 5 } end
class CreateRooms < ActiveRecord::Migration[5.2] def change create_table :rooms do |t| t.string :name, index: true, null: false t.string :full_name, index: true t.integer :parent_id, null: true, index: true t.integer :lft, null: false, index: true t.integer :rgt, null: false, index: ...
json.businesses do |json| # json.results @businesses.count i = 0 json.array!(@businesses) do |business| json.extract! business, :name, :yelp_id,:yelp_rating, :yelp_review_count, :url, :mobile_url json.phone number_to_phone(business.phone, area_code: true) json.subtext business.biz_sub_text json.di...
class CreateEntries < ActiveRecord::Migration def up execute " CREATE TYPE role_t AS ENUM ('monarch', 'minister', 'rebel', 'trun-coat'); CREATE TYPE result_t AS ENUM ('win', 'fail', 'run-away', 'unkown'); " create_table :entries do |t| t.references :general t.references :lord t.column :r...
class Temperature def initialize(options = {}) @fahrenheit = nil if options.key?(:f) @fahrenheit = options[:f] elsif options.key?(:c) @fahrenheit = self.class.ctof(options[:c]) end end def self.from_fahrenheit(temperature) new(:f => temperature) end def self.from_celsius(temp...
class AddFreeCleaningToSpreePlans < ActiveRecord::Migration[5.0] def change add_column :spree_plans, :free_cleaning, :boolean end end
# frozen_string_literal: true module MLBStatsAPI class Base attr_reader :data def initialize(data) @data = data end def [](key) = @data[key] def dig(*path) = @data.dig(*path) end end
class GroupBankAccount < BankAccount belongs_to :group, required: true delegate :name, to: :group def transactions outgoing_transactions.union(incoming_transactions) .includes(from_account: :group, to_account: :group) .latest end def items outgoing_items.union(incoming_items) .incl...
class ImagesController < ApplicationController before_filter :authenticate_all! before_filter :find_site, :only => [ :new, :create ] before_filter :type_dir, :only => [ :new, :create ] def new @action = params[:imageAction] begin dir = File.join(@site.site_root, @type_dir) @images = FtpCl...
require 'customer' describe Customer do subject(:customer) {described_class.new} describe '#initialize' do it 'intializes with a balance of 0' do expect(customer.balance).to eq 0 end it 'intializes with an empty transaction_history' do expect(customer.statement).to eq ([]) ...
class AgentesController < ApplicationController layout "dashboard" def index @agentes = Agente.all end def mostrar @agente = Agente.find(params[:id]) end def crear @agente = Agente.new @usuarios = Usuario.all end def create # Instantiate a new object using form parameters @ag...
class Document < ApplicationRecord has_many :reviews, dependent: :destroy validates_presence_of :title, :content, :created_by end
require('rspec') require('word') require('definition') describe('Word') do before() do Word.clear() end describe("#word") do it("returns the inputted word") do test_word = Word.new({:word=> "Cow"}) expect(test_word.word()).to(eq("Cow")) end end describe("#meanings")...
class CreatePageFollows < ActiveRecord::Migration def change create_table :page_follows do |t| t.references :page t.references :user t.timestamps end add_index :page_follows, :page_id add_index :page_follows, :user_id end end
for i in 1..255 puts i end puts (1..255).collect { |i| print i, " " } print (1..255).to_a.to_s 1.upto(255) { |i| print i, " " } (1..255).each { |i| print i, ""} while i <=255 print i, " " i += 1 end #2 #puts (1..255).find_all { |i| i.odd? } #puts (1..255).reject { |i| i.even? }.to...
class CreateProductsAdditionalInfos < ActiveRecord::Migration def change create_table :products_additional_infos do |t| t.integer :type_id, null: false t.integer :tinyint_1, precision: 3, limit: 1, null: true t.integer :smallint_1, precision: 5, limit: 2, null: true t.integer :smallint...
FactoryBot.define do factory :event do start_date { Faker::Date.between(100.days.ago, Date.today) } duration { rand(1..120) } title { Faker::Hipster.word } description { Faker::Hipster.paragraphs.join("\n") } price { rand(1..1000) } location { Faker::GameOfThrones.city } end end
Pod::Spec.new do |s| s.name = "SwiftyPhotos" s.version = "0.8.0" s.summary = "***Useful tool for PhotoKit framework*** to boost your productivity." s.description = <<-DESC ***Useful tool for PhotoKit framework*** to boost your productivity. Swift 5.0....
class FeedsController < ApplicationController include ActionController::MimeResponds include ActionView::Layouts def index logger.info "index" end def show logger.info "show #{params[:id]}" @feed = get_feed(params[:id]) i = 0 lastitem = Item.where(feed: @feed).size.positive? ? Item.whe...
class AdminController < ApplicationController before_filter :verify_is_admin def index @weddingInfo = WeddingInfo.all[0] if @weddingInfo.nil? @weddingInfo = WeddingInfo.new @weddingInfo.save end @weddingInfo end def update @weddingInfo = WeddingInfo.find(params[:id]) if @w...
control "M-1.2" do title "1.2 Ensure the container host has been Hardened (Not Scored)" desc " Containers run on a Linux host. A container host can run one or more containers. It is of utmost importance to harden the host to mitigate host security misconfiguration. You should follow infrastructure secu...
class RemoveCompetitionIdFromMap < ActiveRecord::Migration def up remove_column :maps, :competition_id end def down add_column :maps, :competition_id, :integer end end
class ChangedUserInfosAddedBirth < ActiveRecord::Migration def self.up add_column :user_infos, :birth, :datetime end def self.down remove_column :user_infos, :birth end end
Then(/^I should see translation for "([^\"]*)"$/) do |key| page.should have_content(I18n.t(key)) end Then(/^I should not see translation for "([^\"]*)"$/) do |key| expect(page).not_to have_content(I18n.t(key)) end Then(/^the button with translation "(.*)" should be (.*)/) do |name, status| is_disabled = status ...
class AddCoordToAstronomicObject < ActiveRecord::Migration def change add_column :astronomic_objects, :coord_ar, :float add_column :astronomic_objects, :coord_dec, :float end end
class BaseController < ApplicationController layout "base" #before_action :authenticate_admin! # Cancan rescue_from CanCan::AccessDenied do |exception| if request.format == 'json' || request.accept=~ /json/ || request.content_type =~ /json/ render :json => {:success => false, :message => exception.m...
class ApplicationController < ActionController::Base rescue_from CanCan::AccessDenied do |exception| redirect_to root_url, :alert => exception.message end protect_from_forgery :except => :managers before_filter :authenticate_user! skip_before_filter :authenticate_user!, :only => :managers def after_sign_...
class Post < ActiveRecord::Base validates :title, presence: true validates :category, inclusion: { in: %w(Fiction Non-Fiction) } validates :content, length: { :minimum => 100} # PostsController making invalid updates has an error for missing title # PostsController making invalid updates has an error for too shor...
class ChangeProjectsNameNotNill < ActiveRecord::Migration[5.2] def change change_column_null :products, :name,false 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 with_options presence: true do VALID_full_angle = ...
module Task module Attributes class StateRevision < EditableRevision %w[ EmptyStateError UnknownStateError ].each { |error_name| const_set(error_name, Class.new(Error)) } include Persistable VALID_STATES = [:considered, :underway, :canceled, :done].freeze def attri...
FactoryBot.define do factory :artist do name { "Stabby Lambda" } price_per_hour { 150.00 } bio { 'Tattooer. Stayed at a Holiday Inn Express once.' } uid { '11111' } login { 'example@mail.com' } token { 'token' } end end
Factory.define(:mod_action) do |f| f.creator {|x| x.association(:user)} f.description "1234" end
UspsConfirmationEntry = Struct.new( :address1, :address2, :city, :first_name, :last_name, :otp, :state, :zipcode, :issuer ) do def self.user_access_key SessionEncryptor.new.duped_user_access_key end def self.encryptor Pii::PasswordEncryptor.new end def self.new_from_hash(hash) ...
require 'spec_helper' describe "request password reset" do # As Confirmed Store #---------------------------------------------------------------------------- context "as confirmed store", :confirmed => true do include_context "as confirmed store" before(:each) do visit new_store_password_path e...
require 'spec_helper' require 'web_mock' require File.dirname(__FILE__) + '/../app/bot_client' describe 'BotClientResumenCommands' do let(:token) { 'fake_token' } it 'when user looks up resume with a plan but no visits' do # rubocop:disable RSpec/ExampleLength stub_get_updates(token, '/resumen') body = {...
class CommentsController < ApplicationController before_action :authenticate_user! before_action :set_item def create @comment = current_user.comments.build(comment_params) @comment.item = @item if @comment.save redirect_to @item, flash: { info: 'コメントが投稿されました。' } else redirect_to @it...
# frozen_string_literal: true # All generic helpers go here module ApplicationHelper def signed_in? patient_signed_in? || doctor_signed_in? end def patient_or_doctor if !current_doctor.nil? # render stuff build_doctor_links(current_doctor) elsif !current_patient.nil? content_tag(:a...
module Card HEARTS = "\u2665".encode("utf-8") SPADES = "\u2660".encode("utf-8") CLUBS = "\u2663".encode("utf-8") DIAMONDS = "\u2666".encode("utf-8") class Card attr_reader :rank, :suit def initialize(rank, suit) @rank = rank @suit = suit end def to_s "#{rank_s}#{@suit}" ...
class ChangeLocalregionNonnull < ActiveRecord::Migration def change change_column :wines , :localregion_id , :integer , null: false end end
# frozen_string_literal: true module Friendable extend ActiveSupport::Concern included do has_many :friendships, dependent: :destroy has_many :friends, -> { where friendships: { status: 2 } }, through: :friendships has_many :requested_friends, -> { where friendsh...
class BitPack # Element Assignment. Sets the bit at +index+, or the range of bits indicated # by the Range object +range+, or the range specified by +index+ and +length+. # # :call-seq: # bp[index] = value -> value # bp[range] = value -> value # bp[index, length] = value ...
require 'spec_helper' bool_options = [true, false] describe 'secure_linux_cis::debian9::cis_3_5_2_2' do on_supported_os.each do |os, os_facts| bool_options.each do |option| context "on #{os}" do let(:facts) { os_facts } let(:params) { { 'enforced' => option } } it { is_expected.to...
class Balance < ApplicationRecord belongs_to :account monetize :amount_cents monetize :transfers_cents monetize :diff_cents, allow_nil: true before_save :calculate_diffs after_save :convert_currency, if: proc { currency != "MXN" && account.currency != "MXN" } def prev @prev ||= prev_set.limit(1).fi...
require 'test_helper' class ApiTest < ActionDispatch::IntegrationTest setup do @admin = users(:alice) @user = users(:bob) Link.any_instance.expects(:name).at_least(0).returns('test name') SyncController.expects(:send).at_least(0) end test 'get user' do sign_in @user get 'me.json' assert_response :...
# frozen_string_literal: true require 'rails_helper' feature 'user return panel from ticket' do scenario 'user returns to panel before visualize ticket wich he is recipient' do person = create(:person) user = create(:user, person: person) person_other = create(:person, email: 'flavio@docflu...
# encoding: utf-8 module Monetize VERSION = "1.3.0" end
class Genre < ApplicationRecord has_many :subgenres end
module Fog module Compute class Vsphere class Cdroms < Fog::Collection attribute :instance_uuid, :alias => :server_id model Fog::Compute::Vsphere::Cdrom def all(filters = {}) load service.list_vm_cdroms(instance_uuid) end def get(unit_number) all...
class DbSubject < ActiveRecord::Base # Relations belongs_to :subj_area has_and_belongs_to_many :resource_queries has_many :databases, through: :db_subj_weights has_many :db_subj_weights has_and_belongs_to_many :daba_users, association_foreign_key: 'user_id' Reusable.has_many_translations(self) # Sort o...
class User < ActiveRecord::Base has_many :posts has_many :active_relationships, class_name: "Relationship", foreign_key: :follower_id, dependent: :destroy has_many :passive_relationships, class_name: "Relationship", foreign_key: :fo...
module Spree module Api module V1 class TaxonCertificatesController < Spree::Api::BaseController helper ::SpreeApiV1TaxonCertificatesHelper def index @taxon_certificates = scope.certificates.accessible_by(current_ability, :read) respond_with(@taxon_certificates) end ...
package "__name__" do version "__version__" action :install end
class AddDescToProjects < ActiveRecord::Migration def change add_column :projects, :s_desc, :string end end
# frozen_string_literal: true module NCMB class Devise < NCMB::DataStore attr_accessor :client, :name def initialize(client) @client = client @name = "Instration" end def push return NCMB::Push.new(client) end end end
require 'test_helper' module Admin class TopicsControllerTest < ActionController::TestCase def setup @topic = create(:topic) @question = create(:question) @admin = create(:admin) sign_in @admin end test 'should get topic index' do get :index assert_response :success ...
module PrintQuoteFooter # HACK the helper is included in order to allow the formatting of data for processing by prawn include ActionView::Helpers::NumberHelper extend ActiveSupport::Concern include PrintDocumentStyle def quote_total_footer(quote, pdf) pdf.line_width(0.1) # company_head...
class SetNotNullToWarStatuses < ActiveRecord::Migration[6.1] def change change_column_null :war_statuses, :point, false end end
module OpenAssets module Transaction # An insufficient amount of assets is available. class InsufficientAssetQuantityError < TransactionBuildError end end end
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::FragmentSpreadsArePossible do include StaticValidationHelpers let(:query_string) {%| query getCheese { cheese(id: 1) { ... milkFields ... cheeseFields ... on Milk { fatContent } ... on...
class InviteCategory < ApplicationRecord has_many :invites end
module NytimesCongress class Member < Base attr_reader :id, :thomas_id, :api_uri, :first_name, :middle_name, :last_name, :party, :twitter_account, :facebook_account, :facebook_id, :url, :rss_url, :domain, :seniority, :next_election, :state, :district,:missed_votes_pct, :votes_with_party_pct, :date_of_birth, :gender...
#!/usr/bin/env ruby require 'json' require 'net/http' require 'net/https' require 'nokogiri' require 'uri' $db = nil PREFIX_WEIGHTS = { 'Genre' => 1.0, 'Studio' => 0.3, 'Classification' => 0.1, 'Staff' => 0.1, 'Staff: Director' => 1.0, 'Staff: Script' ...
# # Cookbook Name:: bcpc # Recipe:: mysql_client # # Copyright 2013, Bloomberg Finance L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
class Book attr_accessor :title def title title_array = @title.split(" ") result = [] title_array.each_with_index.map do |word, index| little_words = %w(a an and in the of) if index == 0 result << word.capitalize else little_words.include?(word) ? result << word : res...
class Nap < ApplicationRecord belongs_to :day def nap_duration Time.at(self.end - self.start).utc.strftime("%H:%M") if (self.start && self.end) end def nap_start self.start.strftime("%H:%M") if self.start end def nap_end self.end.strftime("%H:%M") if self.end...
class FontRadioCanada < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/radiocanada" desc "Radio Canada" homepage "https://fonts.google.com/specimen/Radio+Canada" def install (share/"fonts").install "RadioCanada-Italic[wdth,wght].ttf" ...
class String def green; "\e[32m#{self}\e[0m" end def blue; "\e[34m#{self}\e[0m" end end require_relative "tile" require "byebug" class Board attr_reader :grid def initialize(file) @grid = [] File.open(file).each do |row| @grid << row.chomp.chars.map do ...
require 'sexp_processor' module CodeGraph class InheritanceProcessor < SexpProcessor def initialize super self.strict = false @scopes = [] @classes = {} end def classes fix_parents @classes end def process_const(exp) name = atom(exp[1]) exp.clea...
require 'puppet' Puppet::Type.type(:rabbitmq_user).provide(:rabbitmqctl) do if Puppet::PUPPETVERSION.to_f < 3 commands :rabbitmqctl => 'rabbitmqctl' else has_command(:rabbitmqctl, 'rabbitmqctl') do environment :HOME => "/tmp" end end defaultfor :feature => :posix def self.instances ...
# frozen_string_literal: true module Bolt class PAL class YamlPlan class Step class Command < Step def self.allowed_keys super + Set['command'] end def self.required_keys Set['target'] end def initialize(step_body) ...