text stringlengths 10 2.61M |
|---|
class FontBallet < Formula
head "https://github.com/google/fonts/raw/main/ofl/ballet/Ballet%5Bopsz%5D.ttf", verified: "github.com/google/fonts/"
desc "Ballet"
desc "Designed by maximiliano sproviero and developed by eduardo tunni"
homepage "https://fonts.google.com/specimen/Ballet"
def install
(share/"fon... |
# Simple bot emulator
class SimpleBot
UNEXPECTED_PHRASE = "don't knows this phrase".freeze
attr_reader :bot_name, :super_phrase
def initialize(bot_name, super_phrase)
@bot_name = bot_name
@super_phrase = super_phrase
@all_phrases = {}
end
def method_missing(method_name, *args)
# check if met... |
# frozen_string_literal: true
class GroupSerializer < BaseSerializer
attributes %i[id name]
end
|
class Account
include Mongoid::Document
embedded_in :store
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :authentic... |
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
include Bootsy::Container
end
|
require 'test_helper'
class VirtualRepositoriesControllerTest < ActionDispatch::IntegrationTest
setup do
log_in
@virtual_repository = FactoryBot.create(:virtual_repository, title: 'Books')
@repository = @virtual_repository.repository
end
test 'virtual repositories index' do
get virtual_reposito... |
module DjsHelper
#URI.parse
#if URI is blank return nil
#else return normalize! uri
def normalize_uri(uri)
return unless uri
if uri !~ /^http/
"http://#{uri}"
else
uri
end
end
end
|
class NewsRestructure < ActiveRecord::Migration
def change
remove_column :news, :published_date
remove_column :news, :caption
remove_column :news, :subj
remove_column :news, :body
add_column :news, :archived, :boolean
end
end
|
class CreateJersey < ActiveRecord::Migration[5.2]
def change
create_table :jerseys do |t|
t.string :user_name
t.string :password
t.string :mali
t.string :phone
t.string :no
end
end
end
|
require 'active_model'
require 'robot'
require 'board'
require 'colorable'
module ToyRobotSimulator
# Main application class for Toy Robot Simulator
class Simulator
include ActiveModel::Validations
include Colorable
DEFAULT_ROBOT = 'R1'
attr_reader :board, :robot, :permitted_commands, :usa... |
IMAGE_SETS = {
concert: 2,
festival: 2,
other: 6,
}.freeze
if Rails.env.production? && !ENV['force']
puts 'Seeding cannot be run in production!'
return
end
def get_time_zone country_code
case country_code
when 'US'
'America/New_York'
when 'GB'
'Europe/London'
end
end
def load_country name, ... |
class Api::V1::CapesController < ApiController
before_action :authenticate_user!, only: [:create, :update]
def index
render json: Cape.all
end
def show
render json: Cape.find(params["id"]), serializer: CapeSerializer
end
def create
cape = Cape.new(cape_params)
cape.user = current_user
... |
class PostsController < ApplicationController
before_action :authenticate_user!
before_action :find_membership, :find_group
def new
@post = @group.posts.new
end
def create
@post = @group.posts.new(post_params)
@post.membership = @group.memberships.find_by(user_id: current_user.id)
if @post.... |
class ItemsController < ApplicationController
def search
end
def index
fromtime = Date.strptime(params[:from_filter], '%Y/%m/%d')
leavetime = Date.strptime(params[:to_filter], '%Y/%m/%d').end_of_day
@items = Item.where("updated_at >= ? AND updated_at <= ?", fromtime, leavetime).where("done = ? OR m... |
require 'spec_helper'
require 'app/models/hound_config'
describe HoundConfig do
describe '#content' do
it 'returns the content of the .hound.yml file' do
commit = stubbed_commit(
'.hound.yml' => <<-EOS.strip_heredoc
ruby:
enabled: true
config_file: config/rubocop.y... |
require_relative 'simple_js_runnable.rb'
module PageHelper
module Utils
#
# Realiza o scroll da página para o início.
#
def scroll_to_top
js('window.scroll(0,0);')
end
#
# Aguarda o ajax retornar na pagina, mantendo
# um loop e não permitindo timeout.
#
def wait_ajax
... |
class CreateSmsClients < ActiveRecord::Migration
def change
create_table :sms_clients do |t|
t.integer :contact, limit: 10
t.string :message, limit: 100
t.timestamps null: false
end
end
end
|
class CurrencyNotSupportedError < StandardError; end
class Numeric
@@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019, 'dollar' => 1}
def method_missing(method_id)
singular_currency = method_id.to_s.gsub( /s$/, '')
if @@currencies.has_key?(singular_currency)
self * @@currencies[singular_cur... |
require 'pry'
class Owner
attr_accessor :pets, :name
attr_reader :species
@@all = []
def initialize(name)
@name = name
@pets = {fishes: [], dogs: [], cats: []}
@species = "human"
@@all << self
end
def self.all
@@all
end
def self.reset_all
@@all = []
end
de... |
module Redux
class Store
include Native::Wrapper
class << self
def add_middleware(middleware)
if Isomorfeus.store
`console.warning("Adding middleware after Store initialization may have side effects! Saving state and initializing new store with restored state!")`
middlewares... |
module XcodeInstaller
VERSION = '0.3.1'
class UnsuccessfulAuthenticationError < RuntimeError; end
end
|
# frozen_string_literal: true
module AuthenticatedSessionHelper
def use_authenticated_current_user(options = {})
current_user = options[:current_user] || build(:user)
expect_any_instance_of(ApplicationController)
.to receive(:authenticate_token).at_least(:once).and_return(:true)
expect_any_instanc... |
class CreateHousesStreets < ActiveRecord::Migration[6.0]
def change
create_table :houses_streets do |t|
t.references :houses
t.references :streets
t.timestamps
end
end
end
|
class CreateAgencies < ActiveRecord::Migration
def change
create_table :agencies do |t|
t.string :name
t.string :subdomain
t.string :address1
t.string :address2
t.string :city
t.string :parish
t.string :state
t.string :zip
t.string :... |
require 'rails_helper'
RSpec.describe User, type: :model do
subject(:user) { build(:user, :without_detail, confirmed_at: confirmed_at) }
describe '#confirmed?' do
context 'when confirmed_at blank' do
let(:confirmed_at) { nil }
it 'returns false' do
expect(user.confirmed?).to eq false
... |
class AddReferenceToAlert < ActiveRecord::Migration[5.1]
def change
add_reference :alerts, :user, foreign_key: true
end
end
|
class Question < ActiveRecord::Base
include Votable
default_scope { order ('created_at DESC') }
has_many :answers, dependent: :destroy
has_many :subscribes,dependent: :destroy
has_many :subscribed_users, through: :subscribes, source: :user
has_many :attachments, as: :attachable, dependent: :destroy
has_... |
class UserGroupsController < ApplicationController
lock_with_feature :user_groups_enhancement
before_filter :find_department_and_batch, :only => [:create_user_group, :add_member, :edit_user_group]
before_filter :find_group, :only => [:show_user_group, :destroy_user_group, :add_member, :edit_user_group]
before_... |
class Proof < ActiveRecord::Base
belongs_to :dhokebaaz
has_attached_file :content
do_not_validate_attachment_file_type :content
validates_presence_of :detail
end
|
# frozen_string_literal: true
require 'transmission_chaos/client'
require 'transmission_chaos/torrent'
require 'transmission_chaos/version'
autoload :Logging, 'logging'
module TransmissionChaos
class Error < StandardError; end
def self.debug!
logger.level = :debug
end
def self.logger
@logger ||= ::... |
require 'spec_helper'
require 'rails_helper'
describe 'issues index' do
before(:each) do
@user = User.create(name: "Test User", email: "Test@test.com", password: "testing")
@attr = {email: @user.email, name: @user.name }
end
it 'visits the issues index page' do
visit('/issues')
end
it 'should h... |
module Rdomino
class DocumentCollection
include DomObject, Enumerable, DcView, DxlExportable
delegate :query,:count, :to => :obj
alias_method :size, :count
def each
doc = @obj.getFirstDocument
while doc
next_doc = @obj.getNextDocument doc
d = Document.new doc, self
... |
class ContactController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(message_params)
if @contact.save
redirect_to thankyou_page_path
end
end
private
def message_params
params.required(:contact).permit(:first_name, :last_name, :emai... |
class TransferJob < ActiveJob::Base
queue_as :default
def perform(action, type, batch_name, key)
action_method = TransferJob.actions action
raise "Invalid remote action #{action}!" unless action_method
batch = Batch.where(
key: key
).first || Batch.new(
key: key,
category: 'trans... |
require "rails_helper"
describe RestaurantService do
let(:service) { RestaurantService.new }
let(:search_response) { {
"region" => {
"span" => {"latitude_delta" => 0.05088225999999452, "longitude_delta" => 0.026115099999998392},
"center" => {"latitude" => 40.031235300000006, "longitude"... |
json.array!(@logins) do |login|
json.extract! login, :id, :new, :edit, :create, :destroy
json.url login_url(login, format: :json)
end
|
module Reuters
module Wsdls
module Search
# The Equity Search WSDL endpoint is used by the
# {Reuters::Client::Search::Equity} class to discover
# and make search-based API calls.
module Equity
# @!parse include Base
include Base
# Wsdl for the TokenManagement en... |
class OrdersController < ApplicationController
def show
@order = Order.find(params[:id])
end
def create
price = 0
params[:order][:prescriptions][1..-1].each do |prescription_id|
price += Prescription.find(prescription_id).price_cents
end
order = Order.create!(total_cost_cents: price, stat... |
# Use tnyubot as a puppet }:)
#
# General format: say|do [channel] [message]
#
# @author wyattisimo
#
class Puppet
include Cinch::Plugin
match /^(say|do)\s+(.+)$/, :react_on => :private
def execute(m, action, what)
p = ConfigData.new :Puppet
if p.hash[:puppet_masters].include? m.user.user
... |
# Encoding: utf-8
Ohai.plugin(:Wordpress) do
depends 'webapps'
depends 'apache2'
provides 'webapps/wordpress'
def get_docroots
docroots = {}
unless apache2['vhosts'].empty?
# Build hash of docroots to iterate
apache2['vhosts'].each do |_vhost_name, vhost|
vhost.each do |site_name, ... |
class RenameDueDateToDue < ActiveRecord::Migration[4.2]
def self.up
add_column :deliverables, :due, :date
Deliverable.reset_column_information
Deliverable.all.each do |deliverable|
deliverable.update_attribute(:due, deliverable.due_date)
end
remove_column :deliverables, :due_d... |
require_relative "piece"
class Pawn < Piece
def symbol
"♟"
end
def move_dirs
[
[1,0], ## normal move
[-1,0],
[2, 0], ##start move?
[-2, 0],
[1,1], ##attacks
[-1,1],
[1,-1],
[-1,-1]
]
end
private
def at_start_ro... |
require "code"
describe Array do
describe "#my_uniq" do
subject(:array) { [1, 2, 1, 3, 3] }
it 'removes duplicates' do
expect(array.my_uniq).to eq([1,2,3])
end
it 'should not call #uniq' do
expect(array).to_not receive(:uniq)
end
it "should not modify the original" do
... |
require './src/Eval'
require './src/MulEval'
class Test_Mul < Test::Unit::TestCase
include Eval
include Mul_Eval
def test_mul1
lit = Literal.new(10)
lit1 = Literal.new(15)
mul = Mul.new(lit, lit1)
assert_equal 150, mul.eval
end
def test_mul2
... |
def number_of_nodes
@number_of_nodes ||= header.split(" ")[0].to_i
end
def create_adjacency_matrix
adjacency_matrix = [].tap { |m| number_of_nodes.times { m << Array.new(number_of_nodes) } }
file.drop(1).map { |x| x.gsub(/\n/, "").split(" ").map(&:to_i) }.each do |(node1, node2, weight)|
adjacency_matrix[nod... |
class SuggestedTrackIdentificationSerializer < ActiveModel::Serializer
attributes :suggested_name, :suggested_track_identification_votes
belongs_to :identifier, serializer: UserSerializer
belongs_to :suggested_artist, serializer: ArtistSerializer
# has_many :suggested_track_identification_votes, each_serializ... |
# Cookbook Name:: ktc-openstack-ha
# Recipe:: _active_passive.rb
include_recipe 'sysctl'
include_recipe 'services'
include_recipe 'keepalived'
# we install this here cause keepalive doens't
package 'ipvsadm'
# initialize the Services (etc) connection
Services::Connection.new run_context: run_context
node.run_state[... |
Gem::Specification.new do |s|
s.name = 'CloudFlareDNS'
s.version = '0.2'
s.date = '2015-06-17'
s.summary = "CloudFlare DNS Gem"
s.description = "CloudFlare GEM to support add/delete/list DNS records"
s.authors = ["Lester Claudio"]
s.email = 'lester@redhat.com'
s.files ... |
require 'pry-debugger'
require 'pry'
require 'csv'
require 'rubygems'
namespace :data do
desc "imports blogs CSV files"
task :import_blogs => :environment do
csv_file_path = 'db/blogs.csv'
CSV.foreach(csv_file_path) do |row|
Blog.create!({
:name => row[0],
:blog_url => row[1],
... |
class DeleteUserPastDaysAndTaskPeople < ActiveRecord::Migration
def change
remove_column :users, :past_days, :integer
remove_column :tasks, :people, :integer
end
end
|
Rails.application.routes.draw do
# Welcome to our rails app!
# When someone browses to our website, for example by typing:
# school-tracker.adadeveloperscademy.org into their browser's URL bar
# the browser automatically translates this to:
#
# http://school-tracker.adadeveloperscademy.org/
# ^ \--... |
class Note < ApplicationRecord
# The belongs_to association creates a one-to-one match with another model.
# In database terms, this association says that this class contains the foreign key.
belongs_to :subject
end
|
require 'cinch'
require 'open-uri'
require 'nokogiri'
require 'cgi'
load './config.rb'
class Dictionary
include Cinch::Plugin
match /dictionary (.+)/
match /define (.+)/
def dictionary(query)
url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/#{CGI.escape(query)}?key=#{CONFIG_DICTIONARY_API_... |
class SessionsController < ApplicationController
before_action :current_user
def new
unless current_user.nil?
redirect_to home_path
end
end
def create
user = User.from_omniauth(env["omniauth.auth"])
session[:user_id] = user.id
redirect_to home_path
end
def destroy
session[:user_id] = n... |
class Item < ActiveRecord::Base
belongs_to :publisher
has_and_belongs_to_many :products
end
|
module Docks
class List
fattr(:hash) do
res = {}
path = File.dirname(__FILE__) + "/../../defs/**/*.yml"
path = File.expand_path(path)
Dir[path].each do |f|
res = res.merge(add_file(f))
end
res
end
def add_file(f)
from_yaml = YAML::load(File.read(f))
... |
class UserDecorator < Draper::Decorator
delegate_all
def short_name
"#{object.first_name} #{object.last_name}"
end
def self.collections
[:administrators, :authors]
end
end
|
require 'test_helper'
class ImportFilesControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
end
test "should get new" do
get :new
assert_response :success
assert_template :new
end
test "should error with empty file" do
post :cr... |
class Api::ApiController < ApplicationController
respond_to :json
protected
# If the block passed to authenticate_or_request_with_http_token returns true, the authentication passes
# So, in here we check that an ApiKey exists with the token that is passed in
def restrict_access
authenticate_or_request_w... |
# frozen_string_literal: true
class Migrate
def self.on_schema(schema)
conn = ActiveRecord::Base.connection
default_search_path = conn.schema_search_path
# Set the schema that you want run the migration
conn.schema_search_path = schema
yield schema
# Return to default schema path
conn.... |
class SocialNetwork < ActiveRecord::Base
attr_accessible :name,
:scale,
:translation_x,
:translation_y,
:node_ids,
:family_ids,
:role_ids,
:user_id,
:description
belongs_to... |
# FeedlyからエクスポートしたOPMLをDynamoDBのaddguid_targetテーブルに突っ込むスクリプト
# OLD_HOST=example.com ruby tools/opml2target.rb path-to-opml.opml
require 'uri'
require 'cgi'
require 'aws-sdk'
dynamodb = Aws::DynamoDB::Client.new(
region: 'ap-northeast-1',
)
File.foreach(ARGV[0]) do |line|
line =~ /xmlUrl="(.+?)"/
next unless $1... |
module Admin
class AboutsController < Admin::BaseController
before_action only: [:show, :edit, :update, :destroy]
def new
@about = About.new
end
def create
@about = About.new(about_params)
if @about.save
flash[:notice] = 'About Page has been created'
redirect_to adm... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# Every Vagrant virtual environment requires a box to build off of.
config.vm.box = "ubuntu/trusty64"
config.vm.provider "virtualbox" do |v|
v.name = 'jsmess'
v.memory = 3072
... |
require 'test_helper'
class UserTest < ActiveSupport::TestCase
test "non admin user" do
assert_not User.find_by_email('notconfirmed@viky.ai').admin?
assert User.find_by_email('admin@viky.ai').admin?
u = User.new(email: 'not-admin@viky.ai', password: 'Hello baby', username: 'mrwho')
assert u.save
... |
class IceTraySimulation
def self.possible_icetray_paths
[ENV['I3_SRC'], "#{ENV['HOME']}/icetray", "#{ENV['HOME']}/icecube/icetray", "#{ENV['HOME']}/code/icetray"]
end
def self.icetray_path
@icetray_path ||= possible_icetray_paths.detect do |path|
path if !path.nil? && Dir.exists?(path)
end || ... |
class ChoreSerializer < ActiveModel::Serializer
attributes :id, :chore_name, :description, :min_age
has_one :household
has_many :child_chores
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
before(:all) do
@uber_admin = User.find_or_create_by(admin: true) do |u|
u.name = "Administrator"
u.email = "admin@example.com"
u.password = "Password"
u.password_confirmation = "Password"
end
end
it "can add a regular u... |
#LETTER SWAP
=begin
Given a string of words separated by spaces, write a method that takes this string of words and returns a string in which the first and last letters of every word are swapped.
(Understand the Problem):
• (Inputs): string of words separated by spaces
• (Outputs): string (first and last... |
# encoding: utf-8
require "string_ext/version"
module StringExt
String.class_eval do
def to_bool
return true if self == true || self =~ (/\A(true|t|yes|y|1)\Z/i)
return false if self == false || self.empty? || self =~ (/\A(false|f|no|n|0)\Z/i)
raise ArgumentError.new("invalid value for Boolean... |
module ApplicationHelper
def form_element form, name, element, label_name=nil, opts={}
label_name ||= name.to_s.humanize
if opts.class == Hash
unless opts[:class]
opts[:class] = "form-control"
end
if element == :text_area
if !opts[:rows]
opts.merge!(rows: 4)
... |
# This is the dispenser that controls coin holders of each denomination
# Accepts coins of various denominations
# Coins are valued in pence, and denominations are :p1 (1p), :p2 (2p), ..., :p200 (2 pounds)
# The implementation allows for additional payment types (tokens, coupons, etc)
# to be used in the future, since... |
puts 'What is your first name?'
first_name = gets.chomp
puts 'What is your middle name?'
middle_name = gets.chomp
puts 'What is your last name?'
last_name = gets.chomp
p 'Hello '+first_name+' '+middle_name+' '+last_name+'!'
p 'What is your favorite number?'
favorite_number = gets.chomp
better_number = favorite_number.... |
=begin
write me a function stringy that takes a size and returns a string of alternating '1s' and '0s'. the string should start with a 1. a string with size 6 should return :'101010'. with size 4 should return : '1010'. with size 12 should return : '101010101010'. The size will always be positive and will only use wh... |
#public - anyone can call the method
#protected - called only be defining class and subclasses
#private - only can be called internally in class
class MyClass
private
def test1
"Private"
end
protected
def test2
"Protected"
end
public
def public_again
"Public"
... |
class TweetsController < ApplicationController
before_filter :authenticate_user!, :except => [:index]
def index
if params[:search]
@tweets = Tweet.find(:all, :conditions => ['description LIKE ?', "%#{params[:search]}%"])
else
@tweets = Tweet.order("created_at DESC")
end
end
def new
... |
# Locking module for gemma (wrapper)
#
=begin
The logic is as follows:
1. a program creates a named lock file (based on a hash of its inputs) with its PID
2. on exit it destroys the file
3. a new program checks for the lock file
4. if it exists and the PID is still in the ps table - wait
5. when the pid disappears o... |
Rails.application.routes.draw do
resources :urls, only: [:index, :new, :create, :show]
get '/:slug', to: 'urls#short', as: :short
get '/:slug/details', to: 'urls#details', as: :details
root to: 'urls#new'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
e... |
# frozen_string_literal: true
require 'rails_helper'
require 'alchemy/test_support/factories/page_factory'
require 'alchemy/test_support/factories/element_factory'
RSpec.describe Alchemy::GraphQL::ElementFields do
describe 'alchemyElements' do
let!(:element) { create(:alchemy_element) }
let!(:element_2) { c... |
class Survey < ActiveRecord::Base
has_many :questions
has_many :completions
belongs_to :creator, class_name: "User"
end
|
class Center < ActiveRecord::Base
belongs_to :foundation
attr_accessible :name, :address, :location, :lat, :long, :phone1, :phone2, :mobile, :email, :foundation_id
validates_presence_of :name, :address, :email, :location
end
|
require 'spec_helper'
describe Dog do
let(:blanks) { ['', nil] }
it { should_not have_valid(:name).when(*blanks) }
it { should have_valid(:name).when('Spot') }
it { should have_many(:owners).through(:dog_owners) }
end
|
module HasModerated
module Associations
module HasOne
module AssociationPatches
def replace_with_moderation(record, save = true)
# TODO: code duplication
if owner.new_record? || owner.moderation_disabled
replace_without_moderation record
else
if ... |
# Deaf Grandma. Whatever you say to Grandma, she should respond with this: "HUH? SPEAK UP, SONNY!".
# Unless you shout it (type in all caps). If you should, she can hear you and yells back:
# 'NO, NOT SINCE 1938!';
# Original instructions
while true
puts 'Say something to Grandma.';
your_response = gets.chomp;
yo... |
require 'uri'
require 'i18n'
require 'i18n/backend/fallbacks'
# Validates request URL
class Validations
attr_reader :url
def initialize(url)
@url = url
end
def uri
URI(url)
end
def validate_https
protocol = uri.scheme
result = {}
if protocol == 'https'
result[:message] = I18n.t... |
#!/usr/bin/env ruby
$:.unshift(File.dirname(__FILE__) + '/../lib') unless $:.include?(File.dirname(__FILE__) + '/../lib')
require 'twiq'
cmd = ARGV.shift
cmds = %w(deq enq list clear)
begin
if cmd && cmds.include?(cmd)
Twiq::Commands.stdout = STDOUT
Twiq::Commands.stdin = STDIN
Twiq::Commands.send(cmd,... |
module ApplicationHelper
def url_with_protocol(url) #from http://stackoverflow.com/questions/5012188/rails-link-to-external-site-url-is-attribute-of-user-table-like-users-websit
/^http/.match(url) ? url : "http://#{url}"
end
def meta_description(desc = nil) #from http://nycdevshop.com/blog/creating-titles-a... |
require 'rails_helper'
RSpec.describe "CreatingCategories", type: :system do
before do
driven_by(:rack_test)
end
User.destroy_all
before :each do
# Devise gem rspec helper
user = User.create(:email => 'test123@example.com', :password => 'f4k3p455w0rd')
login_as(user, :scope => :user)
Ca... |
# frozen_string_literal: true
class CreateProfileItems < ActiveRecord::Migration[5.2]
def change
create_table :profile_items do |t|
t.string :item
t.string :brand
t.string :color
t.integer :price
t.integer :cost
t.timestamps
end
end
end
|
#:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=
# ▼ Custom Weapon Formulas
# Author: Kread-EX
# Version 1.01
# Release date: 13/12/2011
#:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=
#----------------------------------------------------------------... |
class User < ApplicationRecord
has_many :microposts, dependent: :destroy
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
... |
require_relative '../helpers/mail_service'
require_relative '../helpers/mail_messages/reset_password_mail_message'
class App < Sinatra::Base
register Sinatra::Namespace
def create_reset_password_token user
token = ResetPasswordToken.create
token.user = user
token.save!
user.save!
token
end
... |
class River
attr_accessor :name
def initialize(name, fish_array)
@name = name
@fish_array = fish_array
end
def fish_count()
@fish_array.size()
end
def lose_a_fish(fish)
@fish_array.delete(fish)
end
def bear_fishing(fish, bear)
fish = @fish_array.sample
lose_a_fish(fish)
... |
class CreateProductCategories < ActiveRecord::Migration
def self.up
create_table :product_categories , :options => 'DEFAULT CHARSET=utf8' do |t|
t.string :name #类别名称
t.integer :parent_id #父类别
t.string :url #类别的静态URL地址如果有
t.string :note #简短的描述信息
t.integer :priority_flag #排序优先级标志
... |
=begin
** Form generated from reading ui file 'mainwindow.ui'
**
** Created: Sun Oct 14 05:54:02 2012
** by: Qt User Interface Compiler version 4.8.1
**
** WARNING! All changes made in this file will be lost when recompiling ui file!
=end
class Ui_MainWindow
attr_reader :centralWidget
attr_reader :vertica... |
class Board
attr_accessor :rows
attr_accessor :cols
attr_accessor :board
attr_accessor :robot
def initialize(rows, cols)
@rows = rows
@cols = cols
@board = []
@rows.times do
row = []
@cols.times do
row.push(0)
end
@board.push(row)
end
@board = @board... |
require "pry"
# David Lin
# Description: 2D binary search
# @param {Integer[][]} matrix
# @param {Integer} target
# @return {Boolean}
def search_matrix(matrix, target)
return false if matrix == []
return false if matrix == [[]]
# index range of x and y.
x_left, x_right = 0, matrix[0].size - 1
y_left, y_rig... |
require('minitest/autorun')
require('minitest/rg')
require_relative('../song.rb')
require_relative('../room.rb')
class TestSong < MiniTest::Test
def setup
@song = Song.new("Britney Spears", "Oops…I Did It Again")
end
def test_song_can_have_artist
assert_equal("Britney Spears", @song.artist)
end
def... |
class AddDefaultBookingStatusIdToPosts < ActiveRecord::Migration
def change
change_column_default(:guide_posts, :booking_status_id, 3)
change_column_default(:angler_posts, :booking_status_id, 3)
change_column_default(:property_posts, :booking_status_id, 3)
end
end
|
class Follow < ApplicationRecord
validates :shoe_id, :user_id, presence: true
belongs_to :user
belongs_to :shoe
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.