text stringlengths 10 2.61M |
|---|
class Store::ProductsController < ApplicationController
before_action :find_product, only: [:show]
def show
@cart_item = CartItem.new
end
private
def find_product
@product = Product.find(params[:id])
end
end |
# gem 'rubyzip'
require 'zip/zipfilesystem'
require 'zip/zip'
class ZipIt
def self.zip_file(archive, file)
path = File.dirname(file)
path.sub!(%r[/$],'')
FileUtils.rm archive, :force=>true
entry_name = File.basename(file)
Zip::ZipFile.open(archive, 'w') do |zipfile|
zipfile.add(entry_name,file)
end
end
def self.zip_folder(archive, path)
path.sub!(%r[/$],'')
FileUtils.rm archive, :force=>true
Zip::ZipFile.open(archive, 'w') do |zipfile|
Dir["#{path}/**/**"].reject{|f|f==archive}.each do |file|
zipfile.add(file.sub(path+'/',''),file)
end
end
end
end
|
require "rails_helper"
RSpec.feature "Records", type: :feature do
before do
@user = FactoryBot.create(:user)
@record = FactoryBot.build(:record)
end
context "新規投稿ができるとき" do
it "ログインしたユーザーは新規投稿できる" do
# ログインする
visit new_user_session_path
fill_in "user_email", with: @user.email
fill_in "user_password", with: @user.password
click_button("ログインする")
visit new_record_path
expect(current_path).to eq new_record_path
fill_in "record_name_a", with: @record.name_a
# 投稿するとRecordモデルのカウントが1上がる
expect { click_on("投稿する") }.to change(Record, :count).by(1)
# ユーザーページに遷移し、投稿した情報が存在する
expect(current_path).to eq user_path(@user)
expect(page).to have_content(@record.name_a)
end
end
context "新規投稿ができないとき" do
it "ログインしていないと新規投稿ページに遷移できない" do
# トップページに遷移する
visit root_path
# 新規投稿ページへのリンクがない
expect(page).to have_no_link("スコア投稿")
end
it "投稿内容が空だと投稿できない" do
# ログインする
visit new_user_session_path
fill_in "user_email", with: @user.email
fill_in "user_password", with: @user.password
click_button("ログインする")
# 「投稿」をクリックし、新規投稿ページへ遷移する
visit new_record_path
expect(current_path).to eq new_record_path
# フォームが空のまま、投稿ボタンを押してもRecordモデルのカウントが変わらない
fill_in "record_name_a", with: ""
click_button "投稿する"
expect { click_on("投稿する") }.to change(Record, :count).by(0)
# 新規投稿ページへ戻される
expect(current_path).to eq "/records"
end
end
end
RSpec.describe "投稿内容の編集", type: :feature do
before do
@user = FactoryBot.build(:user)
@record = FactoryBot.create(:record)
end
context "投稿内容が編集できるとき" do
it "ログインしたユーザーは、自分が投稿した投稿内容を編集ができる" do
# 投稿を投稿したユーザーでログインする
visit new_user_session_path
fill_in "user_email", with: @user.email
fill_in "user_password", with: @user.password
click_button("ログインする")
# 投稿の詳細ページへ遷移する
visit record_path(@record.id)
# 編集するボタンをクリックし、編集ページへ遷移する
find_link("編集").click
expect(current_path).to eq edit_record_path(@record)
# すでに投稿済みの内容がフォームに入っている
expect(find("#record_title").value).to eq @record.title
expect(find("#record_place").value).to eq @record.place
expect(find("#record_teamname").value).to eq @record.teamname
expect(find("#record_enemyteam").value).to eq @record.enemyteam
expect(find("#record_name_a").value).to eq @record.name_a
expect(find("#record_name_b").value).to eq @record.name_b
expect(find("#record_name_c").value).to eq @record.name_c
expect(find("#record_enemyname_a").value).to eq @record.enemyname_a
expect(find("#record_enemyname_b").value).to eq @record.enemyname_b
expect(find("#record_enemyname_c").value).to eq @record.enemyname_c
fill_in "record_title", with: "編集"
fill_in "record_place", with: "編集"
fill_in "record_teamname", with: "編集"
fill_in "record_enemyteam", with: "編集"
fill_in "record_name_a", with: "編集"
fill_in "record_name_b", with: "編集"
fill_in "record_name_c", with: "編集"
fill_in "record_enemyname_a", with: "編集"
fill_in "record_enemyname_b", with: "編集"
fill_in "record_enemyname_c", with: "編集"
# 編集してもRecordモデルのカウントは変わらない
expect { click_on("更新する") }.to change(Record, :count).by(0)
# 編集した内容の投稿が成功する
expect(page).to have_content "編集"
end
end
context "投稿内容が編集できないとき" do
it "ログインしていないと、投稿の編集画面には遷移できない" do
# トップページにいる
visit root_path
# 投稿の詳細ページへ遷移する
visit record_path(@record)
# 投稿に編集ボタンがない
expect(page).to have_no_link "編集", href: edit_record_path(@record)
end
end
end
|
class ProfileMatrix < Matrix
#*******************
#Apply a profile matrix over a DNAarray to obtain the most probable DNAmotifs in DNAarray through the profile matrix and its probability.
#It also works in the particular case in which the DNAarray is just a DNAsequence
#*******************
#The length of the motif is determined by the width of the profile matrix.
#If mode == 'random' and the matrix acts over a sequence, a randomly generated k-mer is returned, with prbabilities fixed by the matrix
def over(object, mode = 'best')
if object.is_a? DNAsequence
if mode == 'best'
return _overSequence(object)
elsif mode == 'random'
return _randomSequence(object)
else
puts "Wrong mode"
exit
end
elsif object.is_a? DNAarray
prob = 1
motifs = []
0.upto(object.height - 1){ |i|
motif, pr = _overSequence(object.at(i))
prob *= pr
motifs.push(motif)
}
end
return [DNAmotifsArray.new(motifs), prob]
end
#*******************
#*******************
#
#Private methods
#
#*******************
#*******************
private
#*******************
#Returns the most probable k-mer from the sequence through the matrix as a DNAsequence and its probability
#*******************
#For the particular case in which k == width of the profile matrix, it returns the same k-mer and its probability
def _overSequence(sequence)
if sequence.length == @width
return [sequence, _probability(sequence)]
end
mostP = sequence.cut(0, @width)
maxp = _probability(mostP)
1.upto(sequence.length - @width){ |i|
kmer = sequence.cut(i, @width)
prob = _probability(kmer)
if prob > maxp
maxp = prob
mostP = kmer
end
}
return [mostP, maxp]
end
#*******************
#Computes the probability of a DNAsequence through the profile matrix
#*******************
#The length of the sequence must be the width of the profile matrix
def _probability(sequence, round = 8)
prob = 1
0.upto(sequence.length - 1){ |i|
prob *= @matrix[Base.new(sequence.cut(i, 1).to_s).number][i]
}
return prob.round(round)
end
#*******************
#Returns a k-mer from sequence, with the probability computed from the profile matrix
#*******************
def _randomSequence(sequence)
if sequence.length == @width
return [sequence, _probability(sequence)]
end
#Compute the probability of each k-mer
probs = []
0.upto(sequence.length - @width){ |i|
probs.push(_probability(sequence.cut(i, @width)))
}
#Generate a non-uniform random number with these probabilities and return the correspondent k-mer
i = _nonUniformRandom(probs)
return [sequence.cut(i, @width), probs[i]]
end
#*******************
#Returns an integer in [0, probs.length - 1] with a probability set by the values at probs.
#*******************
#probs is just a set of non-negative numbers. They do not necessarily sum to 1.
def _nonUniformRandom(probs)
#1. Normalize to sum = 1
weight = 0
probs.each{ |prob|
weight += prob
}
0.upto(probs.length - 1){ |i|
probs[i] /= weight.to_f
}
#2. Build the intervals array
intervals = Array.new.push(probs[0])
1.upto(probs.length - 1){ |i|
intervals[i] = intervals[i - 1] + probs[i]
}
#3. Random number between 0 and 1
die = rand()
#4. Check the interval which contains the random
result = 0
while(intervals[result] < die)
result += 1
end
return result
end
end
|
class AddingCustomernameAndTotalassets < ActiveRecord::Migration
def change
add_column :project_completions, :m_customer_name, :string
add_column :project_completions, :m_total_firestop_assets, :string
end
end
|
require 'open-uri'
require 'nokogiri'
require 'pry'
class Scraper
def self.scrape_index_page(index_url)
doc = Nokogiri::HTML(open(index_url))
students = []
doc.css('div.roster-cards-container').each do |card|
students =
card.css('.student-card a').map do |student|
{
:name => student.css('.student-name').text,
:location => student.css('.student-location').text,
:profile_url => "./fixtures/student-site/#{student.attr('href')}"
}
end
end
students
end
def self.scrape_profile_page(profile_url)
doc = Nokogiri::HTML(open(profile_url))
attributes = Hash.new
doc.css('.social-icon-container a').each do |social|
attributes[:twitter] = social['href'] if social['href'].include?('twitter')
attributes[:linkedin] = social['href'] if social['href'].include?('linkedin')
attributes[:github] = social['href'] if social['href'].include?('github')
attributes[:blog] = social['href'] if
(doc.css('.social-icon-container img').map do |image|
image['src'].include?('rss-icon')
end).include?(true)
end
attributes[:bio] = doc.css('.details-container .description-holder p').text
attributes[:profile_quote] = doc.css('.profile-quote').text
attributes
end
end
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Brcobranca::Retorno::Cnab240::Base do
let(:arquivo) { File.join(File.dirname(__FILE__), '..', '..', '..', 'arquivos', nome_arquivo) }
describe '#load_lines' do
it 'retorna nil se o arquivo é nil' do
expect(described_class.load_lines(nil)).to be_nil
end
context 'Sicoob' do
subject { Brcobranca::Retorno::Cnab240::Sicoob }
let(:nome_arquivo) { 'CNAB240SICOOB.RET' }
it 'lê o arquivo pela classe do Sicoob' do
expect(subject).to receive(:load_lines).with(arquivo, {})
described_class.load_lines(arquivo)
end
end
end
end
|
require 'fcm'
class PushNotification < ActiveRecord::Base
# A PushNotification uses the Parse API to send a standard
# push notification message to the mobile devices of all
# subscribers of a given "channel."
# Byte's channels correspond to specific application resources,
# such as restaurant locations, menu items, and users.
#############################
### ATTRIBUTES
#############################
attr_accessible :notification_type, :message, :additional_data
serialize :additional_data # a hash that might include the push_notifiable_type
#############################
### ASSOCIATIONS
#############################
belongs_to :push_notifiable, polymorphic: true
#############################
### VALIDATIONS
#############################
validates :notification_type, presence: true, inclusion: { in: PUSH_NOTIFICATION_TYPES }
validates :push_notifiable_type, presence: true, inclusion: { in: PUSH_NOTIFIABLE_TYPES }
validates :push_notifiable_id, presence: true, numericality: { only_integer: true }
validates :message, presence: true
#############################
### INSTANCE METHODS
#############################
def dispatch device_token
# You can use this method with something like:
# Item.push_notifications.create(message: 'Great new price!').dispatch
# but the more common way is the dispatch_message_to_resource_subscribers
# class method (see below).
# NOTE: We are using Parse's "Advanced Targeting" because we
# only want to send push notifications to users whose preferences
# allow them.
# Create the push notification object
# data = {
# alert: message,
# pushtype: notification_type,
# # title: 'TBD',
# sound: 'chime',
# badge: 'Increment',
# }
# data.merge!(additional_data) if additional_data.present?
# push = Parse::Push.new(data)
# Advanced Targeting parameters
# (See the "Sending Pushes to Queries" subsection of:
# https://parse.com/docs/push_guide#sending-queries/REST )
# The User must be subscribed to the given channel and accept notifications of
# the given type, and notifications may only be sent to the User's current device.
# query = Parse::Query.new(Parse::Protocol::CLASS_INSTALLATION).
# eq('channels', PushNotificationSubscription.channel_name_for(push_notifiable)). # 'channels' is an array but the Parse documentation indicates it may be used this way
# eq('push_notification_types', notification_type) # This should work the same way as 'channels'; an array that can be used without 'include' sytax
# push.where = query.where
# Send the push notification to all currently-active subscriber devices
# push.save
# return true
# dm2EQT55ewY:APA91bF9xk24TPxNedvAvvdqsOIxmKngzjTiIbR6AO1xNUHSB-mrEpvVA0BWllvWMTuYgj4nlTwPGk9wzBNw3wn33trzrHiNetbWcJ_PjDKDM-WhM4nThKMvnfPzbZnwD1fmdvU1JSso,
# debugger
data = {}
if additional_data.present?
data = {
:notification => {
:body => message,
# :title => "TBD",
:icon => "myicon",
:sound => 'chime',
# :badge => 'Increment',
:pushtype=> notification_type,
:locationid=> additional_data[:location_id],
:click_action=> "OpenAction",
},
:content_available => true,
:to=> device_token,
:priority => 'high',
:data=> {
:body => message,
:pushtype=> notification_type,
:locationid=> additional_data[:location_id]
}
}
else
data = {
:notification => {
:body => message,
# :title => "TBD",
:icon => "myicon",
:sound => 'chime',
# :badge => 'Increment',
:pushtype=> notification_type,
:click_action=> "OpenAction",
},
:content_available => true,
:to=> device_token,
:priority => 'high',
:data=> {
:body => message,
:pushtype=> notification_type,
}
}
end
# data.merge!(additional_data) if additional_data.present?
url = URI.parse('https://fcm.googleapis.com/fcm/send')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
# data.merge!(additional_data) if additional_data.present?
request = Net::HTTP::Post.new(url.path,
{"Content-Type" => 'application/json',
'Authorization' => 'key=' + Rails.application.config.fcm_public_key}
)
request.body = data.to_json
response = http.request(request)
# fcm = FCM.new(Rails.application.config.fcm_public_key)
# data = {
# alert: message,
# pushtype: notification_type,
# # title: 'TBD',
# sound: 'chime',
# badge: 'Increment',
# }
# registration_ids=[]
# registration_ids << device_token
# options = {data: data, collapse_key: "updated_score"}
# response = fcm.send(registration_ids, options)
return response
end
#############################
### CLASS METHODS
#############################
def self.dispatch_message_to_resource_subscribers(notification_type, message, resource, additional_data_hash = {})
# You can use this method with something like:
# PushNotification.dispatch_message_to_resource_subscribers('fav_item_on_special', 'Great new price!', item)
# return false unless self.resource_is_valid?(resource)
# resource.push_notifications.create({
# notification_type: notification_type,
# message: message,
# additional_data: additional_data_hash
# }).dispatch
return false unless self.resource_is_valid?(resource)
resource.push_notifications.create({
notification_type: notification_type,
message: message,
additional_data: additional_data_hash
}).dispatch(resource.device_token)
end
def self.resource_is_valid?(resource)
PUSH_NOTIFIABLE_TYPES.include?(resource.class.to_s)
end
end
|
require 'spec_helper'
describe Translation do
it { should validate_uniqueness_of(:language_id).scoped_to(:resource_id) }
it { should belong_to :language }
it { should belong_to :resource }
it { should allow_mass_assignment_of :text }
it { should allow_mass_assignment_of :language_id }
it { should allow_mass_assignment_of :resource_id }
end
|
# frozen_string_literal: true
FactoryBot.define do
factory :permission, class: Permission do
transient { role { 'user' } }
permissions { Role.find_by(name: role).permissions.map { |perm| perm[:name] } }
end
end
|
class CreateBookings < ActiveRecord::Migration[5.2]
def change
create_table :bookings do |t|
t.integer :table_size
t.references :time_slot, foreign_key: true
t.references :user, foreign_key: true
t.references :restaurant, foreign_key: true
t.string :name
t.string :email
t.string :number
t.datetime :time
t.integer :discount
t.timestamps
end
end
end
|
module RubyXL
# http://www.schemacentral.com/sc/ooxml/e-ssml_sheetView-1.html
class SheetView < OOXMLObject
define_attribute(:tab_selected, :tabSelected, :int)
define_attribute(:zoom_scale, :zoomScale, :int, false, 100)
define_attribute(:zoom_scale_normal, :zoomScaleNormal, :int, false, 100)
define_attribute(:workbook_view_id, :workbookViewId, :int, :required, 0)
define_attribute(:view, :view, :string, false,
%w{ normal pageBreakPreview pageLayout })
attr_accessor :pane, :selections
def initialize
@pane = nil
@selections = []
super
end
def self.parse(node)
sheetview = super
node.element_children.each { |child_node|
case child_node.name
when 'pane' then sheetview.pane = RubyXL::Pane.parse(child_node)
when 'selection' then sheetview.selections << RubyXL::Selection.parse(child_node)
else raise "Node type #{child_node.name} not implemented"
end
}
sheetview
end
def write_xml(xml)
node = xml.create_element('sheetView', prepare_attributes)
node << pane.write_xml(xml) if @pane
@selections.each { |sel| node << sel.write_xml(xml) }
node
end
end
class Pane < OOXMLObject
define_attribute(:x_split, :xSplit, :int)
define_attribute(:y_split, :ySplit, :int)
define_attribute(:top_left_cell, :topLeftCell, :string)
define_attribute(:active_pane, :activePane, :string, false, nil,
%w{ bottomRight topRight bottomLeft topLeft })
define_element_name 'pane'
end
class Selection < OOXMLObject
define_attribute(:pane, :pane, :string, false, nil,
%w{ bottomRight topRight bottomLeft topLeft })
define_attribute(:active_cell, :activeCell, :string)
define_attribute(:active_cell_id, :activeCellId, :int) # 0-based index of @active_cell in @sqref
define_attribute(:sqref, :sqref, :sqref, :required) # Array of references to the selected cells.
define_element_name 'selection'
def self.parse(node)
sel = super
sel.active_cell = RubyXL::Reference.new(sel.active_cell) if sel.active_cell
sel
end
def before_write_xml
# Normally, rindex of activeCellId in sqref:
# <selection activeCell="E12" activeCellId="9" sqref="A4 B6 C8 D10 E12 A4 B6 C8 D10 E12"/>
if @active_cell_id.nil? && !@active_cell.nil? && @sqref.size > 1 then
# But, things can be more complex:
# <selection activeCell="E8" activeCellId="2" sqref="A4:B4 C6:D6 E8:F8"/>
# Not using .reverse.each here to avoid memory reallocation.
@sqref.each_with_index { |ref, ind| @active_cell_id = ind if ref.cover?(@active_cell) }
end
end
end
end
|
Then(/^I should have the new records$/) do
Record.count.should == 1
Record.find(1).data.should == 'data'
end
|
class OrderMailer < ActionMailer::Base
default from: "store@ski-lines.com"
add_template_helper(OrdersHelper)
def merchant_purchase_orders(order, user)
@url = 'https://www.ski-lines.com'
@order = order
@user = user
mail(to: @user.email, subject: 'You have a new order!')
end
def customer_purchase_order(order)
@order = order
@url = 'https://www.ski-lines.com'
mail(to: @order.cust_email, subject: 'Your Ski-Lines Purchase Details')
end
end
|
require 'minitest/autorun'
require './lib/arcade/intro/edge_of_the_ocean'
class TestEdgeOfTheOcean < Minitest::Test
def setup
@this_world = EdgeOfTheOcean.new
end
def test_adjacent_elements_product
assert_equal 21, @this_world.adjacent_elements_product([3, 6, -2, -5, 7, 3])
assert_equal (-12), @this_world.adjacent_elements_product([-23, 4, -3, 8, -12])
assert_equal 0, @this_world.adjacent_elements_product([1, 0, 1, 0, 1000])
end
def test_shape_area
assert_equal 5, @this_world.shape_area(2)
assert_equal 1, @this_world.shape_area(1)
assert_equal 199900013, @this_world.shape_area(9998)
end
def test_make_array_consecutive2
assert_equal 3, @this_world.make_array_consecutive2([6, 2, 3, 8])
assert_equal 0, @this_world.make_array_consecutive2([1])
assert_equal 2, @this_world.make_array_consecutive2([0, 3])
end
def test_almost_increasing_sequence
assert_equal false, @this_world.almost_increasing_sequence([1, 3, 2, 1])
assert_equal true, @this_world.almost_increasing_sequence([1, 2, 5, 3, 5])
assert_equal true, @this_world.almost_increasing_sequence([3, 5, 67, 98, 3])
end
end |
class AddDefaultLatlngToAdresses < ActiveRecord::Migration
def change
change_column :adresses, :lat, :decimal, {:precision=>10, :scale=>6, default: 0}
change_column :adresses, :lng, :decimal, {:precision=>10, :scale=>6, default: 0}
end
end
|
class NeighborList < BaseModel
include Singleton
attr_accessor :list
alias :neighbors :list
def initialize
@list = []
end
def each_neighbor(&block)
list.each do |n|
yield n
end
end
def <<(neighbor)
list << neighbor
end
def self.each_neighbor(&block)
instance.each_neighbor(&block)
end
end
|
class CreateRawPageViews < ActiveRecord::Migration
def self.up
create_table :raw_page_views do |t|
t.column :owner_type, :string, :null => false
t.column :owner_id, :int, :null => false
t.column :viewed_at, :datetime, :null => false
t.column :session_id, :string, :null => false
t.column :ip_address, :string, :null => false
t.column :owner_user_id, :int, :null => false
end
add_index :raw_page_views, [:owner_id, :owner_type], :name => 'raw_page_views_owner_id_and_type_index'
add_index :raw_page_views, :viewed_at
add_index :raw_page_views, :session_id
add_index :raw_page_views, :ip_address
end
def self.down
drop_table :raw_page_views
end
end
|
require_relative 'pg/database'
module HerokuCLI
# manage postgresql databases
class PG < Base
# show database information
def info
@info ||= begin
heroku('pg:info').split("===").reject(&:empty?).map do |stdout|
next if stdout.nil? || stdout.length.zero?
stdout = stdout.split("\n")
stdout[0] = "===#{stdout[0]}"
Database.new(stdout, self)
end
end
end
def reload
@info = nil
end
# create a follower database
def create_follower(database, options = {})
plan = options.delete(:plan) || database.plan
heroku "addons:create heroku-postgresql:#{plan} --follow #{database.resource_name}"
end
# Remove the following of a database and put DB into write mode
def un_follow(database, wait: false)
raise "Not a following database #{database.name}" unless database.follower?
heroku "pg:unfollow #{database.url_name} -c #{application.name}"
wait_for_follow_fork_transformation(database) if wait
end
# sets DATABASE as your DATABASE_URL
def promote(database, wait: false)
raise "Database already main #{database.name}" if database.main?
un_follow(database, wait: wait) if database.follower?
heroku "pg:promote #{database.resource_name}"
end
def destroy(database)
raise "Cannot destroy #{application.name} main database" if database.main?
heroku "addons:destroy #{database.url_name} -c #{application.name}"
end
# Return the main database
def main
info.find(&:main?)
end
# Returns an array of allow forks databases
def forks
info.find_all(&:fork?)
end
# Returns an array of allow follower databases
def followers
info.find_all(&:follower?)
end
# blocks until database is available
def wait
heroku 'pg:wait'
end
def wait_for_follow_fork_transformation(database)
while database.follower? do
puts "...wait 10 seconds for DB to change from follower to fork"
sleep 10
database.reload
puts database
end
end
end
end
|
class CreateVoicemailMsgs < ActiveRecord::Migration
def self.up
create_table :voicemail_msgs, :id => false do |t|
t.integer :created_epoch
t.integer :read_epoch
t.string :username, :limit => '255'
t.string :domain, :limit => '255'
t.string :uuid, :limit => '255'
t.string :cid_name, :limit => '255'
t.string :cid_number, :limit => '255'
t.string :in_folder, :limit => '255'
t.string :file_path, :limit => '255'
t.integer :message_len
t.string :flags, :limit => '255'
t.string :read_flags, :limit => '255'
t.string :forwarded_by, :limit => '255'
end
add_index :voicemail_msgs, [ :created_epoch ], :unique => false, :name => 'voicemail_msgs_idx1'
add_index :voicemail_msgs, [ :username ], :unique => false, :name => 'voicemail_msgs_idx2'
add_index :voicemail_msgs, [ :domain ], :unique => false, :name => 'voicemail_msgs_idx3'
add_index :voicemail_msgs, [ :uuid ], :unique => false, :name => 'voicemail_msgs_idx4'
add_index :voicemail_msgs, [ :in_folder ], :unique => false, :name => 'voicemail_msgs_idx5'
add_index :voicemail_msgs, [ :read_flags ], :unique => false, :name => 'voicemail_msgs_idx6'
add_index :voicemail_msgs, [ :forwarded_by ], :unique => false, :name => 'voicemail_msgs_idx7'
end
def self.down
drop_table :voicemail_msgs
end
end
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Arclight::Indexer do
ENV['SOLR_URL'] = Blacklight.connection_config[:url]
subject(:indexer) { described_class.new } # `initialize` requires a solr connection
let(:xml) do
data = Nokogiri::XML(
File.open('spec/fixtures/ead/nlm/alphaomegaalpha.xml').read
)
data.remove_namespaces!
data
end
it 'is a wrapper around SolrEad::Indexer' do
expect(indexer).to be_kind_of SolrEad::Indexer
end
describe '#add_collection_context_to_parent_fields' do
context 'collection context' do
it 'are appended to the existing parent fields' do
node = xml.at_xpath('//c')
fields = indexer.additional_component_fields(node)
expect(fields['parent_ssi']).to eq 'aoa271'
expect(fields['parent_ssm']).to eq ['aoa271']
expect(fields['parent_unittitles_ssm']).to eq ['Alpha Omega Alpha Archives, 1894-1992']
end
end
end
describe '#add_count_of_child_compontents' do
it 'adds the number of direct children' do
node = xml.at_xpath('//c[@id="aspace_563a320bb37d24a9e1e6f7bf95b52671"]')
fields = indexer.additional_component_fields(node)
expect(fields['child_component_count_isim']).to eq 25
end
it 'returns zero when the child has no components' do
node = xml.at_xpath('//c[@id="aspace_843e8f9f22bac69872d0802d6fffbb04"]')
fields = indexer.additional_component_fields(node)
expect(fields['child_component_count_isim']).to eq 0
end
end
describe '#add_collection_creator_to_component' do
it 'adds the creator of the collection to a stored non-indexed/faceted field' do
node = xml.xpath('//c[@id="aspace_563a320bb37d24a9e1e6f7bf95b52671"]').first
fields = indexer.additional_component_fields(node)
expect(fields['creator_ssim']).to be_nil
expect(fields['collection_creator_ssm']).to eq ['Alpha Omega Alpha']
end
end
describe '#add_self_or_parents_restrictions' do
it 'adds first restrictions found in self, parents, or collection' do
node = xml.xpath('//c[@id="aspace_72f14d6c32e142baa3eeafdb6e4d69be"]').first
fields = indexer.additional_component_fields(node)
expect(fields['parent_access_restrict_ssm']).to eq ['No restrictions on access.']
end
end
describe '#add_self_or_parents_terms' do
it 'adds first user terms found in self, parents, or collection' do
node = xml.xpath('//c[@id="aspace_72f14d6c32e142baa3eeafdb6e4d69be"]').first
fields = indexer.additional_component_fields(node)
expect(fields['parent_access_terms_ssm']).to eq ['Original photographs must be handled using gloves.']
end
end
describe 'delete_all' do
before do
expect(indexer).to receive_messages(solr: solr_client)
end
let(:solr_client) { instance_spy('SolrClient') }
it 'sends the delete all query to solr and commits' do
indexer.delete_all
expect(solr_client).to have_received(:delete_by_query).with('*:*')
expect(solr_client).to have_receive(:commit)
end
end
end
|
require 'spec_helper'
describe "TrainingSample" do
before :all do
explanatory_variable(:x) { type :numeric }
explanatory_variable(:y) { type :numeric }
end
let(:training_sample) { TrainingSample.new("./spec/lib/test_training_data.csv") }
describe "initialize" do
let(:other_sample) { TrainingSample.new([trans], [:amount, :email_match]) }
let(:trans) { FactoryGirl.create(:good_transaction, amount: 100) }
it "should initialize a sample from either 1) a csv file, or 2) an array of transactions and an array of EV's" do
other_sample.size.should == 1
other_sample.mean(:amount).should == 100
end
#TODO: decide what to do about the difference between a sample initialized from a csv vs. a list of transactions
#TODO: (for example, a value being stored as "true" vs. :true)
end
describe "#size" do
it "should return the size of the sample" do
training_sample.size.should == 3
end
end
describe "#mean" do
it "should compute the sample mean of its numeric columns" do
training_sample.mean(:x).should == 0.5
training_sample.mean(:y).should == 0.5
end
end
describe "#stdev" do
it "should compute the sample standard deviation" do
training_sample.stdev(:x).should be_within(0.01).of(0.5)
training_sample.stdev(:y).should be_within(0.01).of(0.5)
end
end
describe "#bucketter" do
it "should produce a bucketter for the column of this name" do
training_sample.bucketter(:x, 3).cutoffs.should == [0.25, 0.75]
end
end
describe "#[]" do
it "should lookup columns by name" do
training_sample[:x].should == [1.0, 0.0, 0.5]
training_sample[:category].should == ["true", "false", "true"]
end
end
describe "#hashify" do
it "should create a hash with column names from an array" do
training_sample.hashify(["true", 0, 1]).should == { category: "true", x: 0, y: 1 }
end
end
describe "#find_row" do
it "should lookup a row by index" do
training_sample.find_row(0).should == ["true", 1.0, 0.0]
training_sample.find_row(1).should == ["false", 0.0, 1.0]
training_sample.find_row(2).should == ["true", 0.5, 0.5]
end
end
describe "#sample_distribution" do
it "should produce an estimated cumulative distribution function" do
dist = training_sample.sample_distribution(:x)
dist.proportion_under(0.75).should > 0.66
dist.proportion_under(1).should <= 1
dist.proportion_under(0).should >= 0
dist.proportion_under(0.5).should >= 0.33
end
end
describe "#write_to_csv" do
before :all do
if File.exists?('./spec/lib/training_sample_write.rb')
raise "this test expected that the file /spec/lib/training_sample_write.csv did not exist, " +
"but it did and I panicked"
end
end
after :all do
File.delete('./spec/lib/training_sample_write.rb')
end
it "should write the sample to a csv file" do
training_sample.write_to_csv('./spec/lib/training_sample_write.rb')
duplicate_sample = TrainingSample.new('./spec/lib/training_sample_write.rb')
duplicate_sample.size.should == training_sample.size
duplicate_sample.col_names.should == training_sample.col_names
duplicate_sample[:y].should == training_sample[:y]
end
end
end |
class CreateChannelBots < ActiveRecord::Migration[5.0]
def up
create_table :channel_bots do |t|
t.integer :live_status_id
t.integer :intended_status_id
t.string :bot_name
t.integer :channel_id
t.timestamps
end
end
def down
drop_table :channel_bots
end
end
|
require 'spec_helper'
require_relative '../../lib/paths'
using ArrayExtension
using StringExtension
using SymbolExtension
module Jabverwock
RSpec.describe 'path test' do
subject(:oo) { JW_CSS_OPAL_JS.new }
it 'path is exist' do
oo.opalPath = "/test"
expect(oo.isExistOpalScript).to eq true
end
it 'path is not exist' do
oo.opalPath = ""
expect(oo.isExistOpalScript).to eq false
end
it 'file name, incorrect' do
oo.opalPath = ""
oo.readOpalFile ("/test")
expect(oo.opalFileName).to eq ""
end
end
end
|
FactoryGirl.define do
factory :spree_adyen_ratepay_source, aliases: [:ratepay_source], class: "Spree::Adyen::RatepaySource" do
auth_result "Authorised"
psp_reference { SecureRandom.hex }
trait :dob_provided do
dob_day "12"
dob_month "12"
dob_year "1970"
end
end
end
|
module Api
module V2
class PrizesController < Api::BaseController
respond_to :json
def index
@prizes = nearby_locations.map do |l|
points = l.points_awarded_for_checkin + @user.points
prizes = Prize.get_unlocked_prizes_by_location(l.id, points, @user.id)
prizes.each do |p|
p.location_id = l.id
p.location_logo = l.logo.try(:url)
p.location_cuisine = []
p.location_cuisine << {name: l.primary_cuisine} if l.primary_cuisine.present?
p.location_cuisine << {name: l.secondary_cuisine} if l.secondary_cuisine.present?
p.location_name = l.name
p.location_lat = l.lat.to_f
p.location_long = l.long.to_f
p.byte_prize_type = get_prize_type(p.id)
end
end.flatten.compact.uniq{|prize| [prize.id, prize.location_id]}
end
private
def get_prize_type(prize_id)
share_prize = SharePrize.where(prize_id: prize_id).first
return share_prize.from_share if share_prize.present?
user_prize = UserPrize.where(prize_id: prize_id).first
return 'owner' if user_prize.present?
return 'immediate'
end
end
end
end
|
#!/Users/spamram/.rvm/rubies/ruby-1.9.2-p180/bin/ruby
# Goal:
# Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
sum = 1.upto(1000).inject(0) {|sum, n| sum += (n**n)}.to_s
len = sum.length
puts sum[(len-10)..(len-1)] |
require 'spec_helper'
describe League do
it 'has many heroes' do
league1 = League.create(name: "League of Rosy Pedals")
hero1 = Hero.create(name: "Ralph", power: "Wreck it", league_id: league1.id)
hero2 = Hero.create(name: "Venelopy", power: "Drive Really Fast", league_id:league1.id)
expect(league1.heros).to eq [hero1, hero2]
end
end
|
module Protocols::Shareable
def self.included(model)
model.class_eval do
has_many :shares, :as => :content
after_save :share!, :if => :shareable?
end
end
# Is this instance shareable or not? Overrideable, but include +super+, e.g.,
#
# Review.class_eval do
# def shareable?
# super && active?
# end
# end
def shareable?
shares.unshared.any?
end
def share!
shares.unshared.each { |share| Resque.enqueue SharingJob, share.id }
end
# A string containing user-supplied content. (It may be truncated.)
def user_generated_content
raise UnimplementedMethodError.new(self, :user_generated_content)
end
# The title of the resource being mentioned.
def title
raise UnimplementedMethodError.new(self, :title)
end
# A description of the resource mentioned.
def description
raise UnimplementedMethodError.new(self, :description)
end
# An association, object, or array of objects that conform to the
# <tt>Protocols::Shareable::Media</tt> protocol.
def media
raise UnimplementedMethodError.new(self, :media)
end
# The kind of content mentioned.
#
# Default:
#
# self.class.name.downcase
def kind
self.class.name.downcase
end
end
|
module Refinery
module Pods
class Pod < Refinery::Core::BaseModel
self.table_name = 'refinery_pods'
POD_TYPES = %w(content banner gallery video inquiry)
attr_accessible :name, :body, :url, :image_id, :pod_type, :portfolio_entry_id, :video_id, :position, :page_ids
acts_as_indexed :fields => [:name, :body, :url, :pod_type]
validates_presence_of :name
validates_inclusion_of :pod_type, :in => POD_TYPES
belongs_to :image, :class_name => '::Refinery::Image'
belongs_to :portfolio_entry, :class_name => '::Refinery::Portfolio::Gallery'
belongs_to :video, :class_name => '::Refinery::Videos::Video'
has_and_belongs_to_many :pages, :class_name => '::Refinery::Page', :join_table => 'refinery_pages_pods'
def system_name
pod_type
end
end
end
end
|
#!/usr/bin/env ruby
module Boolean; end
class TrueClass; include Boolean; end
class FalseClass; include Boolean; end
class RubyTruth
def initialize
vals = %w(true false nil) + (0..9).to_a
ops = %w(|| &&)
@statement = create_statement(vals, ops)
end
def play
puts @statement, 'True, truthy, false, or falsey?'
evaluated_statement = evaluate @statement
response = gets.chomp.downcase.strip
the_rest = " This statement is #{evaluated_statement}."
response == evaluated_statement ? 'Correct!' + the_rest : 'Incorrect!' + the_rest
end
def evaluate(arg)
case arg
when Boolean
arg.to_s
when Integer
'truthy'
when nil
'falsey'
else
evaluate(eval arg)
end
end
private
def create_statement(vals, ops)
rand(2) == 1 ? vals.sample : [vals.sample, ops.sample, vals.sample].join(' ')
end
end
if __FILE__ == $0
puts RubyTruth.new.play
end
|
# Topic.where(name: 'teeth extraction')[0].id
FactoryBot.define do
factory :procedure do
patient
time_ago 1
time_ago_scale 'years'
note 'general anesthesia'
topic_id 84
end
end
|
# == Schema Information
#
# Table name: ticket_templates
#
# id :integer not null, primary key
# label :string(255)
# meta :string(255)
# times_used :integer default(0), not null
# account_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# file_file_name :string(255)
# file_content_type :string(255)
# file_file_size :integer
# file_updated_at :datetime
#
class TicketTemplate < ActiveRecord::Base
attr_accessible :file, :label, :meta, :thumbnail
belongs_to :account
has_attached_file :file,
:storage => :s3,
:bucket => ENV['S3_BUCKET_NAME'],
:s3_credentials => {
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
},
:s3_protocol => :https,
:styles => { :medium => "300x300>", :thumb => "100x100>" },
:path => ":account_subdomain/:class/:attachment/:id_partition/:style/:filename"
validates_presence_of :label
validates_presence_of :file
validates_uniqueness_of :label, :scope => :account_id
Paperclip.interpolates :account_subdomain do |attachment, style|
'jamminjava'#attachment.instance.account.subdomain
end
def self.random
offset = rand(TicketTemplate.count)
rand_record = TicketTemplate.first(:offset => offset)
end
end
|
# frozen_string_literal: true
Gem::Specification.new do |spec|
spec.name = 'chronometer'
spec.version = File.read(File.expand_path('VERSION', __dir__)).strip
spec.authors = ['Samuel Giddins']
spec.email = ['segiddins@segiddins.me']
spec.summary = 'A library that makes generating Chrome trace files for Ruby programs easy.'
spec.homepage = 'https://github.com/segiddins'
spec.license = 'MIT'
spec.files = Dir[File.join(__dir__, '{lib/**/*.rb,exe/*,*.{md,txt},VERSION}')].map { |f| f.gsub(__dir__ + '/', '') }
spec.bindir = 'exe'
spec.executables = ['chronometer']
spec.require_paths = ['lib']
spec.add_runtime_dependency 'claide', '~> 1.0'
spec.add_development_dependency 'bundler', '~> 1.16'
spec.add_development_dependency 'rake', '~> 10.5'
spec.add_development_dependency 'rspec', '~> 3.7'
spec.add_development_dependency 'rubocop', '~> 0.54.0'
spec.required_ruby_version = '>= 2.1'
end
|
class AddRequestToRestaurant < ActiveRecord::Migration
def change
add_column :restaurants, :request_approve_photo ,:boolean, :default => false
end
end
|
class IdeasUser < ActiveRecord::Base
belongs_to :user
belongs_to :idea, dependent: :destroy
end
|
class VotersController < ApplicationController
# GET /voters
# GET /voters.xml
def index
@voters = Voter.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @voters }
end
end
# GET /voters/1
# GET /voters/1.xml
def show
@voter = Voter.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @voter }
end
end
# GET /voters/new
# GET /voters/new.xml
def new
@voter = Voter.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @voter }
end
end
# GET /voters/1/edit
def edit
@voter = Voter.find(params[:id])
end
# POST /voters
# POST /voters.xml
def create
@voter = Voter.new(params[:voter])
respond_to do |format|
if @voter.save
format.html { redirect_to(@voter, :notice => 'Voter was successfully created.') }
format.xml { render :xml => @voter, :status => :created, :location => @voter }
else
format.html { render :action => "new" }
format.xml { render :xml => @voter.errors, :status => :unprocessable_entity }
end
end
end
# PUT /voters/1
# PUT /voters/1.xml
def update
@voter = Voter.find(params[:id])
respond_to do |format|
if @voter.update_attributes(params[:voter])
format.html { redirect_to(@voter, :notice => 'Voter was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @voter.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /voters/1
# DELETE /voters/1.xml
def destroy
@voter = Voter.find(params[:id])
@voter.destroy
respond_to do |format|
format.html { redirect_to(voters_url) }
format.xml { head :ok }
end
end
end
|
class Redson::View
KEY_PUBLISHED_EVENTS = "published_events"
include Redson::Observable
attr_reader :target_element, :this_element,
:template_element, :model, :form
def initialize(model, target_element, template_element = nil)
@target_element = target_element
@template_element = template_element
@this_element = template_element ? template_element.clone : target_element
@this_element = `jQuery(self.this_element)`
@model = model
@model.register_observer(
self, :on => :request_started
).register_observer(
self, :on => :request_ended
).register_observer(
self, :on => :created
).register_observer(
self, :on => :updated
).register_observer(
self, :on => :unprocessable_entity
)
initialize_view_elements
initialize_observable
end
def initialize_view_elements
Redson.l.d("Template method #{self}#initialize_view_elements called. Override to do something different.")
end
def model_request_started_handler(event)
Redson.l.d("Handler #{self}#model_request_started_handler called. Override to do something different.")
end
def model_request_ended_handler(event)
Redson.l.d("Handler #{self}#model_request_ended_handler called. Override to do something different.")
end
def model_created_handler(event)
Redson.l.d("Handler #{self}#model_created_handler called. Override to do something different.")
end
def model_updated_handler(event)
Redson.l.d("Handler #{self}#model_updated_handler called. Override to do something different.")
end
def model_unprocessable_entity_handler(event)
Redson.l.d("Handler #{self}#model_uprocessable_entity_handler called. Override to do something different." )
end
def find_element!(matcher)
this_element.find!(matcher)
end
def render
target_element.append(this_element) unless target_element == this_element
end
def bind(element_matcher, to, event_name_to_update_on, notification_handler = nil)
element = this_element.find!(element_matcher)
Redson.l.d("View #{self} binds #{element_matcher} to #{model}\##{to} on #{event_name_to_update_on} with handler #{self}\##{notification_handler}");
element.on(event_name_to_update_on) do |event|
model[to] = element.value
notification_handler_method = self.method(notification_handler)
if notification_handler_method
Redson.l.i("Dispatching #{event} from #{self} to #{self}\##{notification_handler}");
notification_handler_method.call(event)
end
end
end
end |
Puppet::Type.newtype(:wlp_server_control) do
desc "Puppet type for controlling state of a Websphere Liberty Profile (ie running/stopped)"
newparam(:name, :namevar => true) do
desc "Server name to configure"
newvalues(/^[a-zA-Z0-9_]*$/)
end
newproperty(:ensure) do
desc "Set the state of server, running or stopped"
newvalues(:running, :stopped)
end
newparam(:base_path) do
desc "Installation path for WLP"
end
newparam(:wlp_user) do
desc "user that WLP is installed/running as"
end
validate do
[:base_path,:wlp_user].each do |p|
if parameters[p].nil?
raise ArgumentError, "Parameter #{p} must be provided!"
end
end
end
autorequire(:wlp_server) do
self[:name]
end
def refresh
provider.restart
end
end
|
class CourseTimesController < ApplicationController
def create
@course = load_course_from_url
@course_time = @course.course_times.new(course_time_params)
if @course_time.save
handle_if_new_top_time(@course_time)
redirect_to course_course_times_path
end
end
def index
@course = load_course_from_url
@course_times = @course.course_times.order(duration_in_seconds: :asc)
end
private
def load_course_from_url
Course.find(params[:course_id])
end
def handle_if_new_top_time(course_time)
if current_user.top_time(course_time.course_id) == course_time
new_top_time_entry = create_new_top_time_entry(course_time)
create_new_feed_update(new_top_time_entry)
end
end
def create_new_feed_update(entry)
current_user.feed_updates.create(
entry: entry,
poster_id: current_user.id
)
end
def create_new_top_time_entry(course_time)
NewTopTimeEntry.create(
course_time_id: course_time.id,
duration_in_seconds: course_time.duration_in_seconds
)
end
def course_time_params
duration = turn_time_to_seconds
{ user_id: current_user.id, duration_in_seconds: duration }
end
def turn_time_to_seconds
time = params[:course_time][:duration_in_seconds]
hours, minutes, seconds = time.split(":").map(&:to_i)
(hours * 3600) + (minutes * 60) + seconds
end
end
|
class Api::EventsController < ApplicationController
def index
cat_name = params[:category]
if cat_name
if cat = Category.find_by(category: cat_name)
@events = cat.events
render "api/events/index"
else
letter = params[:category][0].upcase
@events = Event.where("name LIKE :prefix", prefix: "#{letter}%")
if @events.length > 0
render "api/events/index"
else
render json: ["No results for that search"], status: 404
end
end
else
@events = Event.with_attached_photo
render "api/events/index"
end
end
def show
@event = Event.find_by_id(params[:id])
if @event
render "api/events/show"
else
render json: @event.errors.full_messages, status: 404
end
end
def create
@event = Event.new(event_params)
@event.organizer_id = current_user.id
@event.location_id = current_user.id
if @event.save
render "api/events/show"
else
render json: @event.errors.full_messages, status: 422
end
end
def update
@event = Event.find(params[:id])
if @event.update(event_params)
render "api/events/show"
else
render json: @event.errors.full_messages, status: 422
end
end
private
def event_params
params.require(:event).permit(:photo,
:name,
:organizer_id,
:description,
:price, :capacity,
:date, :time,
:location_id)
end
end
|
module DynamicActionable
def self.included(klass)
klass.extend ClassMethods
end
module ClassMethods
def make_list_actions_by(list, klass)
raise('Não é um enum') unless list < EnumerateIt::Base
list.keys.each do |method_name|
define_method method_name do
query = paginate(klass.send(method_name))
instance_name = "@#{klass.name.underscore.pluralize}"
instance_variable_set(instance_name, query)
respond_with :v1, instance_variable_get(instance_name)
end
end
end
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :redirect_to_users_path_if_signed_in, if: Proc.new {
user_signed_in? && controller_name == 'home' && action_name == 'index'
}
def coinbase_client
@coinbase_client ||= Coinbase::Wallet::Client.new(
api_key: ENV['COINBASE_KEY'],
api_secret: ENV['COINBASE_SECRET'],
api_url: "https://api.sandbox.coinbase.com"
)
end
private
def redirect_to_users_path_if_signed_in
redirect_to users_path
end
end
|
require 'i18n'
module Jekyll
class CategoryPage < Page
def initialize(site, category, name, layout)
@site = site
@base = site.source
@dir = I18n.transliterate(category).gsub(/\s/, '-').downcase
@name = name
self.process(@name)
self.read_yaml(File.join(@base, '_layouts'), layout)
self.data['category'] = category
self.data['title'] = site.config['post_categories'][category.downcase]['name']
end
end
class CategoryPageGenerator < Generator
safe true
def generate(site)
site.categories.keys.each do |category|
site.pages << CategoryPage.new(site, category, 'index.html', 'category-index.html')
site.pages << CategoryPage.new(site, category, 'feed.xml', 'category-feed.xml')
end
end
end
module CategoryFilter
def category_slogan(category)
site = @context.registers[:site]
entry = site.config['post_categories'][category.downcase]
entry['slogan'] or site.config['description']
end
# build the url for a given category
def category_url(category)
I18n.transliterate(category).gsub(/\s/, '-').downcase
end
# Gets the number of posts in the given category
def post_count(category)
@context.registers[:site].categories[category.downcase].size
end
end
end
I18n.enforce_available_locales = false
Liquid::Template.register_filter(Jekyll::CategoryFilter)
|
# frozen_string_literal: true
class PlayVerifier
def initialize(game:, move:)
@game = game
@move = move
end
def move
play && cell_played!
end
def playable?
!cell.played?
end
def cell?
cell.present?
end
def playable_with_neighbour_mine?
cell&.not_mines_neighbours? && playable?
end
def won?
@game.board.cells.where(played: false, kind: :void).blank?
end
def over?
won? || cell.mine?
end
def play
@play ||= @game.plays.find_or_create_by! @move
end
private
def cell
@cell ||= @game.board.cells.find_by! @move
end
def cell_played!
cell.update! played: true
end
end
|
class TwilioController < ApplicationController
#test number for tunnel is 604-210-6329
#SmsSid A 34 character unique identifier for the message. May be used to later retrieve this message from the REST API.
#AccountSid The 34 character id of the Account this message is associated with.
#From The phone number that sent this message.
#To The phone number of the recipient.
#Body The text body of the SMS message. Up to 160 characters long.
#http://www.twilio.com/docs/api/twiml/sms/twilio_request
def text
logger.info "SMS REQUEST FROM #{params['From']} to #{params["To"]} in #{params['FromCity']}, #{params['FromState']}: #{params['Body']}"
@sender = User.find_by_phone( params['From'] )
if @sender.nil?
@sender = User.new(:phone => params['From'], :email => params['Body'].strip)
if @sender.save
render :nothing => true, :status => 200
else
@message = ""
@sender.errors.each do |name, error|
@message = @message + name.to_s + " " + error + "\n"
end
render :xml => {:Sms => @message }.to_xml(:root => 'Response')
end
else
@message = "You have already signed up with email: #{@sender.email}, access your dashboard: #{ApplicationController.get_hostname}#{dashboard_path(:auth_token => @sender.authentication_token)}"
render :xml => {:Sms => @message }.to_xml(:root => 'Response')
end
end
def voice
logger.info "Phone call FROM #{params['From']} to #{params["To"]} in #{params['FromCity']}, #{params['FromState']}: #{params['Body']}"
if params['appointment_id']
@appointment = Appointment.find( params['appointment_id'] )
if @appointment
render :xml => @appointment
else
render :xml => {:Say => "You have an upcoming appointment" }.to_xml(:root => 'Response')
end
else
render :xml => {:Say => "You have reached healthcan.net, to signup, text your email address to this number" }.to_xml(:root => 'Response')
end
end
end
|
class AddUserReferencesToApiClients < ActiveRecord::Migration[5.1]
def change
add_reference :api_clients, :user, foreign_key: true
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe DataSourceContributor do
fixtures :users, :data_sources, :data_source_contributors
before(:each) do
@aaron_user = users(:aaron)
@quentin_user = users(:quentin)
@birds_ds = data_sources(:birds_nhm)
@bees_ds = data_sources(:bees_nhm)
@data_source_contributor = DataSourceContributor.new({:user => @aaron_user, :data_source => @bees_ds})
end
it "should be valid" do
@data_source_contributor.should be_valid
end
it "should require user" do
@data_source_contributor.user = nil
@data_source_contributor.should_not be_valid
end
it "should require data_source" do
@data_source_contributor.data_source = nil
@data_source_contributor.should_not be_valid
end
it "user and data source combindation should be unique" do
lambda {
DataSourceContributor.create({:user => @aaron_user, :data_source => @bees_ds})
DataSourceContributor.create({:user => @aaron_user, :data_source => @bees_ds})
}.should raise_error
end
# it "should not delete last contributor for a source"
# lambda {
# ds = DataSource.create({:title => 'Example 686', :description => 'Description',
# :data_url => 'http://example.com/data_url.xml', :data_zip_compressed => false, :metadata_url => nil, :logo_url => 'http://example.com/images/logo.png')
# @data_source_contributor.destroy
# }.should raise_error
# end
end |
class Match
attr_accessor :home_team_name, :home_team_score, :away_team_name, :away_team_score, :date
def initialize(home_team_name, home_team_score, away_team_name, away_team_score, date)
@home_team_name = home_team_name
@home_team_score = home_team_score
@away_team_name = away_team_name
@away_team_score = away_team_score
@date = date
end
end
|
describe ::PPC::API::Qihu::Keyword do
auth = $qihu_auth
test_plan_id = ::PPC::API::Qihu::Plan::ids( auth )[:result][0].to_i
test_group_id = ::PPC::API::Qihu::Group::search_id_by_plan_id( auth, test_plan_id )[:result][0][:group_ids][0].to_i
test_keyword_id = 0
it 'can search keyword id by group id' do
response = ::PPC::API::Qihu::Keyword::search_id_by_group_id( auth, test_group_id )
is_success( response)
expect( response[:result].class ).to eq Array
end
it 'can search keyword by group id' do
response = ::PPC::API::Qihu::Keyword::search_by_group_id( auth, test_group_id )
is_success( response)
expect( response[:result].class ).to eq Array
end
it 'can add keyword' do
keyword1 = { group_id:test_group_id, keyword:"testKeyword1",price:0.3,match_type:"exact"}
response = ::PPC::API::Qihu::Keyword::add( auth, keyword1)
p response
is_success( response )
test_keyword_id = response[:result][0][:id]
end
it 'can update keyword' do
keyword = { id:test_keyword_id, price:0.4 }
response = ::PPC::API::Qihu::Keyword::update( auth, keyword )
is_success( response )
end
it 'can get keyword' do
response = ::PPC::API::Qihu::Keyword::get( auth, [test_keyword_id] )
is_success( response )
expect( response[:result][0].keys ).to include( :id, :status )
end
it 'can get status' do
response = ::PPC::API::Qihu::Keyword::status( auth, [test_keyword_id] )
is_success( response )
end
it 'can delete keyword' do
response = ::PPC::API::Qihu::Keyword::delete( auth, [test_keyword_id] )
is_success( response )
end
end
|
require 'spec_helper'
require_relative 'configuration/shared_example_for_boolean_writer'
RSpec.describe Bambooing::Configuration do
describe '#dry_run_mode=' do
let(:writer) { :dry_run_mode= }
let(:reader) { :dry_run_mode }
it_behaves_like 'boolean writer'
end
describe '#exclude_time_off=' do
let(:writer) { :exclude_time_off= }
let(:reader) { :exclude_time_off }
it_behaves_like 'boolean writer'
end
describe '.load_from_environment' do
let!(:host) { ENV['BAMBOOING_HOST'] }
let!(:x_csrf_token) { ENV['BAMBOOING_X_CSRF_TOKEN'] }
let!(:session_id) { ENV['BAMBOOING_SESSION_ID'] }
let!(:employee_id) { ENV['BAMBOOING_EMPLOYEE_ID'] }
let!(:dry_run_mode) { ENV['BAMBOOING_DRY_RUN_MODE'] }
let!(:exclude_time_off) { ENV['BAMBOOING_EXCLUDE_TIME_OFF'] }
it 'sets every configuration variable to its corresponding environment variable' do
ENV['BAMBOOING_HOST'] = 'https://my_company.bamboohr.com'
ENV['BAMBOOING_X_CSRF_TOKEN'] = 'a_csrf_token'
ENV['BAMBOOING_SESSION_ID'] = 'a_session_id'
ENV['BAMBOOING_EMPLOYEE_ID'] = 'a_employee_id'
ENV['BAMBOOING_DRY_RUN_MODE'] = 'true'
ENV['BAMBOOING_EXCLUDE_TIME_OFF'] = 'true'
described_class.load_from_environment!
configuration = Bambooing.configuration
expect(configuration.host).to eq('https://my_company.bamboohr.com')
expect(configuration.x_csrf_token).to eq('a_csrf_token')
expect(configuration.session_id).to eq('a_session_id')
expect(configuration.employee_id).to eq('a_employee_id')
expect(configuration.dry_run_mode).to eq(true)
expect(configuration.exclude_time_off).to eq(true)
end
after(:each) do
ENV['BAMBOOING_HOST'] = host
ENV['BAMBOOING_X_CSRF_TOKEN'] = x_csrf_token
ENV['BAMBOOING_SESSION_ID'] = session_id
ENV['BAMBOOING_EMPLOYEE_ID'] = employee_id
ENV['BAMBOOING_DRY_RUN_MODE'] = dry_run_mode
ENV['BAMBOOING_EXCLUDE_TIME_OFF'] = exclude_time_off
end
end
end
|
module Emarsys
module Broadcast
class ValidationError < StandardError
attr_reader :errors
def initialize(message, errors)
super(message)
@errors = errors
end
end
end
end
|
module Inputs
class PatchAvailability < Types::BaseInputObject
graphql_name "PatchAvailabilityInput"
description "Properties for an patching the availability of a user"
argument :available, Boolean, required: false
argument :availability_note, String, required: false
end
end
|
# Practice defining instance methods on a class
# Practice defining instance methods that use the self keyword
# Learn about monkey patching
# In this lab, you will be adding a few instance methods to Ruby's String class
# The practice of adding methods to or altering Ruby's built-in classes is called
# monkey patching
# The string class is just like any other class, however, is native to, or included in, Ruby. So
# we can add or change methods in the String class just like we would in any of the classes that we define ourselves
# Monkey Patching
# is the practice of adding methods to or altering Ruby's build in classes
# Monkey patching should almost never be used in real applications
|
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'asciibook/version'
Gem::Specification.new do |spec|
spec.name = "asciibook"
spec.version = Asciibook::VERSION
spec.authors = ["Rei"]
spec.email = ["chloerei@gmail.com"]
spec.summary = %q{}
spec.description = %q{}
spec.homepage = ""
spec.license = "MIT"
spec.files = Dir.glob('{bin,exe,lib,templates,theme,book_template}/**/*') + %w(LICENSE.txt README.adoc)
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_runtime_dependency "asciidoctor", "~> 2.0"
spec.add_runtime_dependency "asciidoctor-mathematical", "~> 0.3"
spec.add_runtime_dependency "mathematical", "1.6.14"
spec.add_runtime_dependency "liquid", "~> 5.0"
spec.add_runtime_dependency "gepub", "~> 1.0"
spec.add_runtime_dependency "mercenary", "~> 0.4"
spec.add_runtime_dependency "rouge", "~> 4.0"
spec.add_runtime_dependency "nokogiri", "~> 1.0"
spec.add_development_dependency "rake"
end
|
require 'digest/sha1'
module Timetable
class Preset
attr_reader :name
COLLECTION = "presets"
def self.find(name)
return if ENV["RACK_ENV"] == 'test'
Database.execute(COLLECTION) do |db|
db.find("name" => name)
end
end
def initialize(course, yoe, year, modules = nil)
@course = course
@yoe = yoe
@year = year
@modules = modules.map(&:to_s)
@ignored = modules_ignored
# Return early if the user needs no preset
return if @ignored.empty?
@name = get_preset_name
save
end
private
# Return the modules that the user has chosen to ignore,
# given the ones they've chosen to take
def modules_ignored
return [] if @modules.nil?
mods = Config.read("course_modules") || []
mods = mods[@course] || []
mods = mods[@year] || []
# Convert everything to string to make sure we can compare
# the elements to the ones in @modules, which are strings
mods.map!(&:to_s)
# Return the set difference between all the modules for the
# given (course, yoe) pair and the modules chosen by the user
ignored = mods - @modules
ignored.sort
end
def get_preset_name
return if @ignored.nil?
salted = @course.to_s + @yoe.to_s + @ignored.join
Digest::SHA1.hexdigest(salted)[0,5]
end
# Check whether the preset is already present in our MongoHQ
# instance, and save it to the database if it isn't
def save
return if ENV['RACK_ENV'] == 'test' || @name.nil?
Database.execute(COLLECTION) do |db|
unless db.exists?("name" => @name)
db.insert(
"name" => @name,
"course" => @course,
"yoe" => @yoe,
"ignored" => @ignored
)
end
end
end
end
end
|
require 'set'
module Cocoadex
# A model of a Cocoa API class or protocol
class Class < Entity
TEMPLATE_NAME=:class
attr_reader :description, :overview
def properties
@properties ||=[]
end
def tasks
@tasks ||= []
end
def methods
@methods ||= ::Set.new
end
def class_methods
methods.select{|m| m.scope == :class }
end
def instance_methods
methods.select{|m| m.scope == :instance }
end
def parents
@parents ||= []
end
def type
"Class"
end
def origin
parents.join(' > ')
end
def parse doc
@name = doc.css('body a').first['title']
logger.debug(" Parsing #{@name}")
@description = doc.css('meta#description').first['content']
# @overview = doc.css(".zClassDescription p.abstract").first.text
@overview = doc.css(".zClassDescription").first.children.map {|n| n.text.sub("Overview","") }
specs = doc.css("div.zSharedSpecBoxHeadList").first.css('a')
@parents = specs.map {|node| node.text} if specs
parse_properties(doc)
# parse_tasks(doc)
parse_methods(doc)
end
def parse_methods doc
[:class, :instance].each do |selector|
nodes = doc.css("div.#{selector}Method")
unless nodes.empty?
methods.merge(nodes.map {|n| Method.new(self, selector, n)})
end
end
end
def parse_properties doc
@properties = doc.css("div.propertyObjC").map do |prop|
Property.new(self, prop)
end
end
def parse_tasks doc
@tasks = {}
doc.css('ul.tooltip').each do |list|
key = list.previous.text
@tasks[key] = []
list.css('li span.tooltip').each do |prop|
@tasks[key] << {
:name => strip(prop.css('a').first.text),
:abstract => prop.css('.tooltipicon').first['data-abstract']
}
end
end
@tasks
end
end
end |
class RenameColumnsOfPhoneNumberRange < ActiveRecord::Migration
def change
# I'm not going to revert all existing entries here.
add_column :phone_number_ranges, :phone_number_rangeable_type, :string
add_column :phone_number_ranges, :phone_number_rangeable_id, :integer
remove_column :phone_number_ranges, :tenant_id
end
end
|
Rails.application.routes.draw do
get 'replays/index'
get 'replays/new'
get 'replays/create'
get 'replays/destroy'
resources :replays, only: [:index, :new, :create, :destroy]
root 'welcome#index'
get 'welcome/index'
post 'auth/steam/callback' => 'welcome#auth_callback'
get '/logout', to: 'welcome#logout'
resources :matches do
collection do
get :status_update
get :enter_slot
get :clear_slot
end
end
end
|
class FileUploadTaskResponse < Dynamic
mount_uploaders :file, GenericFileUploader
def class_name
'Dynamic'
end
def self.max_size
UploadedFile.get_max_size({ env: ENV['MAX_UPLOAD_SIZE'], config: CheckConfig.get('uploaded_file_max_size', nil, :integer), default: 20.megabytes })
end
# Re-define class variables from parent class
@pusher_options = Dynamic.pusher_options
@custom_optimistic_locking_options = Dynamic.custom_optimistic_locking_options
end
|
# frozen_string_literal: true
class CargoTrain < Train
include Manufacturer
TYPE = :cargo
def initialize(number)
super(TYPE, number)
end
end
|
module Types
class QueryType < Types::BaseObject
# Add root-level fields here.
# They will be entry points for queries on your schema.
field :all_items, [ItemType], null: false,
description: "Returns the list of items in the inventory"
def all_items
Item.all
end
field :item, ItemType, null: false do
description "Returns the particular item in the inventory"
argument :id, ID, required:true
# argument :name, String, required:false
end
def item(id:)
Item.find(id)
# Item.where(:id => id)
end
field :variant, VariantType, null: false do
description "Returns the particular variant in the inventory"
argument :id, ID, required:true
# argument :name, String, required:false
end
def variant(id:)
Variant.find(id)
# Item.where(:id => id)
end
field :product, ProductType, null: false do
description "Returns the particular product in the inventory"
argument :id, ID, required:true
# argument :name, String, required:false
end
def product(id:)
Product.find(id)
# Item.where(:id => id)
end
field :all_products, [ProductType], null: false,
description: "Returns the list of products sold by the merchant"
def all_products
Product.all
end
field :all_variants, [VariantType], null: false,
description: "Returns the list of variants sold by the merchant"
def all_variants
Variant.all
end
field :all_locations, [LocationType], null: false,
description: "Returns the list of locations of the merchant"
def all_locations
Location.all
end
field :all_inventory_item_conditions, [InventoryItemConditionType], null: false,
description: "Returns the list of inventory item conditions"
def all_inventory_item_conditions
InventoryItemCondition.all
end
field :all_inventory_item_states, [InventoryItemStateType], null: false,
description: "Returns the list of inventory item states"
def all_inventory_item_states
InventoryItemState.all
end
field :all_item_variants, [ItemVariantType], null: false,
description: "Returns the list of item variants bindingsh"
def all_item_variants
ItemVariant.all
end
field :show_inventory, [InventoryItemType], null: false,
description: "Returns the list of all items in inventory"
def show_inventory
InventoryItem.all
end
field :show_inventory_per_location, [InventoryItemType], null: false do
description "Returns the list of all items in inventory"
argument :id, ID, required:true
end
def show_inventory_per_location(id:)
InventoryItem.all.where(:location_id => id)
end
field :me, Types::AdminType, null: true
def me
context[:current_admin]
end
end
end
|
# frozen_string_literal: true
RSpec.describe RailsParseHead do
context 'RailsParseHead by fetch' do
let(:rph) { RailsParseHead.fetch('https://github.com') }
it 'Invalid URL' do
error = raise_error(HTTP::ConnectionError)
expect { RailsParseHead.fetch('http://github.c') }.to error
end
it 'Invalid schema URL' do
error = raise_error(HTTP::Request::UnsupportedSchemeError)
expect { RailsParseHead.fetch('www://github.com') }.to error
end
it 'Has a title' do
title = 'The world’s leading software development platform · GitHub'
expect(rph.title).to eql(title)
end
it 'Has metas' do
expect(rph.metas).to be_an_instance_of(Array)
expect(rph.metas.count).to be_positive
end
it 'Has links' do
expect(rph.links).to be_an_instance_of(Array)
expect(rph.links.count).to be_positive
end
end
context 'RailsParseHead by parse' do
dirname = File.dirname(__FILE__)
let(:invalid_file) do
body = File.open("#{dirname}/files/invalid.html", 'r', &:read)
RailsParseHead.parse(body)
end
let(:valid_file) do
body = File.open("#{dirname}/files/valid.html", 'r', &:read)
RailsParseHead.parse(body)
end
it 'Has an empty title' do
expect(invalid_file.title).to eql('')
end
it 'Has title' do
expect(valid_file.title).to eql('Test')
end
it 'Has metas' do
expect(valid_file.metas).to be_an_instance_of(Array)
expect(valid_file.metas.count).to be_positive
end
it 'Has not links' do
expect(valid_file.links).to be_an_instance_of(Array)
expect(valid_file.links.count).to be_zero
end
end
end
|
class AddFiledToUser < ActiveRecord::Migration
def change
add_column :users, :email, :string
add_column :users, :salary, :integer
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
after_filter :set_access_control_headers
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = "*"
headers['Access-Control-Request-Method'] = %w{GET POST OPTIONS}.join(",")
end
def logged_in?
session[:user_id]
end
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
end
|
# == Schema Information
#
# Table name: characters
#
# id :integer not null, primary key
# name :string(255)
# address :string(255)
# latitude :string(255)
# longitude :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# gmaps :boolean
#
class Character < ActiveRecord::Base
attr_accessible :name, :address, :latitude, :longitude
acts_as_gmappable
def gmaps4rails_address
#describe how to retrieve the address from your model, if you use directly a db column, you can dry your code, see wiki
#"#{self.street}, #{self.city}, #{self.country}"
address
end
def gmaps4rails_marker_picture
{
"rich_marker" => "<div class='my-marker'>
<img height='30' width='30' src='https://secure.gravatar.com/avatar/ankithbti007@gmail.com'/></div>"
}
end
# def gmaps4rails_infowindow
# "<h1>#{name}</h1>"
# end
# def gmaps4rails_title
# # add here whatever text you desire
# "<h4>Title</h4>"
# end
# def gmaps4rails_marker_picture
# {
# "picture" => "/images/#{name}.png",
# "width" => 20,
# "height" => 20,
# "marker_anchor" => [ 5, 10],
# "shadow_picture" => "/images/morgan.png" ,
# "shadow_width" => "110",
# "shadow_height" => "110",
# "shadow_anchor" => [5, 10],
# }
# end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
#filter_parameter_logging :password
helper_method :current_user
before_filter :set_locale, :strict_transport_security
private
def strict_transport_security
#response.headers["Strict-Transport-Security"] = 'max-age=31536000; includeSubDomains'
response.headers["Strict-Transport-Security"] = 'max-age=0; includeSubDomains'
end
=begin
def set_locale
session[:locale] ||= extract_locale_from_header
return switch_locale_and_redirect_to_referer if params[:locale].present?
@locale = Locale.new session[:locale]
I18n.locale = @locale.current
end
=end
def set_locale
session[:locale] = params[:locale]
session[:locale] ||= extract_locale_from_header
# return switch_locale_and_redirect_to_referer if params[:locale].present?
@locale = Locale.new session[:locale]
I18n.locale = @locale.current
end
# def set_locale
# I18n.locale = params[:locale] || I18n.default_locale
# end
def switch_locale_and_redirect_to_referer
session[:locale] = params[:locale]
redirect_to request.referer
end
def extract_locale_from_header
locale = request.env['HTTP_ACCEPT_LANGUAGE'] || I18n.default_locale.to_s
locale.scan(/^[a-z]{2}/).first
end
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.record
end
def alternate_to url
@locale.alternate_url = url
end
end
|
class GoalSerializer < ActiveModel::Serializer
attributes :id, :name, :completed, :category, :point_value
has_one :user
end
|
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation, :role, :profile_url, :responses, :cell, :on_call, :image, :image_file_name, :image_content_type
has_attached_file :image, :default_url => "/assets/missing.png"
has_many :responses
has_many :issues, :through => :responses
has_many :votes
has_many :issues, :through => :votes
has_many :issues
has_secure_password
validates :password, :presence => { :on => :create }
has_many :identities
validates :email, :name, :presence => true
validates_uniqueness_of :email, :message => "Sorry, that e-mail address already belongs to an existing account."
USER_ROLES = {
:admin => 0,
:student => 10
}
def currently_assigned_issue
Issue.where(:assignee_id => self.id).first
end
def set_as_admin
self.role = USER_ROLES[:admin]
end
def set_as_student
self.role = USER_ROLES[:student]
end
def admin?
true if self.role_name == :admin
end
def owns?(issue)
true if self.id == issue.user_id
end
def self.admin
User.where(:role => USER_ROLES[:admin])
end
def self.user_roles
USER_ROLES
end
def self.notify_on_call_admins
self.admin.each do |admin|
TwilioWrapper.new.admin_sms(admin,'new_issues') if admin.notifiable?
end
end
def notifiable?
self.on_call? && self.has_cell?
end
def on_call?
true if self.on_call == true
end
def is_available?
true if Issue.not_closed.find_by_assignee_id(self.id).nil? && self.on_call?
end
def role_name
User.user_roles.key(self.role)
end
def can_edit?(issue)
true if admin? || owns?(issue)
end
def can_destroy?(issue)
true if admin? || owns?(issue)
end
def can_resolve?(issue)
true if owns?(issue)
end
def can_assign?(issue)
true if Issue.not_closed.collect { |i| i.assignee_id }.include?(self.id) == false
end
def can_unassign?(issue)
true if issue.assignee_id == self.id || self.admin? || self.owns?(issue)
end
def can_mark_as_helped?(issue)
true if issue.assignee_id == self.id || self.admin?
end
def can_upvote?(issue)
true if issue.user_id != self.id && issue.votes.collect {|vote| vote.user_id}.include?(self.id) == false
end
def can_votedown?(issue)
true if issue.votes.collect {|vote| vote.user_id}.include?(self.id) == true
end
def has_identity?(auth_provider)
identity_array = self.identities.collect {|identity| identity.provider}
identity_array.include?(auth_provider)
end
def has_cell?
true unless self.cell == "" || self.cell.nil?
end
# def can?(issue, action)
# true if (self.role == USER_ROLES[:admin] || issue.user_id == self.id)
# end
# current_user.can?(edit, object)
def self.create_from_hash(hash)
create(:name => hash['info']['name'])
end
def can_edit_delete_profile?(user)
true if self.id == user.id || self.admin?
end
def has_open_issue?
true unless self.issues.not_closed.empty?
end
def authenticated_with_github?
true if self.identities.first.present?
end
def assigned_issues
Issue.not_closed.where(:assignee_id => self.id)
end
end
|
# 3.Now, using the same array from #2, use the select method to extract
# all odd numbers into a new array.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = numbers.select { |num| num.odd? }
puts odd_numbers
# or using modulo
odd_numbers = numbers.select { |num| num if num % 2 == 1}
puts odd_numbers |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Board, type: :model do
let(:valid_params) { { name: 'test' } }
context 'validations' do
it { expect(described_class.new).not_to be_valid }
it { expect(described_class.new(valid_params)).to be_valid }
it 'fails on duplicate name' do
create :board, name: 'name'
expect(build(:board, name: 'name')).not_to be_valid
end
end
end
|
##
# License 是许可证管理的封装类。
class Wechat::ShakeAround::License
extend Wechat::Core::Common
extend Wechat::ShakeAround::Common
extend Wechat::ShakeAround::Material
##
# 上传图片素材
# http://mp.weixin.qq.com/wiki/5/e997428269ff189d8f9a4b9e177be2d9.html
#
# Return hash format if success:
# {
# data: { pic_url: <LICENSE_LINK> },
# errcode: 0,
# errmsg: 'success.'
# }
#
# media 图片完整路径。
def self.create(access_token, media)
assert_present! :access_token, access_token
assert_present! :media, media
upload access_token, media, 'license'
end
end
|
class AddLicenseExpirationDate < ActiveRecord::Migration
def change
add_column :people, :driver_license_exp_date, :datetime
end
end
|
#MethodsExercise----------------------------------
#1
def greeting(name)
puts "Hey #{name}"
end
puts greeting("Tom")
#3
def multiply(x, y)
x*y
end
puts multiply(2,3)
#5
def scream(words)
puts words = words + "!!!!"
end
scream("Yo")
#FlowControlExercise-----------------------------
#2
def caps(word)
if word.length >= 10
puts word.upcase
else
puts "Needs more letters!"
end
end
caps("ttretretetretre")
#3
puts "Give me a number: "
input_num = gets.chomp.to_i
if input_num > 100
puts "Over 100"
elsif input_num <= 100 && input_num > 50
puts "between 51 and 100"
elsif input_num <= 50 && input_num > 0
puts "between 0 and 50"
else
puts "Negative number"
end
#5
puts "Give me a number: "
input_num = gets.chomp.to_i
case
when input_num > 100
puts "Over 100"
when input_num > 50
puts "between 51 and 100"
when input_num > 0
puts "between 0 and 50"
else
puts "Negative number"
end
#LoopsandIterationsExercise ---------------------
#2
loop do
puts "Want to continue?"
order = gets.chomp
if order == "STOP"
break
end
end
#3
movie_array = ["interstellar", "billiemadinson"]
movie_array.each_with_index do |movie, index|
puts "#{movie} in position #{index}"
end
#4
def tozero(x)
if x <= 0
puts "Zero or neg number"
else
puts x
tozero(x-=1)
end
end
#ArrayExercises------------------------------
#7
o_array = [1, 2, 3, 4, 5]
new_array = o_array.map{|x| x+2}
p o_array
p new_array
#HashExercises----------------------------------
#1
family = { uncles: ["bob", "joe", "steve"],
sisters: ["jane", "jill", "beth"],
brothers: ["frank","rob","david"],
aunts: ["mary","sally","susan"]}
imm_family = family.select{|key, value| key == :sisters || key == :brothers}
imm_family = imm_family.flatten
p imm_family
#3
compounds = [story: time, table: cloth, happy: days]
p compounds.keys
p compounds.values
p compounds.keys + compunds.values
#6
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live',
'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide',
'flow', 'neon']
anagram = {};
words.each do |x|
letters = x.split('').sort.join
if anagram.has_key?(letters)
anagram[letters].push(x)
else
anagram[letters] = [x]
end
end
anagram.each_value do |value|
puts "-----------"
p value
end
|
# A line of credit product. This is like a credit card except theres no card
class CreditLine
attr_reader :interest_charge
def initialize(apr = 5.0, credit_limit = 1000)
@apr = apr
@credit_limit = credit_limit
@payments_due = 0
@interest_charge = 0
@days = 0
end
def balance
# this get the principle balance rounded to the nearest 2 decimal places
payments_due.round(2)
end
def draw_credit(draw_amount)
total = payments_due + draw_amount
return false if credit_limit < total
@payments_due = total
end
def advance(days)
return false if days < 0
total_days = @days + days
days_over_30_days = total_days - 30
charge(days_over_30_days, days)
@days
end
def calculate_interest(days_of_interest)
payments_due * apr / 100 / 365 * days_of_interest
end
def make_payment(amount)
# paydown your balance
@payments_due -= amount
end
private
attr_reader :payments_due, :credit_limit, :apr
def charge(days_over_30_days, days)
if days_over_30_days >= 0
months_past, remainder_days = days_over_30_days.divmod(30)
calculate_payment(months_past)
@interest_charge += calculate_interest(remainder_days)
@days = remainder_days
else
@interest_charge += calculate_interest(days)
@days += days
end
end
def calculate_payment(months)
@payments_due += calculate_interest((30 - @days))
(0...months).each do
@payments_due += calculate_interest(30)
end
@payments_due += interest_charge
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe '#set_up_user' do
before(:all) do
@user = User.new(
first_name: 'Bill',
last_name: 'Miller',
email: 'bill.miller@example.com',
password: 'password'
)
@user.set_up_user
end
it "sets the credit_limit to $1000" do
expect(@user.credit_limit).to eq(Money.new(100000))
end
it "sets the balance to $0" do
expect(@user.balance).to eq(Money.new(0))
end
it "sets the period_start to the beginning of today" do
beginning_of_day = Time.zone.now.beginning_of_day
expect(@user.period_start).to eq(beginning_of_day)
end
end
describe '#update_balance' do
let(:user) {
User.create(
first_name: 'Bill',
last_name: 'Miller',
email: 'bill.miller@example.com',
password: 'password'
)
}
context "when withdrawing" do
before do
user.update_balance(Money.new(-20000))
end
it "reduces the credit limit by the amount" do
expect(user.credit_limit).to eq(Money.new(80000))
end
it "increases the balance by the amount" do
expect(user.balance).to eq(Money.new(-20000))
end
end
context "when paying" do
before do
user.update_balance(Money.new(20000))
end
it "increases the credit limit by the amount" do
expect(user.credit_limit).to eq(Money.new(120000))
end
it "reduces the balance by the amount" do
expect(user.balance).to eq(Money.new(20000))
end
end
end
describe '#valid_transaction?' do
let(:user) {
User.create(
first_name: 'Bill',
last_name: 'Miller',
email: 'bill.miller@example.com',
password: 'password'
)
}
context "when trying to withdraw more than credit limit" do
it "returns false" do
expect(user.valid_transaction?(Money.new(-200000))).to eq(false)
end
end
context "when trying to pay more than balance" do
it "returns false" do
expect(user.valid_transaction?(Money.new(20000))).to eq(false)
end
end
context "when not overdrawing or overpaying" do
it "returns true" do
expect(user.valid_transaction?(Money.new(-20000))).to eq(true)
end
end
end
end
|
require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::Parameter do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
describe 'correct init' do
subject { operation.parameters.first }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
it do
expect(subject).not_to be nil
expect(subject.object_reference).to eq '#/paths/~1pets/get/parameters/0'
expect(subject.root.object_id).to be root.object_id
end
end
describe 'attributes' do
subject { operation.parameters.first }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
it do
results = {
name: 'tags',
in: 'query',
description: 'tags to filter by',
required: false,
style: 'form',
}
results.each { |k, v| expect(subject.send(k)).to eq v }
expect(subject.allow_empty_value).to eq true
end
end
describe 'header support' do
subject { path_item.parameters.last }
let(:paths) { root.paths }
let(:path_item) { paths.path['/animals/{id}'] }
it do
results = {
name: 'token',
in: 'header',
description: 'token to be passed as a header',
required: true,
style: 'simple',
}
results.each { |k, v| expect(subject.send(k)).to eq v }
expect(subject.schema.type).to eq 'integer'
end
end
end
|
module WithingsSDK
class Base
# @return [Hash]
attr_reader :attrs
# Initializes a new object with attributes for the values passed to the constructor.
#
# @param attrs [Hash]
# @return [WithingsSDK::Base]
def initialize(attrs = {})
@attrs = attrs || {}
@attrs.each do |key, value|
self.class.class_eval { attr_reader key }
instance_variable_set("@#{key}", value)
end
end
end
end
|
require "test_helper"
class FightsControllerTest < ActionDispatch::IntegrationTest
setup do
@fight = fights(:one)
end
test "should get index" do
get fights_url, as: :json
assert_response :success
end
test "should create fight" do
assert_difference('Fight.count') do
post fights_url, params: { fight: { } }, as: :json
end
assert_response 201
end
test "should show fight" do
get fight_url(@fight), as: :json
assert_response :success
end
test "should update fight" do
patch fight_url(@fight), params: { fight: { } }, as: :json
assert_response 200
end
test "should destroy fight" do
assert_difference('Fight.count', -1) do
delete fight_url(@fight), as: :json
end
assert_response 204
end
end
|
Rails.application.routes.draw do
root 'breweries#index'
#get 'kaikki_bisset', to: 'beers#index'
#get 'ratings', to: 'ratings#index'
#get 'ratings/new', to:'ratings#new'
#post 'ratings', to: 'ratings#create'
resources :ratings, only: [:index, :new, :create, :destroy]
resources :beers
resources :breweries
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
# @param {String} moves
# @return {Boolean}
def judge_circle(moves)
x = 0
y = 0
moves.each_char do |char|
if char == 'U'
y += 1
elsif char == 'D'
y -= 1
elsif char =='R'
x += 1
elsif char == 'L'
x -= 1
end
end
return (x == 0 && y == 0)
end
|
$: << __dir__ + '/../lib'
require 'minitest/autorun'
require 'vcr'
require 'leboncoin'
FIXTURES_DIR = __dir__ + '/fixtures'
VCR.configure do |conf|
conf.cassette_library_dir = FIXTURES_DIR
conf.hook_into :faraday
end
class LeboncoinTest < MiniTest::Unit::TestCase
def test_search_raw
url = 'http://www.leboncoin.fr/annonces/offres/ile_de_france/?f=a&th=1&q=rockrider+8.1'
html = VCR.use_cassette('rockrider81') do
Leboncoin.search_raw(url)
end
assert_equal Leboncoin::HTML_ENCODING, html.encoding
end
def test_search_raw_error
exc = assert_raises Leboncoin::Error do
VCR.use_cassette('404') do
Leboncoin.search_raw('http://notfound')
end
end
assert_match /: 404$/, exc.message
end
def test_parse_results
html = File.read(FIXTURES_DIR + '/results.html', {encoding: Leboncoin::HTML_ENCODING})
results = Leboncoin.parse_results(html)
assert_equal 13, results.length
res = results[1]
assert_equal "Rockrider 8.1", res[:title]
assert_kind_of Time, res[:time]
assert_equal 300, res[:price]
assert_equal "http://www.leboncoin.fr/velos/945229630.htm?ca=12_s", res[:url]
assert_equal "http://img2.leboncoin.fr/images/a2d/a2d0bd1149dab442236b74f135795e4082d8ca80.jpg", res[:photo_url]
end
def test_parse_results_without_price
html = File.read(FIXTURES_DIR + '/results_without_price.html', {encoding: Leboncoin::HTML_ENCODING})
results = Leboncoin.parse_results(html)
res = results.first
assert_equal "VTT Rockrider 8.1 Volé, J'ALERTE", res[:title] # sanity check
assert_nil res[:price]
end
def test_parse_results_without_photo
html = File.read(FIXTURES_DIR + '/results_without_photo.html', {encoding: Leboncoin::HTML_ENCODING})
results = Leboncoin.parse_results(html)
res = results[2]
assert_equal "IPhone 6 128 go", res[:title] # sanity check
assert_nil res[:photo_url]
end
def test_parse_results_with_high_price
html = File.read(FIXTURES_DIR + '/results_with_high_price.html', {encoding: Leboncoin::HTML_ENCODING})
results = Leboncoin.parse_results(html)
res = results.first
assert_equal "Appartement 3 pièces 57m² Chanteloup-en-Brie", res[:title]
assert_equal 205000, res[:price]
end
end
class LeboncoinResultTimeTest < MiniTest::Unit::TestCase
def test_parse
t = Time.now
d, m, y = t.day, t.mon, t.year
assert_lbc_time [6,11,y,17,59], "6 nov, 17:59"
assert_lbc_time [d,m,y,15,10], "Aujourd'hui, 15:10"
assert_lbc_time [d-1,m,y,22,43], "Hier, 22:43"
assert_lbc_time [27,12,y,21,57], "27 déc, 21:57"
end
def test_parse_invalid_format
exc = assert_raises Leboncoin::Error do
Leboncoin::ResultTime.parse("27 INVALID 21:57")
end
assert_match /format: 27/, exc.message
exc = assert_raises Leboncoin::Error do
Leboncoin::ResultTime.parse("???")
end
assert_match /format: \?\?\?/, exc.message
end
private
def assert_lbc_time(expected, str)
t = Leboncoin::ResultTime.parse(str)
actual = [t.day, t.mon, t.year, t.hour, t.min]
assert_equal expected, actual
end
end
|
RSpec.describe CoursePolicy do
subject { described_class.new(user, record) }
let(:record) { Course.new }
context 'student' do
let(:user) { FactoryBot.create :user }
it { is_expected.to permit_actions(%w[index show]) }
it { is_expected.to forbid_edit_and_update_actions }
it { is_expected.to forbid_new_and_create_actions }
it { is_expected.to forbid_action(:destroy) }
end
context 'instructor' do
let(:user) { FactoryBot.create :user, role: 1 }
it { is_expected.to permit_actions(%w[index show]) }
it { is_expected.to forbid_edit_and_update_actions }
it { is_expected.to forbid_new_and_create_actions }
it { is_expected.to forbid_action(:destroy) }
end
context 'admin with no instructors' do
let(:user) { FactoryBot.create :user, role: 2 }
it { is_expected.to forbid_new_and_create_actions }
it { is_expected.to forbid_edit_and_update_actions }
it { is_expected.to permit_actions(%w[index destroy show]) }
end
end
|
module Alf
module Types
#
# Encapsulates a Renaming information
#
class Renaming
# @return [Hash] a renaming mapping as AttrName -> AttrName
attr_reader :renaming
#
# Creates a renaming instance
#
# @param [Hash] a renaming mapping as AttrName -> AttrName
#
def initialize(renaming)
@renaming = renaming
end
#
# Coerces `arg` to a renaming
#
def self.coerce(arg)
case arg
when Renaming
arg
when Hash
h = Tools.tuple_collect(arg){|k,v|
[Tools.coerce(k, AttrName), Tools.coerce(v, AttrName)]
}
Renaming.new(h)
when Array
coerce(Hash[*arg])
else
raise ArgumentError, "Invalid argument `#{arg}` for Renaming()"
end
end
def self.from_argv(argv, opts = {})
coerce(argv)
end
#
# Applies renaming to a a given tuple
#
def apply(tuple)
Tools.tuple_collect(tuple){|k,v| [@renaming[k] || k, v]}
end
# Checks if this renaming is equal to `other`
def ==(other)
other.is_a?(Renaming) && (other.renaming == renaming)
end
end # class Renaming
end # module Types
end # module Alf |
require 'spec_helper'
describe DatabaseResourcesController do
render_views
let(:user) { User.make! }
before(:each) do
sign_in user
@deployment = given_resources_for([:deployment], :user => user)[:deployment]
@database = @deployment.database_resources.first
@databases = @deployment.database_resources
@params = {:deployment_id => @deployment.id, :id => @database.id}
end
it "should render index" do
get :index, :deployment_id => @deployment.id
response.code.should == "200"
assigns(:database_resources).should =~ @databases
assigns(:deployment).should == @deployment
response.should render_template("index")
end
it "should show deployment databases" do
get :show, :deployment_id => @deployment.id, :id => @database.id
response.should redirect_to(deployment_database_resources_url(@deployment))
end
context "update" do
it "should update the database" do
put :update, @params.merge(:database_resource => {:name => 'new name'})
response.code.should == "200"
@database.reload.name.should == 'new name'
assigns(:deployment).should == @deployment
end
it "should return a json of the update errors" do
put :update, @params.merge(:database_resource => {:name => ''})
response.code.should == "422"
response.body.should == ["Name can't be blank"].to_json
assigns(:deployment).should == @deployment
end
end
context "create" do
it "should not create invalid database" do
post :create, @params.merge(:database_resource => {:name => ''})
assigns(:database_resources).should =~ @databases
assigns(:deployment).should == @deployment
response.should render_template("index")
end
it "should create database" do
@cloud = Cloud.make!(:cloud_provider => CloudProvider.make!)
@database_type = DatabaseType.make!
cost_structure = CloudCostStructure.make!
cost_scheme = CloudCostScheme.make!(:cloud => @cloud, :cloud_resource_type => @database_type, :cloud_cost_structure => cost_structure)
cloud_database_type = "#{@cloud.id}:#{@database_type.id}"
post :create, @params.merge(:database_resource => {:name => 'Test'}, :cloud_database_type => cloud_database_type)
response.should redirect_to(deployment_database_resources_url(@deployment))
flash[:success].should == 'Database was created.'
end
end
it "should destroy the database" do
delete :destroy, @params
response.should redirect_to(deployment_database_resources_url(@deployment))
DatabaseResource.exists?(@database.id).should == false
end
it "should clone the database" do
post :clone, @params
response.should redirect_to(deployment_database_resources_url(@deployment))
flash[:success].should == "Database was cloned."
end
end |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rails_mysql/version'
Gem::Specification.new do |spec|
spec.name = "rails_mysql"
spec.version = RailsMysql::VERSION
spec.authors = ["Matt Burke"]
spec.email = ["burkemd1+github@gmail.com"]
spec.summary = %q{Adds a few mysql tool wrappers as rake tasks.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "rake"
# This is really only good for CI and for local development
if RUBY_VERSION == "1.8.7"
spec.add_runtime_dependency "rails", "< 4.0"
else
spec.add_runtime_dependency "rails"
end
spec.add_development_dependency "rspec"
end
|
# frozen_string_literal: true
require 'rakuten_web_service/resource'
require 'rakuten_web_service/ichiba/item'
module RakutenWebService
module Ichiba
class Shop < Resource
attribute :shopName, :shopCode, :shopUrl, :shopAffiliateUrl
def items(options = {})
options = options.merge(shop_code: code)
RakutenWebService::Ichiba::Item.search(options)
end
end
end
end
|
require "rails_helper"
RSpec.describe Repositories::Create do
let(:user) { FactoryBot.create(:user) }
let(:technology_name) { "foo" }
let(:category_name) { "bar" }
let(:repository_name) { "baz/qux" }
let(:args) do
{
user: user,
technology_name: technology_name,
category_name: category_name,
repository_name: repository_name
}
end
let(:outcome) { described_class.run(args) }
describe "#execute" do
it "created expected records" do
details = { "foo" => "bar" }
response = spy(data: spy(errors: {}, as_json: { "data" => { "repository" => details }}))
allow(GitHub::Client).to receive(:query).with(GitHub::RepositoryQuery, variables: { owner: "baz", name: "qux" }).and_return(response)
expect {
outcome
}.to change {
user.technologies.count
}.by(1).and change {
Category.where(name: category_name, technology: user.technologies.take).count
}.by(1).and change {
Repository.where(name: repository_name.split("/").last , details: details).count
}.by(1)
expect(GitHub::Client).to have_received(:query).with(GitHub::RepositoryQuery, variables: { owner: "baz", name: "qux" })
end
context "when repository create failed" do
context "when repository name is empty" do
let(:repository_name) { "" }
it "doesn't create any record and returns expected error" do
expect {
outcome
}.not_to change {
user.technologies.count
}
expect(outcome.errors.details[:repository_name]).to include(error: :invalid)
end
end
context "when repository name is nil" do
let(:repository_name) { "foo" }
it "doesn't create any record and returns expected error" do
expect {
outcome
}.not_to change {
user.technologies.count
}
expect(outcome.errors.details[:repository_name]).to include(error: :invalid)
end
end
context "when repository is not found" do
let(:repository_name) { "foo/bar" }
it "doesn't create any record and returns expected error" do
error_message = "error_message"
response = spy(data: spy(errors: { repository: [error_message] }))
allow(GitHub::Client).to receive(:query).with(GitHub::RepositoryQuery, variables: { owner: "foo", name: "bar" }).and_return(response)
expect {
outcome
}.not_to change {
user.technologies.count
}
expect(outcome.errors.details[:base]).to include(error: error_message)
end
end
context "when the same repository was created in different category" do
it "uses the same repository" do
details = { "foo" => "bar" }
response = spy(data: spy(errors: {}, as_json: { "data" => { "repository" => details }}))
allow(GitHub::Client).to receive(:query).with(GitHub::RepositoryQuery, variables: { owner: "baz", name: "qux" }).and_return(response)
# created a different category but same repository name record
described_class.run(
user: user,
technology_name: technology_name,
category_name: "different_category_name",
repository_name: repository_name
)
owner, name = repository_name.split("/")
expect {
outcome
}.to change {
Category.where(name: category_name, technology: user.technologies.take).count
}.by(1).and not_change {
Repository.where(owner: owner, name: name, details: details).count
}
end
end
end
end
end
|
class AmendmentToClause < Amendment
validates_presence_of :clause_number
end |
# frozen_string_literal: true
FactoryBot.define do
factory :cat do
name { 'cat_name' }
breed_id { create(:breed).id }
sex { 'male' }
status { 'unavailable' }
date_of_birth { '2018-02-03' }
breeding { 'breeding_name' }
colour { 'colour' }
profile_image { Rack::Test::UploadedFile.new('spec/factories/testst.png', 'testst/png') }
end
end
|
require './lib/station'
require './lib/stop'
require './lib/line'
require 'pg'
DB = PG.connect({:dbname => 'timetable', :host => 'localhost'})
def welcome
puts "Welcome to the To Do list!"
admin_menu
end
def admin_menu
choice = nil
until choice == 'e'
puts "Press 1 to add a station, 2 to add a line, 3 to add a stop."
puts "Press 4 to list all of the stations for a given line."
puts "Press 5 to list all of the lines that stop at a given station."
puts "Press 'e' to exit."
choice = gets.chomp
case choice
when '1'
add_station
when '2'
add_line
when '3'
add_stop
when '4'
view_stations_by_line
when '5'
view_lines_by_station
when 'e'
exit
else
invalid
end
end
end
def add_station
puts 'Please enter in a station name:'
@station = Station.new({'name' => gets.chomp}).save
end
def add_line
puts 'Please enter in a line name:'
@line = Line.new({'name' => gets.chomp}).save
end
def view_lines_by_station
puts "Here is a list of all the stations and their ids:"
stations = Station.all
stations.each {|station| puts "'#{station.id}': '#{station.name}'"}
print "Please enter a station id for your list: "
station_id = gets.chomp.to_i
station_name = Station.find_by_id({'station_id' => station_id}).first.name
stops = Stop.list_by_station_id({'station_id' => station_id})
lines = []
stops.map {|stop| lines += Line.find_by_id({'line_id' => stop.line_id})}
if lines.length then puts "Here is a list of all the lines that run through station #{station_name}:" end
lines.each {|line| puts "'#{line.name}'"}
end
def view_stations_by_line
puts "Here is a list of all the lines and their ids:"
lines = Line.all
lines.each {|line| puts "'#{line.id}': '#{line.name}'"}
print "Please enter a line id for your list: "
line_id = gets.chomp.to_i
line = Line.find_by_id(line_id)
stations = line.stations
puts "Here is a list of all the stations that line #{line.name} stops at:"
stations.each {|station| puts "'#{station.id}': '#{station.name}'"}
stops = Stop.list_by_line_id({'line_id' => line_id})
stations = []
stops.map { |stop| stations += Station.find_by_id({'station_id' => stop.station_id})}
if stations.length then puts "Here is a list of all the stations that line #{line_name} stops at:" end
stations.each {|station| puts "'#{station.id}': '#{station.name}'"}
end
def add_stop
puts "Here is a list of all the stations and their ids:"
stations = Station.all
stations.each {|station| puts "'#{station.id}': '#{station.name}'"}
puts "Here is a list of all the line and their ids:"
lines = Line.all
lines.each {|line| puts "'#{line.id}': '#{line.name}'"}
print "Please enter a station id for your stop: "
station_id = gets.chomp.to_i
print "Please enter a line id for your stop: "
line_id = gets.chomp.to_i
Stop.new({'station_id' => station_id, 'line_id' => line_id}).save
end
def clear_db
DB.exec("DELETE FROM lines *;")
DB.exec("DELETE FROM stations *;")
DB.exec("DELETE FROM stops *;")
end
# clear_db
welcome
|
class DeviseMailer < Devise::Mailer
default template_path: 'devise/mailer'
default from: 'info@chat-app.com'
before_action :set_object
def confirmation_instructions
mail(to: @object.try(:email), subject: 'Email Confirmation Instructions')
end
def activated_email
mail(to: @object.try(:email), subject: 'Email Activated')
end
def reset_password_instructions
mail(to: @object.try(:email), subject: 'Reset Password Instructions')
end
def email_changed
mail(to: @object.try(:email), subject: 'Email Changed')
end
def password_change
mail(to: @object.try(:email), subject: 'Password Changed')
end
private
def set_object
@object = params[:object]
end
end
|
require 'rails_helper'
RSpec.describe Hashtag, type: :model do
it 'should belong to a model'
it 'should have a value for name'
end
|
module SportsSouth
class Inventory < Base
API_URL = 'http://webservices.theshootingwarehouse.com/smart/inventory.asmx'
ITEM_NODE_NAME = 'Onhand'
def initialize(options = {})
requires!(options, :username, :password)
@options = options
end
def self.get_quantity_file(options = {})
requires!(options, :username, :password)
options[:last_updated] = '1990-09-25T14:15:47-04:00'
options[:last_item] = '-1'
new(options).get_quantity_file
end
def self.all(options = {})
requires!(options, :username, :password)
if options[:last_updated].present?
options[:last_updated] = options[:last_updated].strftime('%Y-%m-%dT%H:%M:00.00%:z')
else
options[:last_updated] = '1990-09-25T14:15:47-04:00'
end
options[:last_item] ||= '-1'
new(options).all
end
def self.get(item_identifier, options = {})
requires!(options, :username, :password)
new(options).get(item_identifier)
end
def all
http, request = get_http_and_request(API_URL, '/IncrementalOnhandUpdate')
request.set_form_data(form_params = form_params(@options).merge({
SinceDateTime: @options[:last_updated],
LastItem: @options[:last_item].to_s
}))
items = []
tempfile = download_to_tempfile(http, request)
tempfile.rewind
Nokogiri::XML::Reader.from_io(tempfile).each do |reader|
next unless reader.node_type == Nokogiri::XML::Reader::TYPE_ELEMENT
next unless reader.name == ITEM_NODE_NAME
node = Nokogiri::XML.parse(reader.outer_xml)
_map_hash = map_hash(node.css(ITEM_NODE_NAME))
items << _map_hash unless _map_hash.nil?
end
tempfile.close
tempfile.unlink
items
end
def get_quantity_file
tempfile = Tempfile.new
http, request = get_http_and_request(API_URL, '/IncrementalOnhandUpdate')
request.set_form_data(form_params = form_params(@options).merge({
SinceDateTime: @options[:last_updated],
LastItem: @options[:last_item].to_s
}))
response = http.request(request)
xml_doc = Nokogiri::XML(sanitize_response(response))
xml_doc.css('Onhand').map do |item|
tempfile.puts("#{content_for(item, 'I')},#{content_for(item, 'Q')}")
end
tempfile.close
tempfile.path
end
def self.quantity(options = {})
requires!(options, :username, :password)
if options[:last_updated].present?
options[:last_updated] = options[:last_updated].to_s("yyyy-MM-ddTHH:mm:sszzz")
else
options[:last_updated] = '1990-09-25T14:15:47-04:00'
end
options[:last_item] ||= '-1'
new(options).all
end
def get(item_identifier)
http, request = get_http_and_request(API_URL, '/OnhandInquiry')
request.set_form_data(form_params(@options).merge({ ItemNumber: item_identifier }))
response = http.request(request)
xml_doc = Nokogiri::XML(sanitize_response(response))
end
protected
def map_hash(node)
{
item_identifier: content_for(node, 'I'),
quantity: content_for(node, 'Q').to_i,
price: content_for(node, 'C')
}
end
end
end
|
class ThumbnailsController < ApplicationController
before_action :set_thumbnail, only: [:show, :edit, :update, :destroy]
# GET /thumbnails
# GET /thumbnails.json
def index
@thumbnails = Thumbnail.all
end
# GET /thumbnails/1
# GET /thumbnails/1.json
def show
end
# GET /thumbnails/new
def new
@thumbnail = Thumbnail.new
end
# GET /thumbnails/1/edit
def edit
end
# POST /thumbnails
# POST /thumbnails.json
def create
@thumbnail = Thumbnail.new(thumbnail_params)
respond_to do |format|
if @thumbnail.save
format.html { redirect_to @thumbnail, notice: 'Thumbnail was successfully created.' }
format.json { render :show, status: :created, location: @thumbnail }
else
format.html { render :new }
format.json { render json: @thumbnail.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /thumbnails/1
# PATCH/PUT /thumbnails/1.json
def update
respond_to do |format|
if @thumbnail.update(thumbnail_params)
format.html { redirect_to @thumbnail, notice: 'Thumbnail was successfully updated.' }
format.json { render :show, status: :ok, location: @thumbnail }
else
format.html { render :edit }
format.json { render json: @thumbnail.errors, status: :unprocessable_entity }
end
end
end
# DELETE /thumbnails/1
# DELETE /thumbnails/1.json
def destroy
@thumbnail.destroy
respond_to do |format|
format.html { redirect_to thumbnails_url, notice: 'Thumbnail was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_thumbnail
@thumbnail = Thumbnail.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def thumbnail_params
params.require(:thumbnail).permit(:title, :body, :main_image, :thumb_image)
end
end
|
Given /^I am on "([^"]*)"$/ do |page_name|
FactoryGirl.create(:periodJan2013)
visit "/"
end
When /^I follow "([^"]*)"$/ do |link_label|
click_link link_label
end
Then /^I should see title "([^"]*)"$/ do |title_text|
within('head title') do
page.should have_content(title_text)
end
end
When /^I select "([^"]*)" from "([^"]*)"$/ do |value, field|
select value, :from => field
end
When /^I fill im "([^"]*)" with "([^"]*)"$/ do |field, value|
fill_in field, :with => value
end
When /^I submit "([^"]*)"$/ do |button_label|
click_button(button_label)
end |
# Helper Method
def position_taken?(board, index)
!(board[index].nil? || board[index] == " ")
end
# Define your WIN_COMBINATIONS constant
WIN_COMBINATIONS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 4, 8], [2, 4, 6],
[0, 3, 6], [1, 4, 7], [2, 5, 8]]
def won?(board)
WIN_COMBINATIONS.each do |line|
combo = []
line.each do |index|
combo << board[index]
end
all_x = combo.all? do |spot|
spot == "X"
end
all_o = combo.all? do |spot|
spot == "O"
end
if all_x == true || all_o == true
return line
end
end
false
end
def full?(board)
board.none? do |position|
position == " "
end
end
def draw?(board)
if full?(board) && !won?(board)
return true
end
false
end
def over?(board)
if won?(board) || draw?(board) || full?(board)
return true
end
false
end
def winner(board)
if won?(board)
winning_line = won?(board)
return board[winning_line[0]]
end
nil
end
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
def input_to_index(input)
index = input.to_i - 1
end
def valid_move?(board, index)
if position_taken?(board, index) || !index.between?(0, 9)
return false
end
true
end
def move(board, position, token)
board[position] = token
end
def turn_count(board)
turn = 0
board.each do |space|
if space == "O" || space == "X"
turn += 1
end
end
turn
end
def current_player(board)
symbol = turn_count(board).even? ? "X" : "O"
end
def turn(board)
symbol = current_player(board)
puts "Please enter 1-9:"
input = gets.chomp
position = input_to_index(input)
if valid_move?(board, position)
move(board, position, symbol)
display_board(board)
else
turn(board)
end
end
def play(board)
until over?(board)
turn(board)
end
if draw?(board)
puts "Cats Game!"
else
puts "Congratulations #{winner(board)}!"
end
end
|
class Api::V1::SessionsController < Api::V1::BaseController
# skip_before_action :verify_authenticity_token
def create
user = User.find_by(name: create_params[:name])
if user
self.current_user = user
render(
json: Api::V1::SessionSerializer.new(user, root: false).to_json,
status: 201
)
else
return api_error(status: 401)
end
end
private
def create_params
params.require(:user).permit(:name)
end
end |
Fabricator(:ingredient_quantity, :class_name => '::MTMD::FamilyCookBook::IngredientQuantity') do
recipe_id { Fabricate(:recipe).id }
ingredient_id { Fabricate(:ingredient).id }
unit_id { Fabricate(:unit).id }
amount { (100..400).to_a.sample }
portions { (1..4).to_a.sample }
description { Faker::Lorem.sentence }
end
|
class Project < ApplicationRecord
has_many :bugs, dependent: :destroy
belongs_to :creator, class_name: :User
has_many :enrollments , dependent: :delete_all
has_many :enrolled_user, through: :enrollments, source: :user
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.