text stringlengths 10 2.61M |
|---|
desc 'check code with brakeman'
task :brakeman do
require 'brakeman'
result = Brakeman.run app_path: '.', print_report: true
exit Brakeman::Warnings_FoundExit_Code unless result.filtered_warnings.empty?
end
|
# @param {Integer} amount
# @param {Integer[]} coins
# @return {Integer}
def change(amount, coins)
return 1 if amount == 0
dp = Array.new(coins.size + 1) { Array.new(amount + 1)}
for i in (0..(coins.size)) do
dp[i][0] = 1
end
for j in (1..amount) do
dp[0][j] = 0
end
p dp
for i in (1..coins.... |
class UnformattedHtml < Exception; end
class DocumentNotFound < Exception; end
class ScraperNotFound < Exception; end
module Myimdb
module HandleExceptions
EXCEPTIONS_ENABLED = true
def self.included(base)
base.send(:include, InstanceMethods)
base.send(:extend, ClassMethods)
end
module... |
describe 'Extraction au format :html' do
# Méthode principale pour construire le div qui contient
# un label et une valeur
def div_libval label, valeur
"<div class=\"libval\"><span class=\"label\">#{label}</span><span class=\"value\">#{valeur}</span></div>"
end
before(:all) do
@collecte = Collecte.n... |
require "socket"
module Osc
class Client
def initialize(host, port)
@udp = UDPSocket.new
@udp.connect(host, port)
end
def send(address, messages)
osc_message = Osc::Message.new(address, messages)
@udp.send(osc_message.encode, 0)
end
end
end |
class LikesController < ApplicationController
before_action :find_post
def create
if already_liked?
flash[:notice] = "You can't like more than once"
else
@post.likes.create(user_id: current_user.id)
end
redirect_to posts_path
end
private
def find_post
@po... |
desc "Upload release notes"
lane :upload_release_notes do
deliver(
app_identifier: "com.example.MyApp",
app_version: get_version_number(target: "MyApp"),
force: true,
skip_binary_upload: true,
skip_screenshots: true,
metadata_path: "fastlane/metadata",
)
end
|
require 'spec_helper'
describe 'Comments SO' do
let(:user) { FactoryGirl.create(:user) }
let(:image) { FactoryGirl.create :user_image, user: user }
let(:parameters) do
{
user_id: user.id,
user_image_id: image.id,
content: 'test'
}
end
describe 'parent valid' do
let!(:comment) {... |
class ShortenedUrl < ActiveRecord::Base
include SecureRandom
validates :long_url, presence: true, uniqueness: true
validates :short_url, presence: true, uniqueness: true
validates :user_id, presence: true
has_many(
:visitors,
primary_key: :short_url,
foreign_key: :short_url,
class_name: :Vis... |
require 'test_helper'
module Radiator
class NetworkBroadcastApiTest < Radiator::Test
def setup
@api = Radiator::NetworkBroadcastApi.new
end
def test_method_missing
assert_raises NoMethodError do
@api.bogus
end
end
def test_all_respond_to
@api.method_names.each do... |
#ピタゴラスの三つ組(ピタゴラスの定理を満たす自然数)とはa<b<cで
#a² + b² = c²
#を満たす数の組である.
#
#例えば, 3² + 4² = 9 + 16 = 25 = 5²である.
#a + b + c = 1000となるピタゴラスの
#三つ組が一つだけ存在する. このa,b,cの積を計算しなさい.
class PitagorasCalculator
def initialize(side_sum)
@side_sum = side_sum
calc
end
def print_answer
# p "a(#{@a}) + b(#{@b}) + c(#{@c}) = 1... |
module ThreeScale
module Backend
module OAuth
class Token
module Storage
include Configurable
# Default token size is 4K - 512 (to allow for some metadata)
MAXIMUM_TOKEN_SIZE = configuration.oauth.max_token_size || 3584
private_constant :MAXIMUM_TOKEN_SIZE
... |
class Genre < ApplicationRecord
has_many :artists
end
|
class Video < ActiveRecord::Base
acts_as_decorables
has_many :video_users
has_many :users, through: :video_users
def how_many_times_seen_by(user)
VideoUser.where(video_id: id, user_id: user.id).first.try(:views) || 0
end
end
|
require 'rails_helper'
RSpec.describe ConsultantExamInvitationsController, type: :controller do
describe "get #create" do
let(:user) { create(:user, aasm_state: 'not_invited_to_exam') }
let(:consultant) { create :consultant }
let(:superadmin) { create :superadmin }
it "should not let users in... |
class FieldDefinition
include Mongoid::Document
include Mongoid::Attributes::Dynamic
field :name, type: String
field :label, type: String
field :field_type, type: String
embedded_in :model_definition, inverse_of: :field_definitions
end
|
class Courses < ActiveRecord::Migration[5.2]
def change
create_table :courses do |t|
t.integer :category_id, null: false, :limit => 8, index: true
t.integer :creator_id, null: false, :limit => 8, index: true
t.string :title, index: true, null: false
t.string :description, null: false
... |
# frozen_string_literal: true
# rubocop:disable Style/Documentation
class ApplicationController < ActionController::API
before_action :check_mime_type
before_action :check_data_type
before_action :check_user_authentication
private
def check_mime_type
return unless %w[POST PUT PATCH].include? request.me... |
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :authenticate_user!
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:account_update, keys: [:role, :department, :name])
end
def must... |
# The MIT License (MIT)
# Copyright (c) 2013 alisdair sullivan <alisdairsullivan@yahoo.ca>
# 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 ... |
Pod::Spec.new do |s|
s.name = 'YHPhotoBrowser'
s.version = '1.0.1'
s.summary = '类似于qq,微信,微博的图片浏览器:9宫格的图片,点击任何一张放大至全屏,并可以左右滑动查看所有图片.简易框架,易懂.'
s.homepage = 'https://github.com/RusselYHCui/YHPhotoBrowser'
s.license = 'MIT'
s.author = { 'Russel_yh_Cui' => '960743995@qq.com' }
s.pl... |
require 'test_helper'
class TableTest < ActiveSupport::TestCase
setup do
@restaurant = create(:restaurant)
end
test 'validate name and table capacity' do
table = build(:table, restaurant: @restaurant)
table.name = nil
assert_not table.valid?
assert_equal "can't be blank", table.errors[:name... |
object @board_pic
attributes :id, :class_date, :created_at
child :image => :image do
attributes :url, :size, :content_type
node :thumbnail_url do |img|
img.url(:thumb)
end
end
child :author => :author do
attributes :id, :name
end |
class Floor
attr_reader :dirty
def initialize
@dirty = true
end
def dirty?
if dirty == false
puts "The floor should be clean."
else
puts "The floor should be dirty."
end
dirty
end
def wash
@dirty = false
end
end
|
class SubjectsPublication < ActiveRecord::Base
belongs_to :publication
belongs_to :subject
# attr_accessible :publication_id, :subject_id
validates_uniqueness_of :publication_id, :scope => :subject_id
end
|
require "spec_helper"
describe PowerAPI::Data::Student do
include Savon::SpecHelper
before(:all) {
savon.mock!
@session = {:locale=>nil, :server_current_time=>"2014-08-24T03:01:25.007Z", :server_info=>{:api_version=>"2.1.1", :day_light_savings=>"0", :parent_saml_end_point=>nil, :raw_offset=>"-14400000", ... |
# frozen_string_literal: true
class CreateCinemas < ActiveRecord::Migration[6.1]
def change
create_table :cinemas do |t|
t.integer :cinema_number
t.integer :total_seats
t.integer :columns
t.integer :rows
t.timestamps
end
add_index :cinemas, :cinema_number, unique: true
end... |
require 'yt/models/resource'
module Yt
module Models
# Provides methods to interact with YouTube playlists.
# @see https://developers.google.com/youtube/v3/docs/playlists
class Playlist < Resource
### SNIPPET ###
# @!attribute [r] title
# @return [String] the playlist’s title.
d... |
# encoding: utf-8
class ImageUploader < CarrierWave::Uploader::Base
# リサイズしたり画像形式を変更するのに必要
include CarrierWave::RMagick
# 画像の上限を700pxにする
process :resize_to_limit => [700, 700]
# 保存形式をJPGにする
process :convert => 'jpg'
# サムネイルを生成する設定
version :thumb do
process :resize_to_limit => [73, 73]
end
... |
require 'minitest/spec'
require 'minitest/autorun'
require File.expand_path(File.join('..', 'lib/parser.rb'), File.dirname(__FILE__))
require File.expand_path(File.join('..', 'lib/pbxproj_nodes.rb'), File.dirname(__FILE__))
class PbxMerge
attr_accessor :merged, :conflicts
def initialize(lists)
@merged = []... |
# -*- coding : utf-8 -*-
require 'spec_helper'
describe Mushikago::Hanamgri::GetAnalysisRequest do
context '.new("domain_name", "request_id")' do
subject{ Mushikago::Hanamgri::GetAnalysisRequest.new('domain_name', 'request_id')}
it{ should be_kind_of(Mushikago::Http::GetRequest)}
its(:domain_name){ shoul... |
class Changetodefault < ActiveRecord::Migration
def change
change_column :students, :name, :string, :default => "hello"
end
end
|
class Api::V1::AssessmentsController < ApplicationController
def index
@assessments = Assessment.all
render json: @assessments
end
# POST /assessments
def create
@assessment = Assessment.new(assessment_params)
if @assessment.save
render json: @assessment, status: :created
... |
# frozen_string_literal: true
require 'dry/validation'
module Contract
# Create Foo Contract
class CreateFoo < Dry::Validation::Contract
params do
required(:name).filled(:string)
end
end
end
|
##
# 짝지어 제거하기
# 문제 설명
# 짝지어 제거하기는, 알파벳 소문자로 이루어진 문자열을 가지고 시작합니다. 먼저 문자열에서 같은 알파벳이 2개 붙어 있는 짝을 찾습니다. 그다음, 그 둘을 제거한 뒤, 앞뒤로 문자열을 이어 붙입니다. 이 과정을 반복해서 문자열을 모두 제거한다면 짝지어 제거하기가 종료됩니다. 문자열 S가 주어졌을 때, 짝지어 제거하기를 성공적으로 수행할 수 있는지 반환하는 함수를 완성해 주세요. 성공적으로 수행할 수 있으면 1을, 아닐 경우 0을 리턴해주면 됩니다.
#
# 예를 들어, 문자열 S = baabaa 라면
#
# b aa baa → ... |
class BuildingController < ApplicationController
get '/new' do
signed_in_user
@title = t('create_record')
@post = Building.new
slim :'buildings/new'
end
get '' do
@title = t('building')
@buildings = Building.all.paginate(per_page: 10, page: params[:page])
slim :'buildings/index'
en... |
# TODO
# more specs for fragment caching:
# cache_get, cache_set, cached?, cache, expire
describe "merb-cache-fragment" do
it "should render index" do
c = dispatch_to(CacheController, :index)
c.body.should == "test index"
end
it "should cache the fragment (erb capture/concat)" do
c = dispatch_to(Ca... |
class CreateCandidatures < ActiveRecord::Migration[5.0]
def change
create_table :candidatures do |t|
t.references :gig, foreign_key: true
t.references :volunteer, foreign_key: true
t.boolean :accepted
t.text :introduction_letter
t.timestamps
end
end
end
|
# frozen_string_literal: true
# Handles application request
class ApplicationController < ActionController::API
def authorize_entity
if decoded_auth_token
@entity = if decoded_auth_token[:entity] == 'User'
User.find(decoded_auth_token[:auth_entity_id])
else
... |
class AddSearchIdToLists < ActiveRecord::Migration[5.2]
def change
add_column :lists, :search_id, :string
end
end
|
require 'rails_helper'
RSpec.describe Admin::LetterConversationsController, type: :controller do
render_views
let(:resource_class) { LetterConversation }
let(:all_resources) { ActiveAdmin.application.namespaces[:admin].resources }
let(:resource) { all_resources[resource_class] }
let(:page) { Capybara... |
$evm.log("info", "********* my_validate_tag - GetIP STARTED *********")
begin
@method = 'my_validate_tag'
$evm.log("info", "===== EVM Automate Method: <#{@method}> Started")
# Turn of debugging
@debug = true
# Log the inbound object
$evm.log("info", "===========================================")
proces... |
require File.expand_path(File.dirname(__FILE__) + '/page_object')
class ApiPage < PageObject
def initialize(page)
super(page)
@url_base = '/api/'
end
def visit_subscriptions(person, type = nil)
if person.respond_to?(:id)
id = person.id
else
id = person.to_i
end
if type.nil?... |
class Expense < ActiveRecord::Base
STATUSES = %w(Pending Approved Rejected)
belongs_to :user
belongs_to :category
has_one :expense_job_title_assignment
has_one :job_title_assignment, through: :expense_job_title_assignment, class_name: JobTitleAssignment
validates :user, :date, :category, :description, :amo... |
require 'leaderboard'
class TieRankingLeaderboard < Leaderboard
# Default options when creating a leaderboard. Page size is 25 and reverse
# is set to false, meaning various methods will return results in
# highest-to-lowest order.
DEFAULT_OPTIONS = {
:page_size => DEFAULT_PAGE_SIZE,
:reverse => false,... |
# frozen_string_literal: true
class TagPolicy < ApplicationPolicy
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
if user.global_role?
scope.all
else
scope.where(organization_id: user.membership_or... |
class SelectionSimulation
NUM_TO_ROUND = 5
#run this as a concurrent set of user's from the 'concurrent_selection_simulation.sh' script
def initialize(user_offset)
@retire_num = 3
# @active_user_set = User.limit(10).offset(user_offset).map(&:id)
@active_user_set = (1..10).to_a.map { |n| user_offset ... |
class Like < ApplicationRecord
belongs_to :speak , optional: true
belongs_to :st_user , optional: true
belongs_to :ad_user , optional: true
counter_culture :speak
validates :ad_user_or_st_user, presence: true
validates :speak_id, presence: true
def ad_user_or_st_user
ad_user_id.presence or s... |
require 'minitest/autorun'
require 'rubygems'
require 'bundler/setup'
require 'pry'
require 'mocha/mini_test'
require "net/http"
require 'sqlite3'
require File.join(__dir__, '..', '..', 'app', 'models', 'user')
require File.join(__dir__, '..', '..', 'app', 'models', 'user_Submission')
require File.join(__dir__, '..',... |
Rails.application.routes.draw do
#get 'welcome/index'
devise_for :users
#root :to => 'posts#index'
resources :posts
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
# the followed are routes for the user_controller
get "all_users", to: "users#all_users... |
class AddAgreementAndInstitutionalProgramsToAll < ActiveRecord::Migration
def change
add_column :activities, :agreement_id, :integer
add_column :article_referees, :agreement_id, :integer
add_column :awards, :agreement_id, :integer
add_column :books, :agreement_id, :integer
add_column :conference_a... |
FactoryGirl.define do
factory :tag do
name "test"
user
factory :invalid_tag do
name nil
user
end
factory :tag_with_contacts do
transient do
contacts_count 2
end
after(:create) do |tag, evaluator|
create_list(:contact, evaluator.contacts... |
class AddIndexesToUserNoticePhotoDocument < ActiveRecord::Migration
def change
add_column :documents, :notice_id, :integer
add_index :documents, :notice_id
add_column :photos, :notice_id, :integer
add_index :photos, :notice_id
add_column :notices, :project_id, :integer
add_index :notices, :p... |
# frozen_string_literal: true
require 'test_helper'
class StringTemplateTest < Minitest::Test
def setup
@view = if ActionView::VERSION::MAJOR >= 6
Class.new(ActionView::Base.with_empty_template_cache).with_view_paths([__dir__])
else
Class.new(ActionView::Base).new(ActionView::LookupContext.new(_... |
class SessionsController < ApplicationController
skip_before_filter :check_authentication
def new
@title = "login"
end
def create
begin
@request_path = session[:request_path]
reset_session
@session_user = SimpleUser.authenticate(params[:primary_email], params[:password])
... |
# encoding: utf-8
require 'net/http'
require 'uri'
class Exploit_3 < Playload::Issue
def initialize
@name = "Discuz7.2 SQL"
@type = "discuz"
@tags = "discuz"
@description = %q{Discuz7.2 faq.php Sql Exp: /bbs/faq.php?action=grouppermission&gids[99]=%27&gids[100][0]=%29%20and%2... |
class Tagging < ApplicationRecord
belongs_to :book
belongs_to :tag
end
|
# @param {Integer[]} nums
# @return {Boolean}
def contains_duplicate(nums)
hash_nums = {}
nums.each do |element|
if hash_nums.has_key?(element)
return true
else
hash_nums[element] = 1
end
end
return false
end
|
# 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 bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# ... |
#!/usr/bin/ruby -w
#
# Test etch's handling of creating and updating the original (orig) and
# history files
#
require File.expand_path('etchtest', File.dirname(__FILE__))
class EtchHistoryTests < Test::Unit::TestCase
include EtchTests
def setup
# Generate a file to use as our etch target/destination
@t... |
House::Application.routes.draw do
#root
root 'mixes#index'
# Routes for the Mix resource:
# CREATE
get '/mixes/new', controller: 'mixes', action: 'new', as: 'new_mix'
post '/mixes', controller: 'mixes', action: 'create', as: 'mixes'
# READ
get '/mixes', controller: 'mixes', action: 'index'
get '/mix... |
class Expense < ApplicationRecord
has_one :expensetype
end
|
class CreateProductCategories < ActiveRecord::Migration
def up
create_table "product_categories" do |t|
t.string "title"
t.integer "list_order", :default => 999
t.datetime "created_at"
t.datetime "updated_at"
t.integer "parent_id"
t.integer "sale_id"
end
add_index... |
class Record < ApplicationRecord
belongs_to :zone
validates :name, presence: true
end
|
require 'support/models_shared_examples'
RSpec.describe User, type: :model do
let(:valid_user) { build(:user) }
let(:unique_user) { build(:user, :unique_user) }
let(:required) { "を入力してください。" }
let(:required_and_invalid_params) { "を入力してください。" ", " "は不正な値です。" }
let(:too_long_name) { "は128文字以内で入力してください。" }
l... |
require 'rails_helper'
RSpec.describe Order, :type => :model do
let(:order) { create :order }
let(:item) { create :item}
let(:address) do
Address.new(order_id: 1, street_1: "123 Washington St", city: "Denver", state: "CO", zip: "80202")
end
it "belongs to one user" do
user = User.new
order.use... |
require 'rest-client'
class CloudPlatformController < ApplicationController
before_action :authenticate_user!, :except => [:dataset]
def index
end
def delete
ids = params[:id].split("-")
Instance.delete(ids)
ids.each do |id|
filename = Rails.root.join("storage/"+id.to_... |
# == Schema Information
#
# Table name: jobs
#
# id :integer not null, primary key
# client_id :integer
# data_destruction :string(255)
# no_items :integer default(0)
# collection_date :date
# priority ... |
require 'active_record'
require 'rspec'
require_relative '../app/models/person'
database_configuration = YAML::load(File.open('config/database.yml'))
configuration = database_configuration['test']
ActiveRecord::Base.establish_connection(configuration)
describe Person do
it "should validate the presence of a first ... |
class AddCustomerRefPayment < ActiveRecord::Migration[5.2]
def change
add_reference :payments, :customer, index: true
add_foreign_key :payments, :customers
end
end
|
require 'spec_helper'
describe Puppet::Type.type(:system_attributes) do
# Modify params inline to tests to change the resource
# before it is generated
let(:params) do
{
:name => "/tmp/foo",
:ensure => :present,
}
end
# Modify the resource inline to tests when you modeling the
# b... |
#!/usr/bin/env ruby
# encoding: utf-8
# File: update.rb
# Created: 19/03/12
#
# (c) Michel Demazure <michel@demazure.com>
require_relative '../../jaccess.rb'
require_relative 'build_structure_tables.rb'
require_relative 'build_extended_tables.rb'
module JacintheReports
# methods for building the association and fi... |
# Variables d'application
set :application, "puppet"
set :repository, "https://github.com/bashou/puppet.git"
set :deploy_to, "/root/#{application}"
set :shared_children, []
set :normalize_asset_timestamps, false
set :scm, :git
set :scm_verbose, true
set :deploy_via, :remote_cache
set :copy_exclude, [".git/*",".git... |
module Redcarpet
module Render
class Hiki < Base
def initialize(render_extensions)
super()
@header_offset = 0
if render_extensions[:header_offset]
@header_offset = render_extensions[:header_offset]
end
end
def normal_text(text)
text
end
... |
require_relative 'minesweeper'
require_relative 'constants'
require_relative 'cell'
require_relative 'board_printer'
#
# Classe para debugar o game
#
class Debug
def run()
puts "Hello! "
end
def assert_equal(expected, actual, message)
if !(expected == actual)
raise "Expected #{expected} but got #... |
require './lib/participant'
class Activity
attr_reader :name,
:participants
def initialize(activity)
@name = activity
@participants = []
end
def add_participant(info)
participant = Participant.new(info)
@participants << participant
end
def calculate_cost
costs = @par... |
class ReviewsController < ApplicationController
before_action :set_review, only: [:show, :edit, :update, :destroy]
before_action :can_manage, except: [:index, :show, :create]
before_action :authenticate_user!
respond_to :html, :js
def index
@reviews = Review.all
respond_with(@reviews)
end
def... |
require_relative './base'
module BandCampBX
module Entities
class Order < Base
class InvalidTypeError < StandardError; end
def self.map_type
->(val) do
case val.to_s
when 'Quick Sell'
:sell
when 'Quick Buy'
:buy
else
... |
Rails.application.routes.draw do
concern :api_base do
resources :sessions, only: [:create]
resources :registrations, only: [:create, :update, :destroy]
resources :products, param: :slug
resources :categories, param: :slug do
get :just_category, to: "categories#just_category"
end
resource... |
require_relative 'grid'
# a class called Game that controlls the game, changing the grid, etc.
class Game
attr_reader :grid
def initialize(grid = Grid.new)
@grid = grid
end
def tile_alive(coodinates)
@grid.tiles[coodinates[:x]][coodinates[:y]].birth
end
def prompt_for_coordinates
puts 'enter ... |
module Trustworthy
class Settings
def self.open(filename)
store = YAML::Store.new(filename)
store.ultra_safe = true if store.respond_to?(:ultra_safe=)
store.transaction do
yield Trustworthy::Settings.new(store)
end
end
def initialize(store)
@store = store
end
... |
class CategoriesController < ApplicationController
def show
# binding.pry
@category = Category.find_by(params[:id])
end
def index
@categories = Category.all
end
private
def category_params
params.require(:category).permit(:title)
end
end
|
require 'test_helper'
class PostsControllerTest < ActionDispatch::IntegrationTest
setup do
@post = posts(:one)
end
test "should get index" do
get posts_url
assert_response :success
end
test "should get new" do
get new_post_url
assert_response :success
end
test "should create post" ... |
require 'test_helper'
class PalletsControllerTest < ActionDispatch::IntegrationTest
setup do
@pallet = pallets(:one)
end
test "should get index" do
get pallets_url
assert_response :success
end
test "should get new" do
get new_pallet_url
assert_response :success
end
test "should cre... |
class Category < ActiveRecord::Base
has_many :categorizations
has_many :events, :through => :categorizations
has_many :taggings, :as => :taggable
has_many :tags, :through => :taggings
has_attached_file :image, :styles => { :small => "100x100#", :medium => "250x250#" }
validates :name, :uniqueness => tr... |
class Place < ApplicationRecord
has_and_belongs_to_many :itineraries
has_and_belongs_to_many :categories
end
|
require_relative 'test_helper'
require_relative '../lib/transaction_repository'
require_relative '../lib/transaction'
class TransactionRepositoryTest < Minitest::Test
def setup
@transaction_1 = Transaction.new({:id => 6, :invoice_id => 8, :credit_card_number => "4242424242421111", :credit_card_expiration_date =>... |
module PagesHelper
# Returns a hash of { date => num }. Puts chart data on a fixed axis to
# prevent weird scaling by filling in empty dates with a count of 0.
def daily_date_data(date_count_data, date_range)
Hash[date_range.map { |date| [date, 0] }].merge(date_count_data)
end
end
|
# Your Code Here
def map(array)
i = 0
while i < array.length
array[i] = yield(array[i])
i += 1
end
array
end
def reduce(array, starting_point = nil)
if starting_point
sum = starting_point
i = 0
else
sum = array[0]
i = 1
end
while i < array.length
sum = yield(sum, array[i... |
class Hash
def keys_of(*arguments)
#splat(*) captures whatever other arguments you pass into the method.
#the splat is required for when you're passing multiple keys
collect {|key,value| arguments.include?(value)? key:nil}.compact
#collect enumerator pulls and passes array
#the block compare... |
class AddEmailUniquenessIndex < ActiveRecord::Migration
def self.up
add_index :users, :mail, :unique => true
end
def self.down
remove_index :users, :mail
end
end
|
require 'spec_helper'
describe "personal_informations/edit" do
before(:each) do
@personal_information = assign(:personal_information, stub_model(PersonalInformation,
:Id_Number => ""
))
end
it "renders the edit personal_information form" do
render
# Run the generator again with the --webr... |
class RemoveGameIdFromUnit < ActiveRecord::Migration[5.1]
def change
remove_column :units, :game_id, :integer
end
end
|
require "spec_helper"
describe ResidencesController do
describe "routing" do
it "routes to #index" do
get("/residences").should route_to("residences#index")
end
it "routes to #new" do
get("/residences/new").should route_to("residences#new")
end
it "routes to #show" do
get("/r... |
class Shelf < ApplicationRecord
validates :user_id, presence: true
end
|
class AddImportedIdToGoals < ActiveRecord::Migration[5.1]
def change
add_column :goals, :imported_id, :bigint
end
end
|
class UserPolicy < ApplicationPolicy
def create?
user.admin?
end
def update?
user.admin? || is_self?
end
def destroy?
return false if is_guest?
user.admin? || is_self?
end
private
def is_self?
user == record
end
end
|
require 'test_helper'
class HistoricAssetsControllerTest < ActionController::TestCase
setup do
@historic_asset = historic_assets(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:historic_assets)
end
test "should get new" do
get :new
as... |
VAGRANTFILE_API_VERSION = "2"
name = "docker"
home = "/home/vagrant/project"
memory = "512"
cpu="2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "precise64"
config.vm.box_url = "http://files.vagrantup.com/precise64.box"
config.vm.provider "virtualbox" do |v|
v.name = name
v.... |
class CreateMediaFiles < ActiveRecord::Migration
def change
create_table :media_files do |t|
t.string :name
t.string :description
t.string :file
t.string :zencoder_output_id
t.boolean :processed
t.string :file
t.string :asset_type
t.integer :file_size
t.string... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.