text stringlengths 10 2.61M |
|---|
class ArrayDiff
def initialize(params)
params.assert_valid_keys :new, :old
@new = params[:new]
@old = params[:old]
end
def added
(@new - @old).sort
end
def deleted
(@old - @new).sort
end
def intersection
(@old & @new).sort
end
def union
(@old | @new).sort
end
def ... |
class UsersController < ApplicationController
before_action :require_signin,except: [:new,:create]
before_action :require_correct_user ,only:[:edit,:update,:destroy]
def index
@users=User.all
end
def show
@user=User.find(params[:id])
end
def new
@user=User.new
end
def create
@user=User.new(user_par... |
class User < ActiveRecord::Base
has_secure_password
has_many :comments
# Posts created by the user
has_many :posts
# Votes about this user (via votable)
has_many :votes, as: :votable
# Votes cast by the user (via user_id foreign key)
has_many :ratings, class_name: 'Vote'
validates :email,
presence... |
class CreateOrganizations < ActiveRecord::Migration
def change
create_table :organizations do |t|
t.string :address
t.text :recipient_emails, array: true, default: []
t.text :member_emails, array: true, default: []
t.timestamps
end
add_index :organizations, :recipient_emails, usin... |
require 'byebug'
class Question < ActiveRecord::Base
belongs_to(
:poll,
primary_key: :id,
foreign_key: :poll_id,
class_name: "Poll"
)
has_many(
:answer_choices,
primary_key: :id,
foreign_key: :question_id,
class_name: "AnswerChoice"
)
has_many(
:responses,
through: :... |
# Stack = LIFO (Last in first out)
# Queue = FIFO (First in first out)
class Stack
attr_accessor :array0
def initialize
@array0 = []
end
def add(x)
array0 << x
end
def remove
array0.pop
end
end
class Queue
attr_accessor :array0
def initialize
@array0 = []
end
def add(x)
... |
class Venue < ActiveRecord::Base
validates_presence_of :name
belongs_to :artist
end |
$LOAD_PATH.unshift(File.expand_path("../lib", __FILE__))
require "jekyll/assets/version"
Gem::Specification.new do |spec|
spec.version = Jekyll::Assets::VERSION
spec.homepage = "http://github.com/jekyll/jekyll-assets/"
spec.authors = ["Jordon Bedwell", "Aleksey V Zapparov", "Zachary Bush"]
spec.email = ["jordo... |
require "test_helper"
class RegistrationsControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
test "get show payment settings" do
sign_in(users(:commissioner))
get edit_payment_settings_user_registration_url
assert_response 200
end
test "get edit payment sett... |
class SettingsPage
include PageObject
page_section :top_bar, TopBarSection, css: '.pull-left'
div :body, id: 'body'
link :leads, css: '[href="/settings/leads"]'
link :lead_statuses, css: '[href="#lead-status"]'
link :tags, css: '[href="#tags"]'
button :new_edit, xpath: '(//*[@id="lead-status"]//button)[... |
class QuestionsController < ApplicationController
def new
@newest_questions = Question.order('created_at desc').limit(10)
@question = Question.new
@hash = Gmaps4rails.build_markers(@users) do |user, marker|
marker.lat user.latitude
marker.lng user.longitude
end
end
def create
@qu... |
require 'rails_helper'
describe 'editing restaurants' do
before do
@nikesh = User.create(email: 'n@n.com', password: '12345678', password_confirmation: '12345678')
login_as @nikesh
@nikesh.restaurants.create(name: 'Nandos', phone_number: '02089540598', location_name: 'shoreditch')
end
context 'logged in a... |
class RegistrationsController < ApplicationController
def show
date = Date.parse(params[:id])
registrations = Registration.where('created_at > ? and created_at < ?',
date.beginning_of_day, date.end_of_day).includes(:student)
@students = registrations.map{|r| r.stude... |
# Example of a method that modifies its argument permanently
# mutate.rb
#a = [1, 2, 3]
#def mutate(array)
# array.pop
#end
#p "Before mutate method: #{a}"
# mutate(a)
#p "After mutate method: #{a}"
# Example of a method that does not mutate the caller
# mutate.rb
a = [1, 2, 33]
def ... |
class Room < ApplicationRecord
belongs_to :cinema
has_many :seat
has_many :films
has_many :booking_tickets
end
|
# require 'rails_helper'
#
# feature "search bar" do
# before(:each) do
# @user1 = User.create(username: "User1", password: "password", email: "example1@gmail.com")
#
# visit new_user_session_path
#
# fill_in 'Email', with: "example1@gmail.com"
# fill_in 'Password', with: "password"
# click_button... |
module QuickJobs
module Job
STATES = {:waiting => 1, :running => 2, :done => 3, :error => 4}
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def quick_jobs_job!(opts={})
include QuickScript::Eventable
opts[:for] ||= :mongoid
if opts[:for... |
require File.expand_path('../../spec_helper', __FILE__)
describe CacheBuster do
before(:all) do
# ensure default after previous tests
Radiant::Config['cache_buster.timeout'] = CacheBuster::DEFAULT_TIMEOUT
end
describe '.buster' do
it 'should return cache buster' do
CacheBuster.buster.should b... |
namespace :db do
desc "Create 100 contacts with faker data"
task :populate => :environment do
require 'populator'
require 'faker'
Contact.populate 100 do |contact|
contact.first_name = Faker::Name.first_name
contact.last_name = Faker::Name.last_name
contact.email = Faker::Int... |
class ChangeContactToBeStringInUsers < ActiveRecord::Migration[5.0]
def change
change_column :admin_users, :phone, :string
change_column :users, :contact, :string
end
end
|
require "spec_helper"
RSpec.describe "Day 22: Crab Combat" do
let(:runner) { Runner.new("2020/22") }
let(:input) do
<<~TXT
Player 1:
9
2
6
3
1
Player 2:
5
8
4
7
10
TXT
end
describe "Part One" do
let(:solution) { runner.execut... |
require 'bulutfon_sdk/rest/base_request'
module BulutfonSDK
module REST
class CallRecord < BaseRequest
def initialize(*args)
super(*args)
@resource = 'call-records'
end
def get( uuid, encrypt_token = false )
uri = prepare_uri("#{@resource}/#{uuid}", {encrypt_token: enc... |
class Contactmailer < ActionMailer::Base
default from: "from@example.com"
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.contactmailer.reply.subject
#
def reply(content)
@greeting = "Hi"
@admin = content[:from]
@contact = content[:to]
... |
# -*- coding: utf-8 -*-
=begin
--------------------------------------------------------------------------------------------------------------------
<copyright company="Aspose" file="storage_api.rb">
</copyright>
Copyright (c) 2022 Aspose.HTML for Cloud
<summary>
Permission is hereby granted, free of... |
class DownloadFolder < ActiveRecord::Base
belongs_to :club
has_many :downloads, :dependent => :destroy
validates_presence_of :name, :club_id
validates_numericality_of :club_id
validates_uniqueness_of :name, :scope => [:club_id]
attr_protected :id,
:club_id,
... |
class Log < ActiveRecord::Base
self.per_page = 15
#获取日志清单
def self.get_logs(search_email,page)
Log.where("email like ?", "%#{search_email}%").order('created_at desc').paginate(:page => page, :per_page => per_page)
end
#获取日志数量
def self.get_logs_count
Log.count
end
#记录日志
def self.log(email,action,reques... |
FactoryGirl.define do
factory :stock_item do
name Faker::Commerce.product_name
description "Best thing you'll ever buy!"
price 199.99
taxable true
trait :no_tax do
taxable false
end
trait :with_a_store do
association :store
end
end
end
|
# frozen_string_literal: true
# a model storing github login information
class GithubUser
attr_reader :login,
:html_url
def initialize(attributes)
@login = attributes[:login]
@html_url = attributes[:html_url]
end
end
|
class FundingRound
attr_accessor :vc, :amount, :type
attr_reader :startup
@@all = []
def initialize(startup, vc, amount, type)
@startup =startup
@vc = vc
@amount = amount
@type = type
@@all << self
end
def type
@type
end
def self.all
... |
require 'fakeweb'
module Gravatar::TestCase
class << self
attr_accessor :fixtures_path
end
Gravatar::API_METHODS.each do |method_name|
define_method method_name do |*args, &block|
allow_net_connect = FakeWeb.allow_net_connect?
begin
apply_current_mock!
grav.send(method_name... |
require 'digest/sha1'
module Pigeon::Support
# Uses the double-fork method to create a fully detached background
# process. Returns the process ID of the created process. May throw an
# exception if these processes could not be created.
def daemonize(logger = nil)
delay = 10
rfd, wfd = IO.pipe
... |
class ActivityPolicyInferrer
attr_accessor :method_name
attr_accessor :object
def initialize(method_name, object)
@method_name = method_name.to_s
@object = object
end
def key_name
infer_activity
end
def policy_method?
method_name.last == '?'
end
private
def infer_activity
si... |
module Mutations
CreatePool = GraphQL::Relay::Mutation.define do
name "CreatePool"
input_field :pool_title, !types.String
return_field :pool_edge, Queries::PoolType.edge_type
return_field :viewer, Queries::Viewer
resolve ->(inputs, _context) do
pool = ::Pool.create!(title: inputs[:pool_ti... |
require_relative 'interface.rb'
class Game
include Interface
def initialize(board, player_1, player_2)
@board = board
@player_1 = player_1
@player_2 = player_2
end
def gameplay
print_board
until is_game_over?
action(@player_1)
action(@player_2)
end
end
def wi... |
require_relative 'Connection'
require_relative 'Job'
class Worker
attr_accessor :name, #name of the worker used to identify it in the monitor
:workspace, #connection where the worker store its data during the computation
:source, #conne... |
#!/bin/ruby
n = gets.strip.to_i
a = Array.new(n)
for a_i in (0..n-1)
a_t = gets.strip
a[a_i] = a_t.split(' ').map(&:to_i)
end
def diagonal_diff(array_a)
sum_array = array_a.map.with_index { |sub_array, index|
sub_array[index] - sub_array[-1-index]
}.reduce(:+).abs
end
print diagonal_dif... |
class Numeric
def pow(m)
raise TypeError, "exponent must be an integer: #{m}" unless m.is_a? Integer
Array.new(m, self).reduce(1, :*)
end
end
for i in 0..1000000000
2017.pow(12)
19.88.pow(12)
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# All Vagrant configuration is done here. The most common configuration
# options are documented and commen... |
Given(/^I have an account$/) do
@user = create(:user)
@user.save
expect(@user.name).to eql "Someone"
expect(@user.email).to eql "someone@example.com"
end
Given(/^I have forgotten my password$/) do
true
end
Given(/^I am logged in$/) do
visit let_the_right_one_in_path
fill_in "session_email", with: "some... |
require 'minitest/autorun'
require_relative 'solution'
class SolutionTest < Minitest::Test
def test_the_truth
Enums.map(:direction, to: [:east, :west, :north, :south])
assert_equal 4, Traveling.new.move_towards(:west)
end
end
|
require 'json'
require_relative 'Measure.rb'
class User
@@file = 'data.json'
attr_accessor :email, :name, :gender, :set_milestone, :measures, :password
def initialize(email, name, gender, set_milestone, password, measures)
@email = email
@name = name
@gender = gender
@set_milestone= set_miles... |
# Right now if we have only one student, the user will see a message "Now we have 1 students",
# whereas it should be "Now we have 1 student". How can you fix it so that it used singular form
# when appropriate and plural form otherwise?
def input_students
puts "Please enter the names of the students"
puts "... |
require 'rails_helper'
feature 'As a logged in user' do
context 'when visiting a tutorial show page' do
before :each do
@user = create(:user)
@tutorial = create(:tutorial)
@tutorial2 = create(:tutorial)
@video1 = create(:video, tutorial_id: @tutorial.id)
@video2 = create(:video, tut... |
class AddFieldsToMachines < ActiveRecord::Migration
def change
add_column :machines, :print_time, :float, default: 0
add_column :machines, :seal_time, :float, default: 0
add_column :machines, :terminal_time, :float, default: 0
add_column :machines, :wire_time, :float, default: 0
add_column :machin... |
# coding: utf-8
require 'active_support/time'
require "ja_number"
class Horai
NORMALIZE_FROM = '0-9a-zA-Z:'
NORMALIZE_TO = '0-9a-zA-Z:'
DATE_DELIMITER = (/[\/-]/)
TIME_DELIMITER = (/[:]/)
AFTERNOON_PATTERN = (/午後|ごご|夜|よる|(?<![a-z])pm(?![a-z])/i)
RELATIVE_KEYWORDS_PATTERN = (/(?<![明午])後(?![年月日])|(?:[経た... |
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
require 'digest/md5'
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionControll... |
class RcControlsViewController < UITableViewController
DISPLAY_CELL_ID = "DisplayCellID"
SOURCE_CELL_ID = "SourceCellID"
VIEW_TAG = 1
def viewDidLoad
super
self.title = "Controls"
@data_source_array = [
{
:title => "UISwitch", :label => "Standard Switch",
:source => "rc_controls_view_co... |
# coding: utf-8
require_relative "lib/en_masse/version"
Gem::Specification.new do |spec|
spec.name = "en_masse"
spec.version = EnMasse::VERSION
spec.authors = ["Artem Baguinski"]
spec.email = ["abaguinski@depraktijkindex.nl"]
spec.summary = %q{Operations on arrays of activ... |
class CreateConsultations < ActiveRecord::Migration
def self.up
create_table :consultations do |t|
t.string :bpsu_number
t.date :consulted_date
t.string :current_state
t.string :traveled_recently
t.string :notification
t.date :notification_date
t.boolean :notification_dat... |
class Watchlist < ActiveRecord::Base
attr_accessible :user_id, :series_id
validates_uniqueness_of :series_id, scope: :user_id
belongs_to :user
belongs_to :series
has_many :episodes, through: :series
end
|
$:.push File.expand_path('../lib', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'knife-node-attribute'
gem.version = '0.2.0'
gem.authors = ["Daniel Schauenberg"]
gem.email = 'd@unwiredcouch.com'
gem.homepage = 'https://github.com/mrtazz/knife-node-attribute'
gem.su... |
class User < ApplicationRecord
validates :line_id, presence: true
has_many :items
end
|
FactoryBot.define do
trait :supply_teachers_direct_provision do
lot_number { 1 }
end
trait :supply_teachers_master_vendor do
lot_number { 2 }
end
trait :supply_teachers_neutral_vendor do
lot_number { 3 }
end
factory :supply_teachers_rate, aliases: [:direct_provision_rate], class: SupplyTeac... |
module GemBench
class StrictVersionGem
attr_reader :name
attr_reader :version
attr_reader :version_type
attr_reader :valid
attr_reader :relevant_lines
attr_reader :index
attr_reader :tokenized_line
class << self
def from_line(all_lines, line, index, opts = {})
tokenized_... |
module Upload
#
# the base path of all images this library operates on
#
ImagesRootBase = "#{RAILS_ROOT}/public"
#
# Wraps around an external image resizing library
# supports image resizing for now
#
class PreviewGenerator
class << self
#
# resizes image in... |
Jeesi::Application.routes.draw do
root :to => "homepage#home"
resources :comments
resources :requests
resources :categories
get "homepage/home"
get "homepage/about"
devise_for :users
end
|
require 'test_helper'
module KanbanCard
class TaskTest < ActiveSupport::TestCase
def setup
@task2 = Task.create(name: 'Test', description: 'Test description', finishing_date: Date.today)
@task = Task.new
end
def teardown
Task.destroy_all
end
#validations
test "task must not ... |
class Answer < ApplicationRecord
belongs_to :question
validates :name,presence:true
validates :content,presence:true
end
|
# frozen_string_literal: true
module SFRest
# SF Group management
class Group
# @param [SFRest::Connection] conn
def initialize(conn)
@conn = conn
end
# Creates a site group with specified group name.
# This currently will only create a group in the root
# @param [String] groupname N... |
class BaritoAppPolicy < ApplicationPolicy
def create?
return true if is_barito_superadmin?
return false if record.app_group.nil?
record.app_group.app_group_users.
joins(:role).
where(user: user, app_group_roles: { name: %i(admin owner) }).
count.positive?
end
def delete?
create?... |
require 'awestruct/engine'
require 'awestruct/site'
require 'awestruct/page_loader'
require 'awestruct/config'
describe Awestruct::PageLoader do
before :each do
@opts = Awestruct::CLI::Options.new
@opts.source_dir = File.dirname(__FILE__) + '/test-data/page-loader'
@config = Awestruct::Config.new( @opts... |
# frozen_string_literal: true
require "spec_helper"
describe "Edit opinions", type: :system do
include_context "with a component"
let(:manifest_name) { "opinions" }
let!(:user) { create :user, :confirmed, organization: participatory_process.organization }
let!(:another_user) { create :user, :confirmed, organ... |
class User < ApplicationRecord
has_secure_password
has_many :orders
has_many :purchaseditems, through: :order
end
|
class AddTenantReffToRentPayments < ActiveRecord::Migration
def change
add_reference :rent_payments, :tenant, index: true
end
end
|
require 'spec_helper'
describe 'Home' do
def current_user
@auth.user
end
it "should show home page" do
visit '/'
page.should_not have_link("New Board")
end
describe "first login" do
it "should see home page" do
visit "/auth/google"
page.should have_content("Home")
end
... |
module Eel
module ActiveRecord
module QueryExtensions
def order *args
return self if args.blank?
super *args.flatten.map { |a| assign_context(a); a }
end
def reorder *args
return self if args.blank?
super *args.flatten.map { |a| assign_context(a); a }
end
... |
require 'rails_helper'
DUMB_PASSWORD = 'lsdjflksdjfsd'
DUMB_EMAIL = 'woahbam@sdlfdsf.com'
RSpec.describe PlayingCard, type: :model do
before(:each) do
@player = User.create(email: DUMB_EMAIL, password: DUMB_PASSWORD)
@card = PlayingCard.build_from_template(Settings.card_templates.attack.to_h)
@game = Ga... |
start = Time.now
input = File.readlines("input", chomp: true)
.map{ |l| l.split('') }
input = {
0 => {
0 => input.map.with_index{ |xs,x|
[ x, xs.map.with_index{ |x,i| [i,x] }.to_h ]
}.to_h
}
}
puts "Prep: #{Time.now - start}s"
INACTIVE = '.'
ACTIVE = '#'
class Grid
attr_reader :grid
def i... |
# Model : Battle
class Battle < ApplicationRecord
has_and_belongs_to_many :ninjas
validates :winner, presence: true, numericality: { only_integer: true }
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Group, type: :model do
describe 'associations' do
it { is_expected.to have_many(:group_squads) }
it { is_expected.to have_many(:users).through(:group_squads) }
end
end
|
module QML
# {Application} represents a Qt application instance.
# It provides the event loop and manages Application-level configurations.
#
# @see http://qt-project.org/doc/qt-5/qapplication.html QApplication (C++)
class Application
# @return [Engine] The engine of the application.
def engine
... |
class ConsumersController < ApplicationController
before_action :authorize!, only: [:create, :update, :show]
def create
@sp = ServiceProvider.includes(:users).find_by(id: params[:service_provider_id], users: { id: current_user.id })
@sp.consumers.create!(name: params[:name], owner: current_user)
redire... |
# Teskal
#
class VersionsController < ApplicationController
layout 'base'
before_filter :find_project, :authorize
def edit
if request.post? and @version.update_attributes(params[:version])
flash[:notice] = l(:notice_successful_update)
redirect_to :controller => 'projects', :action =>... |
class Push < ApplicationRecord
has_many :commits, as: :commitable
has_one :repository, as: :repositable
belongs_to :pusher
end
|
require 'spec_helper'
describe "movies/show" do
before(:each) do
@movie = assign(:movie, stub_model(Movie,
:user => nil,
:imdb => "Imdb",
:media => "Media",
:media_info => "Media Info",
:seen => "Seen"
))
end
it "renders attributes in <p>" do
render
# Run the genera... |
class AddTaxEnabledToFinanceFeeCollections < ActiveRecord::Migration
def self.up
add_column :finance_fee_collections, :tax_enabled, :boolean, :default => false
end
def self.down
remove_column :finance_fee_collections, :tax_enabled
end
end
|
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@movies = @user.movies.includes(:user).order("updated_at DESC")
@movieForPage = @movies.page(params[:page]).per(10)
end
end
|
class AddAncestryToCheffs < ActiveRecord::Migration
def change
add_column :cheffs, :ancestry, :string
add_index :cheffs, :ancestry
end
end
|
class DelayedMailerReminderJob < Struct.new(:user, :campaign)
def perform
@user = User.find(user.id)
@campaign = Campaign.find(campaign.id)
UserMailer.deliver_managers_meeting_reminder(@user, @campaign, employees_without_meetings(@user, @campaign))
end
protected
def employees_without_meeting... |
module MediaDropboxItem
extend ActiveSupport::Concern
URLS = [
/^https?:\/\/(www\.)?dropbox\.com\/sh?\/([^\/]+)/,
/^https?:\/\/(dl\.)?dropboxusercontent\.com\/s\/([^\/]+)/
]
included do
Media.declare('dropbox_item', URLS)
end
def data_from_dropbox_item
handle_exceptions(self, StandardErro... |
module SDC
# Basic attributes
@window = nil
@scene = nil
@next_scene = nil
@game = nil
@limiter = nil
@text_input = nil
@draw_width = nil
@draw_height = nil
# Short expression to create a new {SDC::Coordinates} objects
def self.xy(x = 0.0, y = 0.0)
return Coordinates.new(x, y)
end
def self.window
... |
class Assignment < ActiveRecord::Base
belongs_to :volunteer
belongs_to :event
end
|
require "test_helper"
describe RatingPeriod do
before do
@tournament = create(:tournament)
end
describe "#previous_rating_period" do
before do
@period1 = create(:rating_period, :tournament => @tournament, :period_at => Time.new(2010))
@period2 = create(:rating_period, :tournament => @tournam... |
require 'mavenlink'
require_relative '../spec_helper'
describe Mavenlink do
before do
@cl = Mavenlink::Client.new("999")
end
describe "expenses" do
use_vcr_cassette "expenses", :record => :new_episodes
it "save an existing expense" do
exp = @cl.expenses({:workspace_id => 3457635, :order => "... |
start = Time.now
input = File.readlines("input", chomp: true)
.map{ |l| l.split.map{ |c| c.match(/[-\d]+/) ? c.to_i : c } }
puts "Prep: #{Time.now - start}s"
def run_bf(program, input)
digits = input.clone
mem = {'w'=>0,'x'=>0,'y'=>0,'z'=>0}
program.each do |op,a,b|
b = mem[b] unless b.is_a?(Integer)
... |
require File.dirname(__FILE__) + '/../spec_helper'
describe Question do
it "should require question text, an answer, and a difficulty" do
Question.should validate_presence_of :ask
Question.should validate_presence_of :answer
Question.should validate_presence_of :difficulty
q = Factory.build(:que... |
require 'dxruby'
class TimeManager
attr_accessor :life
attr_accessor :score
attr_accessor :time
def initialize(time = 20, margin_y = 0)
@start_time = time
@time = @start_time
@margin_y = margin_y
@font = Font.new(32)
@loop_count = 0
end
def clean
@loop_count = 0
@time = @start_ti... |
class BrigadeProject < ActiveRecord::Base
belongs_to :brigade
has_many :brigade_projects_tags
has_many :brigade_projects_users
has_many :tags, through: :brigade_projects_tags
has_many :users, through: :brigade_projects_users
validates :title, presence: true
validates :brigade_id, presence: true
def sel... |
class AddIsMultiSubmitableToForm < ActiveRecord::Migration
def self.up
add_column :forms, :is_multi_submitable, :boolean, :default => false
end
def self.down
remove_column :forms, :is_multi_submitable
end
end
|
require 'yaml_to_env'
describe YamlToEnv do
context 'flat yaml' do
it 'should return collection of env var settings' do
flat_yaml = <<END
---
key1: foo
key2: moo
key3: zoo
END
output = YamlToEnv.new.yaml_to_env flat_yaml
expect(output).to eq <<END
export key1=foo
export key2=moo
export key3... |
class PlayerSerializer < ActiveModel::Serializer
attributes :id, :name, :height, :weight, :image_url, :team_id
has_one :team
end
|
class AddAdviceHoursToUser < ActiveRecord::Migration
def change
add_column :users, :advice_hours, :decimal, precision: 5, scale: 2
end
end
|
class Category < ApplicationRecord
has_many :items
has_many :category_sizes
has_many :sizes, through: :category_sizes
has_ancestry
def find_items
if self.root?
first_id = self.indirects.first.id
last_id = self.indirects.last.id
items = Item.where(category_id: first_id..last_id)
elsi... |
# frozen_string_literal: true
class Ability
include CanCan::Ability
def initialize(user)
case user
when nil
apply_anonymous_permissions
when Visitor
apply_visitor_permissions(user)
when Admin
apply_admin_permissions(user)
end
end
def apply_anonymous_permissions
can [... |
class PresentToIsPresent < ActiveRecord::Migration[6.0]
def change
rename_column :students, :present, :is_present
end
end
|
module MatchesHelper
def pretty_score(match)
local_team_points = match.local_team_points || 0
visiting_team_points = match.visiting_team_points || 0
"#{local_team_points} - #{visiting_team_points}"
end
def pretty_date_time(datetime)
if datetime
datetime.strftime("%d/%m/%Y at %I:%M%p")
... |
# frozen_string_literal: true
require 'statistic_calcs/chi_square_contrast/goodness_and_fit'
require 'statistic_calcs/distributions/gumbel_minimum'
require 'statistic_calcs/helpers/math'
module StatisticCalcs
module ChiSquareContrast
class GumbelMinimumGoodnessAndFit < GumbelMaximumGoodnessAndFit
# mean-E... |
class AddDefaultValueToPassAttribute < ActiveRecord::Migration
def change
change_column :quastions, :pass, :boolean, :default => nil
end
end
|
#!/usr/bin/env ruby
require 'optparse'
require 'pp'
require 'base64'
# Parse command line options
def parseOpts(args)
# Default options
options = {:verbose => false}
OptionParser.new do |opts|
opts.banner = "Usage: autopsy.rb [options]"
opts.separator ""
... |
class EARMMS::GroupEditController < EARMMS::ApplicationController
helpers EARMMS::GroupHelpers
get '/:id' do |cid|
next halt 404 unless logged_in?
@user = current_user
@profile = EARMMS::Profile.for_user(@user)
next halt 404 unless cid
@group = EARMMS::Group[cid]
next halt 404 unless @gro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.