text
stringlengths
10
2.61M
class CadastroPage < SitePrism::Page set_url '?controller=authentication&back=my-account' element :email_create_account_field, '#email_create' element :create_account_btn, '#SubmitCreate' element :title_fem_rd, '#id_gender2' element :first_name_field, '#customer_firstname' element :last_name_fi...
# == Schema Information # # Table name: services # # id :integer not null, primary key # title :string # description :text # rang :integer # created_at :datetime not null # updated_at :datetime not null # image_url :string # s...
class BalanceEventQuery include ActiveModel::Conversion extend ActiveModel::Naming attr_reader :start_date, :end_date, :payee_shareholder_id, :share_shareholder_id, :balance_shareholder_id, :with_text, :bill_type_id, :can_use_running_total, :changed_at_start_date, :changed_at_end_date, :show_change_date_fie...
class EntriesController < ApplicationController def index entries = Entry.all render json: entries end def new entry = Entry.new end def create entry = Entry.create(entry_params) render json: entry end def destroy entry = Entry.delete(...
# double_char1.rb # Write a method that takes a string, and returns a new string in which every # character is doubled. def repeater(string) string.split('').map { |char| char * 2 }.join end puts repeater('Hello') == "HHeelllloo" puts repeater("Good job!") == "GGoooodd jjoobb!!" puts repeater('') == '' puts '----...
class PurchaseAddress include ActiveModel::Model attr_accessor :user_id, :item_id, :postal_code, :state_id, :city, :block_number, :building, :phone_number, :token with_options presence: true do validates :postal_code, format: {with: /\A[0-9]{3}-[0-9]{4}\z/, message: "is invalid. Include hyphen(-)"} valid...
FactoryGirl.define do factory :user_profile do sequence(:vk_id) { |n| n } factory :user_profile_with_friends do ignore do friends_count 3 end after(:create) do |user_profile, evaluator| friends=FactoryGirl.create_list(:user_profile, evaluator.friends_count) user_prof...
#!/usr/bin/env ruby require 'trollop' require 'hub-deployer' require 'colored' require 'fog' $stdout.sync = true base_tasks = <<-'EOS' # Symfony application path set :app_path, "app" # Symfony web path set :web_path, "web" # Symfony log path set :log_path, ...
json.server do json.partial! 'api/servers/server', server: @server end
require 'test_helper' class ParticipantsControllerTest < ActionDispatch::IntegrationTest def setup @participant = participants(:tester) @other_participant = participants(:tester2) end test "should get new" do get signup_path assert_response :success end test "should redirect edit when...
require 'rails_helper' require 'json' require 'facilities_management/fm_supplier_data' RSpec.describe 'select_services/select_services.html.erb', type: :view do it 'Counts suppliers for all lot types with a location of UKC1 and a service of C-20' do fm_supplier_data = FMSupplierData.new supplier_count = fm_su...
class Shipping < ApplicationRecord has_many :orders validates :company, :costs, :days, presence: true validates :costs, :days, numericality: { greater_than: 0 } end
require 'date' require 'digest' module IMML module Book module EntityMethods def initialize @attributes={} end def parse(node) if node["unsupported"] @unsupported=true end end def write(xml) if @unsupported @attributes[:unsuppo...
#!/usr/bin/ruby begin str = File.open(ARGV[0]).read.chomp rescue puts 'Valid input file from AdventOfCode required as first argument.' else puts str.scan(/-*\d+/).map(&:to_i).reduce(:+) end
# - Ask the user what the current temperature is, if the A/C is functional, and what temperature they wish it was. # - If the airconditioner is functional and the current temperature is above the the desired temperature... display "Turn on the A/C Please" # - If the airconditioner is non-functional and the curr...
module Log2Carbon class Analyzer @@logger = nil @@config = nil @@connection = nil def initialize(config) @@config = config trap('HUP') { reload } trap('EXIT') { stop } trap('QUIT') { stop } logger connection ...
class PurchaseShipping include ActiveModel::Model attr_accessor :user_id, :item_id, :purchase_id, :postal_code, :prefecture, :cities, :address, :building_name, :phone_number, :token, :user, :item with_options presence: true do validates :postal_code, format: { with: /\A\d{3}-\d{4}\z/, message: 'を正しく入力してください'...
namespace :db do desc "Load seed fixtures (from db/fixtures) into the current environment's database." task :seed => :environment do require 'active_record/fixtures' Dir.glob(RAILS_ROOT + '/db/fixtures/*.yml').each do |file| Fixtures.create_fixtures('db/fixtures', File.basename(file, '.*')) end ...
require "mysql" begin dbh = Mysql.new 'localhost','[user]','[password]','[dbname]' sql_statement = '[SQL STATMENT]' rs = dbh.query(sql_statement) n_rows = rs.num_rows puts "There are #{n_rows} rows in the result set:\n\n" n_rows.times do puts rs.fetch_row.join("\s") end rescue Mysql...
class Structura; module Containable # @group Struct + Handy # see self.class.*args delegate_class_methods :has_default?, :default_for, :has_flavor? # @yield [index] # @yieldparam [Integer] index # @yieldreturn [self] # @return [Enumerator] def each_index return to_enum(__method__) unless blo...
# # A LigerEngine Search Strategy is responsible for taking some sort # of input, and turning it into an array of Integer Pubmed IDs # # It must implement the instance method 'search', which accepts a # query String and returns an array of Integer Pubmed IDs # module LigerEngine module SearchStrategies # The Pu...
class Song attr_reader :title, :artist @@all = []# This represents/holds all instances of songs created def initialize @title @@all << self end def self.all @@all end def title=(title) @title = title end def artist=(artist) #if you make this attr_accessor or attr_writer you don't need to w...
#!/usr/bin/ruby require 'mechanize' # https://bugs.launchpad.net/ubuntu/+source/librmagick-ruby/+bug/565461 RMAGICK_BYPASS_VERSION_TEST = true require 'RMagick' include Magick ################################################# # Configuration ################################################# potd_url = "http://photog...
require 'rails_helper' RSpec.describe Item, type: :modul do before do user = FactoryBot.create(:user) @item = FactoryBot.build(:item, user_id: user.id) end describe '商品出品機能' do context '出品がうまくいくとき' do it 'image,neme,genre,place,explanation,status,delivery_fee,shipment_source,delivery_completio...
# -*- encoding: utf-8 -*- require File.expand_path("../lib/git-bundlecompare/version", __FILE__) Gem::Specification.new do |s| s.name = "git-bundlecompare" s.version = Git::Bundlecompare::VERSION s.platform = Gem::Platform::RUBY s.authors = ['Martin Schuerrer'] s.email = ['martin@schu...
# Problem 287: Quadtree encoding (a simple compression algorithm) # http://projecteuler.net/problem=287 # The quadtree encoding allows us to describe a 2^N×2^N black and white image as a sequence of bits (0 and 1). Those sequences are to be read from left to right like this: # the first bit deals with the complete 2^...
# coding: utf-8 require 'rails_helper' describe "patients/show" do before(:each) do # @patient = assign(:patient, stub_model(Patient, # :hp_id => "Hp" # )) @patient = stub_model(Patient, :hp_id => "19" ) @examdate = Time.now @audiogram_stub0 = stub_model(Audiogram, :examdate =>...
#!/usr/bin/env ruby require 'rss' require 'open-uri' require 'date' require_relative '../lib/cure_muno.rb' uri = 'https://news.google.com/news/feeds?hl=ja&ned=us&ie=UTF-8&oe=UTF-8&output=rss&scoring=n&q=プリキュア' #Get news published within a day range = 86400 now = Time.now rss = open(URI.encode(URI.unescape(uri))).rea...
class Director < ApplicationRecord validates :name, :presence => true, :uniqueness => { :dob => true } has_many :movies end
class PagesController < ApplicationController def home @title = "Home" @item = Item.new if signed_in? end end
class PagesController < ApplicationController rescue_from Exception, with: :not_found def not_found render 'pages/not_found', layout: false, status: 404 end def sitemap end def home seo = Seo.find_by_page 'Главная' @title = seo.title unless seo.title.blank? @seo_keywords = seo.seo_keywords unless seo....
# Representation of a single attachment to a model. class ActiveStorage::Attached::One < ActiveStorage::Attached delegate_missing_to :attachment # Returns the associated attachment record. # # You don't have to call this method to access the attachment's methods as # they are all available at the model level...
class Membership < ApplicationRecord belongs_to :agent, touch: true belongs_to :user validates :rights, inclusion: { in: ['all', 'edit', 'show'] } validates :user_id, uniqueness: { scope: [:agent_id] } end
require 'spec_helper' describe "Travelport::Bridge::Air" do before :all do @bridge = Travelport::Bridge::Air.new do |config| config.login = "Universal API/uAPI-851375684" config.password = "rZSgRWpPPYb6njF8SKBrnA9cK" config.target_branch = "P105215" config.endpoint = "https://emea.copy-w...
require_relative '../piece' require_relative 'sliding_piece' class Queen < Piece include SlidingPiece def white_symbol "\u2655" end def black_symbol "\u265b" end def move_diffs orthogonal_moves + diagonal_moves end end
class CreateMeetings < ActiveRecord::Migration[5.2] def change create_table :meetings do |t| t.references :session, foreign_key: true, null: false t.date :date, null: false t.references :classroom, foreign_key: true t.boolean :is_canceled, null: false, default: false t.timestamps ...
class Team < ApplicationRecord has_many :users, dependent: :destroy has_many :organizations, dependent: :destroy has_many :bosses, through: :organizations, dependent: :destroy end
require 'rails_helper' RSpec.describe ImageVisibilityJob do let(:image) { FactoryBot.build(:image, visibility: 'restricted') } let(:file_set) { FactoryBot.create(:file_set, visibility: 'restricted') } before do image.ordered_members << file_set image.save! end it 'sets the visibility of an image an...
class Api::V1::SessionsController < ApplicationController skip_before_action :authenticate_request def restore auth_token = params["authToken"] decoded_token = AuthToken.decode(auth_token) user = User.find(decoded_token["user_id"]) if user render json: {user: user, user_role: user.type, auth_toke...
module Auth::Behavior::RememberMe::ControllerExtensions # If a :remember option is given, a remembrance cookie will be set. If omitted, the cookie will be, too. def login_with_remembrance!(user, options = {}) login_without_remembrance!(user) if options[:remember] token = RemembranceToken.create!(...
class Destination < ActiveRecord::Base TYPES = %w(wordpress blogger) belongs_to :user belongs_to :destination_category alias :category :destination_category has_one :credential attr_accessible :destination_id, :destination_type, :title, :url, :credential_attributes, :destination_category_id before_v...
class AddDescriptionAndIntroductionToCourseModules < ActiveRecord::Migration[5.1] def change add_column :course_modules, :introduction, :text end end
class AddNameToUsers < ActiveRecord::Migration[6.0] def change add_column :users, :name, :string add_column :users, :gender, :string add_column :users, :phone, :string add_column :users, :image, :string add_column :users, :address, :text end end
#!/usr/bin/env ruby root = File.expand_path File.dirname(__FILE__) push_to_github = (ARGV == %w(push)) if push_to_github puts 'Pushing to github ...' else puts 'Just generating the doc, call "update_doc.rb push"' end def cmd(cmd) puts ">> #{cmd}" system cmd or raise "#{cmd} failed" end unless File.exist? "...
Rails.application.routes.draw do get '/', to: 'welcome#index' resources :user_cabins resources :images resources :comments resources :cabins resources :users do resources :cabins, only: [:index], as: 'saved_cabins' end # For details on the DSL available within this file, see http://guides.rubyonra...
class ActionController::Routing::RouteSet def load_routes_with_disguise! disguise_routes = File.join(File.dirname(__FILE__), *%w[.. .. config disguise_routes.rb]) add_configuration_file(disguise_routes) unless configuration_files.include? disguise_routes load_routes_without_disguise! end alias_method_...
class Mhp::SkillsController < ApplicationController def index @skills = Mhp::Skill.all paginate json: @skills end end
module BitflyerApi module Configuration CONFIGURABLE_ATTRIBUTES = %i(key secret) attr_accessor *CONFIGURABLE_ATTRIBUTES def configure yield self end end end
require_relative 'validation' require './util/timezone' require 'active_support/inflector' module Fiat class TransactionImport include Fiat::Validation include Fiat::Timezone def initialize @module = nil end def transaction_import(params, send_transaction = true) if @module ...
class RenameListsListInformationToSuperinformation < ActiveRecord::Migration def change rename_column :lists, :list_information_id, :superinformation_id end end
class MessageSetting < ActiveRecord::Base xss_terminate# :sanitize => [:config_value] serialize :config_value, Array include MessageMod extend MessageMod class << self def get_permissions(type) type = 'administrator' if type == 'admin' unless all.present? initialize_settings ...
# # condicionais # # if # puts "digite sua idade" # idade = gets.chomp.to_i # if idade < 18 # puts "Você é menor de idade" # end # # unless print "digite a sua idade:" idade = gets.chomp.to_i # unless idade >= 18 # puts "Você é menor de idade" # else # puts "Você é maior de idade" # end # case case idade ...
require_relative 'template' describe Template do include Template it "should silently process strings without tokens %CODE% and %ALTCODE%." do template('Code is ; This is introduced characters; alt code is ', '5678901234').should == 'Code is ; This is introduced characters; alt code is ' end it ...
module ContentHelper URI_REGEXP = /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix def self.truncate(str, length=30) str.size <= length ? str : str[0..length] + ' ...' end def truncate(str, length=30) str.size <= length ? str : str[0..length] + ' ...' end de...
require_relative '../helpers/ekg_builder' require_relative '../helper_sequences/a000120' class OEIS def self.a109451(n) case n % 8 when 0, 1, 6, 7 then n when 2, 4 then n + 1 when 3, 5 then n - 1 end end end
class HolidayRequest < ActiveRecord::Base include HolidaysHelper has_many :employee_holidays, dependent: :destroy belongs_to :employee belongs_to :authoriser, foreign_key: :authorised_by_id, class_name: :Employee validate :all_days_are_valid def all_days_are_valid (date_from..date_to).to_a.each do |d...
class Ad < ActiveRecord::Base belongs_to :town belongs_to :category, polymorphic: true validates :creator_email, presence: true validates :town_id, presence: true validates :description, length: {maximum: 400} end
class Vote < ActiveRecord::Base belongs_to :question validates_uniqueness_of :token validates_presence_of :token, :question_id, :user, :vote end
module Accepting # handshank = Accepting::HandShank.new(room.acceptings) # handshank.accepting(current_user) # handshank.is_single? # # handshank.is_ # class HandShank def initialize(record, key) @target = record if record.send(key).nil? record.send("#{key}=".to_sym, {}) ...
require 'rspotify/oauth' class FetchPlaybacksJob < ActiveJob::Base queue_as :default def perform(user_id) user = User.find(user_id) if user.token_expires_at < Time.now.to_i response = RSpotify::User.refresh_token(user.uid, user.refresh_token) user.access_token = response['access_token'] ...
require 'spec_helper' describe OJSIssueBuilder do let(:ojs_json_full){ fixture_file('IssueDataWithArticles-21.full.json') } let(:ojs_json_stub){ fixture_file('IssueDataWithArticles-21.stub.json') } let(:ojs_json_multiple_authors){ fixture_file('IssueDataWithArticles-7.json') } it "Accepts JSON from OJS and p...
require_dependency 'mail_handler' module HelpdeskRequiredCfIgnore module MailHandlerPatchIgnore def self.included(base) # :nodoc: base.send(:include, InstanceMethods) base.class_eval do alias_method :receive_issue_without_ignore, :receive_issue alias_method :receive_issue, :receive_is...
class Pattern attr_accessor :pattern, :input_string def initialize(input_string) @input_string = input_string @pattern = self.class.parse_input_string(input_string) end def self.parse_input_string(input_string) input_string.split(',').map(&:to_sym) end def matches?(path) if path.path.leng...
class UserMailer < ApplicationMailer def order_confirmation(order) @url = # generate confirmation url mail(to: order.email, subject: "Confirm your Order!") end end
# level.rb # Okay... Each map is a single floor. # This, on the other hand, is a collection of floors linked together. # This... I may need a wrapper around the maps to provide meta-info like # which floor it is, special features, random events, and so on. # But for now, this should work. require 'map' class Level ...
class Review < ActiveRecord::Base belongs_to :user belongs_to :business has_many :comments end
class CreateStopTimes < ActiveRecord::Migration[5.0] def change create_table :stop_times do |t| t.references :stop, foreign_key: true t.references :trip, foreign_key: true t.time :arrival_time t.time :departure_time t.integer :stop_sequence t.timestamps end end end
require "colorize" require "tty-spinner" require_relative "methods.rb" # -- Loops through each quesion def question_loop type_slow("If you don't input one of the given answers, well...".colorize(:light_yellow)) sleep(0.5) type_slow(" ...you're not helping your case ".colorize(:red)) sleep(1)...
class SessionsController < ApplicationController before_filter :redirect_if_logged_in, only: [ :new, :create ] before_filter :redirect_if_not_logged_in, only: [ :destroy ] def new end def create member = Member.find_by_email(params[:email].downcase) if member if member.authenticate(param...
require 'test_helper' describe WorksController do describe "root" do it "succeeds with all media types" do # Precondition: there is at least one media of each category %w(album book movie).each do |category| Work.by_category(category).length.must_be :>, 0, "No #{category.pluralize} in the tes...
class AddOrderToPages < ActiveRecord::Migration def change add_column :pages, :page_order, :integer add_index :pages, :page_order end end
# A full-text extractor which is tuned towards extracting sentences from news articles. module Boilerpipe::Extractors class ArticleSentenceExtractor def self.text(contents) doc = ::Boilerpipe::SAX::BoilerpipeHTMLParser.parse(contents) ::Boilerpipe::Extractors::ArticleSentenceExtractor.process(doc) ...
class Prime def self.prime?(number) return false if number <= 1 || !number.integer? for i in 2..Math.sqrt(number).to_i return false if (number % i == 0) end true end def self.each(size) primes = self.sequence return primes unless block_given? size.times { yield primes.next } ...
class UsersController < ApplicationController before_action :redirect_if_not_loged_in, only: [:show, :index] before_action :redirect_if_loged_in, only: [:sign_up, :sign_in] def show @user = User.find(session[:user_id]) end def sign_up @user = User.new end def create @user = User.new(first_n...
class CameraRoll < ActiveRecord::Base has_many :takes belongs_to :shooting_day end
class AddDetailsToNotes < ActiveRecord::Migration def change add_column :notes, :username, :string add_column :notes, :note_id, :integer end end
class FeedbackMailer < ApplicationMailer def simple feedback_params @feedback_params = feedback_params mail(to: 'support@bookingsports.ru', subject: "⚽️ Bookingsports: Обратная связь") end end
# == Schema Information # # Table name: export_types # # id :integer not null, primary key # name :string(255) not null # class ExportType < ActiveRecord::Base has_many :export_documents validates :name, presence: true, uniqueness: true, :length => {:maximum => 200} MONTHLY_ACCOUNTING = 'Mo...
require 'spec_helper' describe Deck do it 'is a subclass of Array' do expect(Deck.superclass).to eq(Array) end end
#!/usr/bin/env ruby # Copyright: # (c) 2006 syncPEOPLE, LLC. # Visit us at http://syncpeople.com/ # Author: Duane Johnson (duane.johnson@gmail.com) # Description: # Creates a partial from the selected text (asks for the partial name) # and replaces the text with a "render :partial => [partial_name]" erb fragme...
require 'rails_helper' RSpec.describe ViewHelper do let(:school) { School.new(device_allocations: allocations) } describe '#what_to_order_allocation_list' do context 'with school device allocations' do context 'when devices available to order' do let(:allocations) { [SchoolDeviceAllocation.new(c...
class InventoryItemsController < ApplicationController before_action :set_inventory_item, only: [:show, :update, :destroy] # GET /items def index @inventory_items = InventoryItem.all render json: @inventory_items end # GET /items/1 def show render json: @inventory_item end # PATCH/PUT /in...
require 'rails_helper' describe Site do it 'should belong to a user' do expect(sites(:google).user).to eq(users(:jordan)) end it 'should require a url' do site = Site.new site.valid? expect(site.errors[:url]).not_to be_empty end it 'should require a valid url' do site = Site.new url: 'i...
class SettingsController < ApplicationController before_filter :authenticate_user! before_action :set_setting, only: [:edit, :update] # GET /settings/1/edit def edit end # PATCH/PUT /settings/1 # PATCH/PUT /settings/1.json def update respond_to do |format| if @setting.update(setting_params) ...
require 'spec_helper' describe AccessSchema::Schema do before do @schema = AccessSchema::SchemaBuilder.build_file('spec/schema_example.rb') end describe "#add_role" do it "raises error if duplicate" end describe "#add_assert" do it "raises error if duplicate" end describe "#add_featur...
module StructPacking # Unpackable module provides value assign function from packed byte array. # # A class include this module, and call struct defininesg method, # A instance's unpack method assign variables from packed object. # This module also provide read_struct_data class method # which construct o...
require './lib/messages' class GameBoard include Messages attr_reader :rows, :spaces def initialize @rows = [['a1', 'b1', 'c1', 'd1'],\ ['a2', 'b2', 'c2', 'd2'],\ ['a3', 'b3', 'c3', 'd3'],\ ['a4', 'b4', 'c4', 'd4']] @s...
#--------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache License, Version 2.0. # See License.txt in the project root for license information. #---------------------------------------------------------...
require "rails_helper" RSpec.describe "MutationType::SignUp" do let(:mutation) do %( mutation{ signUp( authProvider:{ credentials:{ email:"test@example.com" password:"123456" } } ){ user{ id ...
require 'spec_helper' describe 'users/campaigns/_form' do let(:campaign) { create(:charity).campaign } before do # Set the tier tagline campaign.tiers.each do |tier| tier.update_attributes(:tagline => "Donate #{tier.amount}") end render :partial => 'users/campaigns/form', :locals => { :campa...
class ChangeTableToPin < ActiveRecord::Migration def change rename_table :tables, :pins end end
class FontSeoulNamsan < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/seoulnamsan" desc "Seoul Namsan" homepage "https://english.seoul.go.kr/seoul-views/seoul-symbols/5-fonts/" def install (share/"fonts").install "SeoulNamsan-Bold.tt...
require 'openssl' class Secret ITERATIONS = 2000 attr_accessor :cipher, :message def initialize(message = nil) @cipher = OpenSSL::Cipher.new 'AES-128-CBC' @message = message end def save(pwd) cipher.encrypt iv = cipher.random_iv salt = OpenSSL::Random.random_bytes 16 key_len = cip...
class Ballot < ActiveRecord::Base belongs_to :source has_many :candidate_ballots has_many :candidates, :through => :candidate_ballots, :order => 'candidate_ballots.order' has_many :contests belongs_to :referendum belongs_to :custom_ballot has_many :custom_notes, :as => :object end
require 'redmine' require 'mail_handler_patch_ignore' Redmine::Plugin.register :helpdesk_required_cf_ignore do name 'Helpdesk ignore required custom field for e-mail' author 'Sergey Melnikov' description 'This is a plugin for Redmine' version '0.0.1' url 'https://github.com/SimSmolin/helpdesk_required_cf_igno...
class BooksController < ApplicationController before_action :logged_in_user, only: [:index, :show, :new, :create, :destroy] def index @book_list = Book.all end def show @book = Book.find(params[:id]) @user_id = current_user.name end def new @book = Book.new end def create ...
class Parser attr_reader :ast def initialize @ast = [] @state = :start end def build_ast(token) if token case @state when :start if token[:id] == :integer @ast << {operate: [token[:value]]} @state = :operate elsif token[:id] == :subzero ...
require 'spec_helper' describe RegistrationsController do context "#new" do before { get :new } it { should respond_with(:success) } it { should render_template(:new) } it { should assign_to(:registration) } end end
class ApplicationController < ActionController::Base protect_from_forgery before_filter :set_locale helper_method :current_user def set_locale I18n.locale = current_user.locale if current_user and current_user.locale end private def current_user @current_user ||= User.find(session[:user_id]) ...
json.array!(@logs) do |log| json.extract! log, :person, :time, :text, :created_at, :updated_at # json.url user_url(user, format: :json) end