text
stringlengths
10
2.61M
class MakeGameSlugUnique < ActiveRecord::Migration def up add_index :games, :slug, { :name => 'unique_slug', :unique => true } end def down remove_index :games, :name => 'unique_slug' end end
module MinimedRF module PumpEvents class SetAutoOff < Base def self.event_type_code 0x1b end def bytesize 7 end def to_s "SetAutoOff #{timestamp_str}" end def timestamp parse_date(2) end end end end
module DebugFile class Runner ARCHIVE_PATH = File.expand_path('~/Library/Developer/Xcode/Archives') attr_accessor :options def initialize(options = {}) @options = options end def latest_dsym(filter: :date) dsyms = list_dsym case filter when :version dsyms.max_by ...
# frozen_string_literal: true class Users::SessionsController < Devise::SessionsController layout 'registrations_application' before_action :configure_sign_in_params, only: [:create] before_action :recaptcha, only: [:create] def create super if verify_recaptcha(model: @user) && @user.save ...
require "rails_helper" RSpec.describe "static_pages/index" do it "displays @posts, @services, @personals, @contact, @order, @back_phone and @services_footer the static_pages" do assign(:static_pages, [ @services = [create(:service, title: 'Первая услуга'), create(:service, title: 'Вторая...
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 require 'spec_helper' describe "README" do renderer = TwitterCldr::Resources::ReadmeRenderer.new( File.read(File.join(File.dirname(__FILE__), "../README.md.erb")) ) renderer.render renderer.assertion_failures.ea...
# frozen_string_literal: true RSpec.describe Might::FilterParametersExtractor do context '#call' do # @param parameters_definition [Might::FilterParameterDefinition] def extractor(parameters_definition) app = ->(env) { env[0] } described_class.new(app, Might::FilterParameters.new([parameters_defin...
RSpec.describe Emulator::Emulator do context "#define_board_size" do let(:emulator) {Emulator::Emulator.new} it "Board size is in range" do input_sizeboard = '3' allow_any_instance_of(Kernel).to receive(:gets).and_return(input_sizeboard) expect(emulator.send(:define_board_size)).to eq(input...
# frozen_string_literal: true require 'rails_helper' require 'sidekiq/testing' Sidekiq::Testing.fake! RSpec.describe AppsApi::DirectoryLoader, type: :worker do subject { described_class } let(:directory_loader) { AppsApi::DirectoryLoader.new } let(:time) { (Time.zone.today + 1.minute).to_datetime } let(:sch...
class Product < ApplicationRecord before_save :strip_html_from_description before_save :set_all_title_lower_case belongs_to :category, optional: true scope :published, ->{where(published: true)} scope :price_more_then, ->(price) {where('price >?', price)} validates :title , :description, :price, presence...
class LRUCache def initialize(size) @size = size @hash = Hash.new @head = ListNode.new(:head) @tail = ListNode.new(:tail) @head.child = @tail @tail.parent = @head end def count # returns number of elements currently in cache @hash.count end def add(el) # adds element to ca...
# frozen_string_literal: true require 'active_support' require 'active_record' # NOTE: # This monkey patch add argument(json) for ActiveRecord::Relation#explain. # Argument json is default false. Therefore, it does not affect the default behavior. # Only MySql and Postgresql are supported. # rubocop:disable all modu...
# frozen_string_literal: true # Coinの操作をまとめたモジュール。 # includeして使うこと。 module Coin extend ActiveSupport::Concern MAX_TRANSACTION_AMOUNT = 500 module_function # 指定額を自分の財布から引いて相手の財布に送り、その履歴を保存するメソッド # == Args # * amount :: 贈与額(Integer) # * from :: 渡す側のUserオブジェクト # * to :: 渡す相手のUserオブジェクト # * revie...
module Gradebook module Components module Models class Base # extend ExecutionHooks ## # Setting instance variables on all attributes passed for initialization # Params: # => attributes (.: key-value pairs) # Example: new(:name => 'John Deo',...
class IdCardTemplatesController < ApplicationController filter_access_to :all def rtl? if session[:language].nil? lan = Configuration.find_by_config_key("Locale").config_value lan = "en" unless lan.present? else lan=session[:language] end if controller and is_cce_controller? ...
class CreateInscricoes < ActiveRecord::Migration def change create_table :inscricoes do |t| t.string :cpf t.string :nome t.string :rg t.string :endereco t.string :bairro t.string :numero t.string :complemento t.string :cep t.string :email t.stri...
# frozen_string_literal: true class ReadingSyncProcessor def process loop do available_entries.each do |k, value| REDIS.pipelined do create_db_entry(k, value) REDIS.hdel('reading_queue', k) end end rescue StandardError => e logger.error "Failed write erro...
module PlayerCardsHelper def inches_to_feet_and_inches(inches) feet_and_inches = inches.divmod(12) "#{ feet_and_inches.first }'#{ feet_and_inches.last }\"" end def style_title(style) if style == '43' then '4-3' elsif style == '34' then '3-4' else style.titleize end end def stat_table...
require 'rails_helper' RSpec.describe User, :type => :model do it { should validate_presence_of :email } it { should validate_uniqueness_of :email } it { should ensure_length_of :email } it { should have_many :equipments } it { should have_many :requests } describe "#confirm" do subject do Fabri...
class CreatePictureLikes < ActiveRecord::Migration def change create_table :picture_likes do |t| t.integer :user_id, null: false t.integer :picture_id, null: false t.timestamps end add_index :picture_likes, :user_id add_index :picture_likes, :picture_id end end
require 'spec_helper' describe 'apress/videos/api/v1/videos/show', type: :view do let(:video) { create :video, :with_oembed_data } let(:schema) do { type: 'object', required: ['video'], properties: { video: { required: [%w(id url oembed_data position status)], pro...
FactoryGirl.define do factory :user do email password { generate :password } password_confirmation { password } first_name { generate :human_name } last_name { generate :human_name } photo state { User.state_machines[:state].states.map(&:name).first.to_s } end factory :admin, parent:...
require File.dirname(__FILE__) + '/../../spec_helper' describe "/serie_comparativas/new.html.erb" do include SerieComparativasHelper before(:each) do @serie_comparativa = mock_model(SerieComparativa) @serie_comparativa.stub!(:new_record?).and_return(true) @serie_comparativa.stub!(:hecho).and_return(...
class Category < ApplicationRecord belongs_to :budget has_many :transactions monetize :balance_cents, :monthly_amount_cents def remaining_per_day MonthlyCalculator.new(balance, Date.today).daily_amount end end
input = File.open("#{File.dirname(__FILE__)}/input", 'rb').read class Solution attr_reader :command_pairs, :register, :max_val def initialize(input) @command_pairs = format_input input @register = Hash.new(0) @max_val = 0 end def part_1 command_pairs.each do |pair| command, c...
Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html resources :buyers resources :products resources :sellers # Auth routes post '/auth_buyer', to: 'auth#create_buyer' get '/current_buyer', to: 'auth#show_buyer' post '/a...
require 'spec_helper' describe TwitterDataController do before(:each) do @controller.stub(:authenticate_user!) end def valid_attributes { :client_id => 1, :global_goal => "Objetivo Followers Text", :new_followers => 10, :total_followers => 10, :goal_followers => 10, :amount_tweets => 10, :...
# Create a method that takes a single argument. def raindrops(num) # Start off with an empty string. We'll be pushing the strings "Pling", "Plang" and "Plong" to this as necessary. str = "" # We could write the tests in a way we're pretty familiar with... # if num % 3 == 0 # str += "Pling" # end # .....
require 'net/http' require 'uri' require 'json' require 'ipaddr' class MapController < ApplicationController DATA_SOURCES = {:epayments => 30102, :requests => 30103, :transactions => 30104} def index end def get_data respond_to do |format| format.json do render :json => get_latest_data ...
class Record < ActiveRecord::Base include PgSearch pg_search_scope :search_stuff, against: [:metadata, :pure_uuid], using: { tsearch: { prefix: true, highlight: { start_sel: '<b>', stop_sel: '</b>', } } } belongs_to :doi_registration_agent...
# frozen_string_literal: true RSpec.describe MigrationScripts::SeedInitialTalks do it 'spec_name' do _alice = create(:user) described_class.new.seed expect(TalkSummary.count).to eq(1) expect(Talk.first.video_url).to eq('https://www.youtube.com/watch?v=URSWYvyc42M') end end
class ApplicationController < ActionController::Base before_action :authorize, except: [:index] protect_from_forgery with: :exception helper_method :current_user def index @projects = Project.last(3).reverse render '/index' end private #check session user id exist def authorize ...
class CreateBalls < ActiveRecord::Migration def change create_table :balls do |t| t.integer :ball_number t.integer :pins_knocked t.references :frame, index: true, foreign_key: true t.timestamps null: false end end end
load '/Users/pk/personal/math/Sloanes/lib/scripts/helpers/subset_logic.rb' def all_substrings(n) s = n.to_s(2) (1...s.length).to_a .map_subsets { |is| split_along_indices(s, is) } end def all_numeric_substrings(n) all_substrings(n) .select { |part| part.all? { |x| x =~ /(^1)|^0$/} } end def a306921(n) ...
class Rank < ApplicationRecord has_and_belongs_to_many :volunteers end
require 'rails_helper' feature 'User signs out', %Q{ As an already authenticated user I want to sign out so that I can exit } do # Acceptance Criteria #* I specify an email and password to sign in # * If I'm already signed in # I don't have to sign in again. # * I want to sign out # once I'm finis...
# encoding: UTF-8 module API module V1 class Users < API::V1::Base helpers API::Helpers::V1::UsersHelpers namespace :users do desc 'Create a new user' params do requires :user, type: Hash do requires :classes_codes, allow_blank: false requires :firs...
class AddRememberTokenToUsers < ActiveRecord::Migration def change # add the following after the migration of remember_token # rails generate migration add_remember_token_to_users # after adding below code run # bundle exec rake db:migrate # bundle exec rake test:prepare add_column :users, :remember...
class RemoveAvatarAndCoverFromEvents < ActiveRecord::Migration def change remove_column :events, :avatar remove_column :events, :cover end end
# frozen_string_literal: true class ImageUploadsController < AdminController def index s3_bucket_path = "http://#{ENV['S3_BUCKET']}.s3.amazonaws.com/" response = HTTParty.get(s3_bucket_path).parsed_response contents = response['ListBucketResult']['Contents'].select { |content| content['Size'].to_i != 0 ...
module Expression class Main < Treetop::Runtime::SyntaxNode def evaluate(context, result) elements.each { |node| node.elements[0].evaluate(context, result).to_s } end end class LineComment < Treetop::Runtime::SyntaxNode def evaluate(context, result) '' end end class FunctionBodyE...
# 1. Enter a numeric value # 2. Numeric value cannot contain letters (if so, alert user, and only continue when criteria is true) # 3. User chooses math operation # 4. Results # 5. Ask user if wants to do more math. # 6. If user decides to do so, go back to enter the numbers. If no, end. puts "--- Calculator ---" puts...
# frozen_string_literal: true module Github class GithubService class << self include SentryLogging extend Memoist GITHUB_REPO = 'department-of-veterans-affairs/vets.gov-team' def create_issue(feedback) client.create_issue( GITHUB_REPO, issue_title(feedback),...
class Subject < ApplicationRecord #履修科目 has_many :student_subjects #学生履修科目を複数もっている has_many :students, through: :student_subjects #student_subjectsを返して複数の学生と紐づいている end
#!/usr/bin/env ruby # encoding: UTF-8 require './piece' require './error' class Board attr_accessor :board, :players SIZE = 8 def initialize(players) @board = Array.new(SIZE) {Array.new(SIZE)} @players = players players.each {|player| player.board = self} place_pieces end def game_over? ...
class Project < ApplicationRecord belongs_to :company, class_name: 'Company', foreign_key: 'company_id' has_many :bugrequests, class_name: 'BugRequest', foreign_key: 'bugrequest_id' end
module SupplyTeachers class Journey::FTACalculatorSalary include Steppable attribute :salary validates :salary, presence: true validate :valid_salary def next_step_class Journey::SchoolPostcodeAgencySuppliedWorker end private def valid_salary errors.add(:salary, :invali...
class Issue < ActiveRecord::Base belongs_to :property scope :new_task, -> { where status: 'New' } scope :in_progress, -> { where status: 'In Progress' } scope :complete, -> { where status: 'Complete' } scope :archive, -> { where status: 'Archive' } scope :not_complete, -> { where(:status => ["New", "In Pro...
# rubocop:disable Metrics/AbcSize, Metrics/BlockLength, Metrics/MethodLength Hyrax::FileSetIndexer.class_eval do def generate_solr_document super.tap do |solr_doc| solr_doc['hasRelatedMediaFragment_ssim'] = object.representative_id solr_doc['hasRelatedImage_ssim'] = object.thumbnail_id # Label i...
class Project < ActiveRecord::Base validates :name,:presence=> true validates_length_of :name, :in => 5..50 has_many :tasks def incomplete_tasks tasks.where(complete: false) end def complete_tasks tasks.where(complete: true) end end
require File.dirname(__FILE__) + '/../test_helper' class UserPreferenceControllerTest < ActionController::TestCase fixtures :users, :user_preferences def test_read # first try without auth get :read assert_response :unauthorized, "should be authenticated" # now set the auth basic_author...
class EARMMS::Token < Sequel::Model def self.generate_session(user) user = user.id if user.respond_to?(:id) t = EARMMS::Crypto.generate_token now = Time.now self.new(user: user, use: 'session', token: t, created: now, last_used: now, valid: true) end def self.generate_password_reset(user) us...
module Admin class PostsController < ApplicationController before_action :authorize_admin expose_decorated :post, find_by: :slug expose_decorated :posts, :fetch_posts expose :q, :fetch_query def index end def edit end def update post.update(post_params) redirect_to...
require 'spec_helper' describe Channels::ProjectsController do let(:channel) { create(:channel) } let(:project) { build(:project) } before do @request.host = "#{channel.to_param}.example.com" end context 'authorized' do before do sign_in channel.user end describe 'create' do it...
class ChangeGenericDateName < ActiveRecord::Migration def change rename_column :events, :generic_date, :start_date end end
class SheetConverter::CLI < Thor desc "xlsx2csv INPUT_PATH", "convert XLSX files to CSV files at the same folder" option :output, aliases: [:o], desc: "specify the output directory" def xlsx2csv(input_path) nav_input_files(input_path, ".xlsx") do |file| file_xlsx_to_csv(file, dir: options[:output]) ...
# frozen_string_literal: true # helpers to enable / disable error bubbling in a block scope. # # Some schemas are made with `.define`, others are `class`, so we have to support both. module ErrorBubblingHelpers def without_error_bubbling(schema) original_error_bubbling = !!schema.error_bubbling begin if...
class AddCurrencyToDialogues < ActiveRecord::Migration def change add_column :dialogues, :currency, :string, :default => "dollars" end end
class CreateDiscussionsTable < ActiveRecord::Migration def up create_table :discussions do |t| t.integer :creator_id, :null => false t.integer :curated_collection_id, :null => false t.string :title, :null => false t.timestamps end end def down drop_table :discussions end end...
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 require 'spec_helper' describe TwitterCldr::Utils do describe '#deep_symbolize_keys' do let(:hash) { { 'foo' => { 'bar' => { 'baz' => 'woot' }, ar: [1, 2] }, 42 => { 'baz' => 'wat' } } } let(:symbolized_hash) { { ...
# encoding: utf-8 # # © Copyright 2013 Hewlett-Packard Development Company, L.P. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights #...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
class Clock include Comparable def self.at(hours, minutes) new(hours, minutes) end def to_s "#{format_string(hours)}:#{format_string(minutes)}" end def +(added_minutes) @given_minutes += added_minutes self end def <=>(other) if self.hours > other.hours 1 elsif self.h...
class Questions::CommentsController < CommentsController before_action :set_question private def set_question @question = Question.find(params[:question_id]) end end
class AddDateToMatches < ActiveRecord::Migration def change add_column :matches, :meetup, :boolean end end
class UserNotificationsController < ApplicationController before_action :signed_in, :correct_user, only: [:new, :create] def create self.format_message() @user_notification = Event.find(cookies.signed[:current_event_id]).user_notifications.build(user_notification_params) @user_notification.user_id = current_us...
module Webmachine class Dispatcher class Route # Determines whether the given variables provides all the required # variables to create a URL for the route. # @param [Hash] vars the candidate variables for the route def path_spec_satisfied?(vars) path_spec.select { |p| Symbol ===...
FactoryGirl.define do factory :regular_message do number "MyString" message "MyString" end end
# frozen_string_literal: true class AddBadgeToSkills < ActiveRecord::Migration[6.1] def change add_column :skills, :badge, :text end end
module Fastlane module Actions class AppliveryAction < Action def self.run(params) app_id = params[:app_id] api_key = params[:api_key] name = params[:name] notes = Helper::AppliveryHelper.escape(params[:notes]) tags = params[:tags] build_path = params[:build_...
class Admin::SpecialRequestsController < Admin::ApplicationController before_action :set_event, :set_reception, only: [:new, :create, :destroy] def new @special_request = SpecialRequest.new @reception = Reception.find_by(id: params[:reception_id]) end def create @special_request = SpecialRequest.n...
require_relative "board" class Piece attr_accessor :color, :pos, :board, :promoted # red pawn's moves S_DELTAS_RED = [[-1,1], [-1,-1]] J_DELTAS_RED = [[-2,2], [-2,-2]] # black pawn's moves S_DELTAS_BLACK = [[1,1], [1,-1]] J_DELTAS_BLACK = [[2,2], [2,-2]] # king piece's moves S_DELTAS_KING = S_DELTAS...
require "formula" class NdnCxx < Formula version "0.4.0" homepage "http://named-data/doc/ndn-cxx/" url "https://github.com/named-data/ndn-cxx", :using => :git, :tag => "ndn-cxx-0.4.0" head "https://github.com/named-data/ndn-cxx", :using => :git, :branch => "master" depends_on "pkg-config" => ...
# frozen_string_literal: true class UsersController < ApplicationController def show render json: current_user end def update return change_email if action_change_email if action_reset_password user = User.find_by(email: params[:email]) return head 200 if user&.reset_password end ...
#!/usr/bin/env ruby require 'rubygems' require 'bundler/setup' require 'thor' require 'pry' require 'active_support/all' require 'xcodeproj' # noinspection RubyClassVariableUsageInspection class Generate < Thor include Thor::Actions @@app_root = File.expand_path('../../Clean', __FILE__) @@src_main_root = "#{@@...
class Satya < ApplicationRecord validates :name,presence: { message: "Baki sarv bhokat nav pahejech" } validates :subject,presence: { message: "Be pahejech" } validates :phone_no, numericality: true validates :email_id, uniqueness: true validate :check_name def check_name if name == "admin...
class SelectedRestaurant < ApplicationRecord belongs_to :restaurant belongs_to :event has_many :votes end
class UserSerializer include FastJsonapi::ObjectSerializer attributes :username, :name has_many :bookmarks, serializer: BookmarkSerializer #reference: https://github.com/Netflix/fast_jsonapi/issues/160 attribute :bookmarks do |object| BookmarkSerializer.new(object.bookmarks).as_json["data"] end end
class MeetingsController < ApplicationController before_action :logged_in_user, only: [:index, :show] before_action :admin_user, only: [:destroy, :create, :edit, :update, :new] def index @meetings = Meeting.order("date DESC").paginate(page: params[:page], :per_page => 10) end def show @meeting ...
# encoding: UTF-8 module CDI module V1 module ChatMessages class CreateService < BaseCreateService record_type ::ChatMessage attr_reader :chat_room WHITELIST_ATTRIBUTES = [:content] def initialize chat_room, user, options={} super user, options @chat_...
class TimeRange < ActiveRecord::Base self.primary_key = :information_id belongs_to :information, class_name: :BasicInformation validate :validate_time_range private def validate_time_range return if self.end.blank? || self.begin.blank? if self.end < self.begin errors.add(:end, "must be after ...
namespace :db do desc "Migrate one version back (or to the version specified as OLD=x), and then up to the current" task :remigrate => :environment do current_version = ActiveRecord::Migrator.current_version old_version = (ENV["OLD"] ? ENV["OLD"].to_i : current_version - 1) ActiveRecord::Migrator...
=begin Jenny has written a function that returns a greeting for a user. However, she's in love with Johnny, and would like to greet him slightly different. She added a special case to her function, but she made a mistake. Can you help her? =end #Solution: def greet(name) return name == "Johnny" ? "Hello, my love!"...
class VideosController < ApplicationController def index @videos = Video.paginate(:page => params[:page], :per_page => 12) end end
class Company < ActiveRecord::Base has_many :funding_rounds, dependent: :destroy has_many :investors, -> { uniq.order(:name) }, through: :funding_rounds has_many :jobs, dependent: :destroy validates :name, presence: true before_save :calculate_total_money_raised def self.permaname name name.downcase....
class AddLastnameToDebits < ActiveRecord::Migration def change add_column :debits, :lastname, :string end end
FactoryBot.define do factory :course do sequence(:name) { |n| "Course #{n}" } educator end end
# -*- coding: utf-8 -*- require 'date' # IDからシンボルを作る def sym(base, id) (base + id.to_s).to_sym end class SSTP METHODS = { :send11 => ["SEND", "1.1"] } def initialize(ip_addr, port) @ip_addr = ip_addr @port = port @mutex = Mutex.new end def send11(script) requests = [] reques...
module Dom class Proposal < Domino selector '.proposal' attribute :title attribute :speakername attribute :description attribute :email attribute :bio end module Flash class Error < Domino selector '.alert-error' end class Success < Domino selector '.alert-success...
class Post < ActiveRecord::Base has_many :comments validates_presence_of :body, :title has_many :post_attachments accepts_nested_attributes_for :post_attachments end
FactoryGirl.define do factory :area_code, :class => Refinery::Properties::AreaCode do sequence(:name) { |n| "refinery#{n}" } end end
class PostsController < ApplicationController before_action :authenticate_user! skip_before_action :verify_authenticity_token before_action :load_user, only: :create before_action :load_book, only: :create before_action :load_posts, only: %i[index create] before_action :load_post, only: %i[close_post des...
class Social < ApplicationRecord belongs_to :portfolio enum kind: [:facebook, :twitter, :linkedin, :github, :other, :instagram] validates :url, presence: true, http_url: true end
class ApplicationController < ActionController::Base helper_method :current_user def current_user @current_user ||= User.find_by(id: session[:user_id]) end private def require_authentication! redirect_to login_path unless current_user end def set_user!(user) session[:user_id] = ...
require 'test_helper' class InclusionTest < Minitest::Spec class Order < TestModel attr_writer :line_items def line_items @line_items ||= [] end end class LineItem < TestModel attr_accessor :product end class Product < TestModel end class OrderSerializer < SimpleJsonapi::Seriali...
class InvoicedItem < ApplicationRecord belongs_to :invoice belongs_to :product, class_name: "Item" belongs_to :sales_order_item, optional: true validates :invoice_id, numericality: { greater_than: 0 } validates :product_id, numericality: { greater_than: 0 } validates :sales_order_item_id, numericality: { g...
class VideosController <ApplicationController def index @videos = Video.all @video = Video.new end def create @video = Video.new(params_video) @video.file = params[:file] # Hacky! Unable to raise CarrierWave::IntegrityError if params[:video][:file].present? && !params[:video][:file].cont...
Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html scope module: :public do root to: 'homes#index' resource :homes, only: :index end end
desc "Release a new project version" task :release do require 'active_support' require 'active_support/core_ext' require 'more_core_extensions/core_ext/hash/nested' require 'pathname' require 'yaml' version = ENV["RELEASE_VERSION"] if version.blank? STDERR.puts "ERROR: You must set the env var RELEA...
ActiveAdmin.register Project do # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # # permit_params :list, :of, :attributes, :on, :model # has_many :pictures menu priority: 0 permit_params :name, :location, :...