text stringlengths 10 2.61M |
|---|
require_relative "customer.rb"
require "csv"
class Order
attr_accessor :products, :customer, :fulfillment_status
attr_reader :id
def initialize(id, products, customer, fulfillment_status = :pending)
@id = id
@products = products
@customer = customer
@fulfillment_status = fulfillment_status
until [:pending, :paid, :processing, :shipped, :complete].include?(fulfillment_status)
raise ArgumentError, "Please enter a valid status."
end
end
def total
array_of_prices = @products.map do |_, price|
price
end
tax = array_of_prices.sum * 0.075
return (array_of_prices.sum + tax).round(2)
end
def add_product(name, price)
if @products.keys.include?(name.downcase)
raise ArgumentError, "This product is already in your order."
else
@products[name] = price
end
end
def remove_product(name, price)
if !(@products.keys.include?(name.downcase))
raise ArgumentError, "#{name} is not in your order."
end
@products.delete(name.downcase)
end
def self.hash(products)
products_hash = {}
split_products = products.split(";")
split_products.each do |pair_product|
split_products = pair_product.split(":")
products_hash[split_products[0]] = split_products[1].to_f
end
return products_hash
end
def self.all
order_info_array = CSV.open("data/orders.csv", "r").map do |order|
Order.new(order[0].to_i, self.hash(order[1]), Customer.find(order[2].to_i), order[3].to_sym)
end
return order_info_array
end
def self.find(id)
self.all.each do |search_order|
if search_order.id == id
return search_order
end
end
return nil
end
end
|
class Gift < ActionMailer::Base
default from: "Emily Tepper <mail@receiveeverything.com>"
def initiate mystic
attachments['ireceive.mp3'] = File.read(File.join(Rails.root, 'public', 'secretfolder', 'ireceive.mp3'))
mail to: mystic.email
end
end
|
module Ehonda
module Middleware
module Server
module ActiveRecord
class Idempotence
def initialize logger: Shoryuken.logger
@logger = logger
end
def call _worker, queue, sqs_msg, _body
message = TypedMessage.new sqs_msg
if ProcessedMessage.exists? message_id: message.id, queue: queue
@logger.info middleware: 'idempotence', ignored_message_id: message.id
else
yield
ProcessedMessage.create!(
sqs_id: sqs_msg.message_id,
message_id: message.id,
queue: queue,
message: message.to_h)
end
end
end
end
end
end
end
|
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
has_many :comments, :as => :commentable
def book
return @book if defined?(@book)
@book = commentable.is_a?(Book) ? commentable : commentable.book
end
end
|
# Using Biogem with Rails
class String
# Handle underscore in routing template
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
|
require 'rubygems'
require 'bundler'
begin
Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
require 'rake'
require 'jeweler'
Jeweler::Tasks.new do |gem|
# gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
gem.name = "public_rescue"
gem.homepage = "http://github.com/cyrilpic/public_rescue"
gem.license = "MIT"
gem.summary = %Q{Rails gem for displaying dynamic error pages.}
gem.description = %Q{PublicRescue is a gem for rails application who want to display dynamic error pages. It creates a new Rack middleware which replaces ActionDispatch::ShowExceptions and overwrites the rescue_action_in_public method.}
gem.email = "Cyril@picard.ch"
gem.authors = ["Cyril Picard"]
# Include your dependencies below. Runtime dependencies are required when using your gem,
# and development dependencies are only needed for development (ie running rake tasks, tests, etc)
# gem.add_runtime_dependency 'jabber4r', '> 0.1'
# gem.add_development_dependency 'rspec', '> 1.2.3'
end
Jeweler::RubygemsDotOrgTasks.new
require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.libs << 'lib' << 'test'
test.pattern = 'test/**/test_*.rb'
test.verbose = true
end
desc "Code coverage detail"
task :simplecov do
ENV['COVERAGE'] = "true"
Rake::Task['test'].execute
end
task :default => :test
require 'rdoc/task'
Rake::RDocTask.new do |rdoc|
version = File.exist?('VERSION') ? File.read('VERSION') : ""
rdoc.rdoc_dir = 'rdoc'
rdoc.title = "hello #{version}"
rdoc.rdoc_files.include('README*')
rdoc.rdoc_files.include('lib/**/*.rb')
end
|
# frozen_string_literal: true
# Normalizator::Normalize module
module Normalizator
# Normalization logic for Normalizator
class Normalize
def initialize(rules, data, options)
raise(Normalizator::NormalizeError, 'Nil data') unless data
raise(Normalizator::NormalizeError, 'Nil rules') unless rules
@rules = rules
@data = data
@rules_keys = rules.keys
@options = options
end
def normalize
normalized_data = []
@data.each do |original_row|
normalized_row = run_rules_on_row original_row
normalized_data.push(normalized_row)
end
normalized_data
end
private
def run_rules_on_row(original_row)
new_row = @options[:exclude_fileds_without_rule] ? {} : original_row.clone
@rules_keys.each do |rule_field|
if rule_field.instance_of? Array
next if should_skip_mutly_field_rule?(rule_field, original_row)
run_rules_on_multy_value(rule_field, new_row, original_row)
else
next if should_skip_rule?(rule_field, new_row, original_row)
run_rules_on_single_value(rule_field, new_row, original_row)
end
end
new_row
end
def run_rules_on_multy_value(multy_field, new_row, original_row)
rules = @rules[multy_field]
runs_on_derived_value = should_provide_derived_value?(rules)
values = multy_field.map { |sub_field| runs_on_derived_value ? new_row[sub_field] : original_row[sub_field] }
normalized_values = run_rules_on_value(rules, values, original_row)
multy_field.each_with_index do |sub_field, index|
new_row[sub_field] = normalized_values[index]
end
end
def run_rules_on_single_value(field, new_row, original_row)
rules = @rules[field]
runs_on_derived_value = should_provide_derived_value?(rules)
value = runs_on_derived_value ? new_row[field] : original_row[field]
new_row[field] = run_rules_on_value(rules, value, original_row)
end
def run_rules_on_value(rules, values, original_row)
if rules.instance_of? Array
ruled_field = values
rules.each do |rule|
raise(RuleError, 'Custom rules should implement .apply method') unless rule.respond_to?(:apply)
ruled_field = rule.apply(ruled_field, original_row)
end
ruled_field
else
raise(RuleError, 'Custom rules should implement .apply method') unless rules.respond_to?(:apply)
rules.apply(values, original_row)
end
end
def should_skip_rule?(field, new_row, original_row)
unless original_row.key? field
return true if @options[:ignore_unmatched_rules]
new_row[field] = @options[:default_unmatched_rules_value]
true
end
end
def should_skip_mutly_field_rule?(multy_field, original_row)
multy_field.any? { |sub_field| !original_row.key?(sub_field) }
end
def should_provide_derived_value?(rules)
if rules.instance_of? Array
rules[0].options[:runs_on_derived_value]
else
rules.options[:runs_on_derived_value]
end
end
end
end
|
class Artist < ActiveRecord::Base
has_many :events
has_many :venues, :through => :events
# attr_reader :artistID, :artistName, :artistType, :genres
# @@all =[]
# # def initialize( artistID, artistName, genres)
# # @artistID = artistID
# # @artistName = artistName
# # @genres = genres
# # @@all.push(self)
# # end
# def self.all
# @@all
# end
def self.load(data)
data = data.uniq
data.each do |e|
Artist.new(e["ArtistID"],e["ArtistName"],e["Genre"])
end
puts all.count.to_s + " Artists loaded."
sleep(0.5)
#binding.pry
end
def get_events()
Event.all.select do |event|
event.artist.artistname.downcase == self.artistname.downcase
end
end
def self.by_id(id)
all.select do |artist|
artist.artistID == id
end
end
def self.find_artist(name)
result = all.select {|artist| artist.artistname.downcase.include? name.downcase}.uniq
end
end
|
require 'puppet_x/bsd/hostname_if/carp'
describe 'Carp' do
subject(:carpif) { Hostname_if::Carp }
describe 'initialize' do
context 'when minimal configuration is passed' do
it 'should not error' do
expect {
subject.new({
:id => '1',
:device => 'em0',
:address => ['10.0.0.1/24'],
})
}.to_not raise_error
end
end
end
describe 'content' do
it 'should support a full example' do
c = {
:id => '1',
:device => 'em0',
:address => ['10.0.0.1/24'],
:advbase => '1',
:advskew => '0',
:pass => 'TopSecret',
}
expect(subject.new(c).content).to match(/vhid 1 pass TopSecret carpdev em0 advbase 1 advskew 0\ninet 10.0.0.1 255.255.255.0 NONE/)
end
it 'should support a partial example' do
c = {
:id => '1',
:device => 'em0',
:address => ['10.0.0.1/24'],
:advbase => '1',
:advskew => '0',
}
expect(subject.new(c).content).to match(/vhid 1 carpdev em0 advbase 1 advskew 0\ninet 10.0.0.1 255.255.255.0 NONE/)
end
end
end
|
# Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
require 'spec_helper'
module AWS
shared_examples_for "it has reserved instance attributes" do
context '#instance_type' do
let(:attribute) { :instance_type }
let(:response_field) { attribute }
let(:response_value) { "c1.medium" }
let(:translated_value) { response_value }
it_should_behave_like "ec2 resource attribute accessor (describe call)"
end
context '#availability_zone' do
let(:attribute) { :availability_zone }
let(:response_field) { attribute }
let(:response_value) { "us-east-1d" }
let(:translated_value) { response_value }
it_should_behave_like "ec2 resource attribute accessor (describe call)"
end
context '#duration' do
let(:attribute) { :duration }
let(:response_field) { attribute }
let(:response_value) { 94608000 }
let(:translated_value) { response_value }
it_should_behave_like "ec2 resource attribute accessor (describe call)"
end
context '#fixed_price' do
let(:attribute) { :fixed_price }
let(:response_field) { attribute }
let(:response_value) { 700.0 }
let(:translated_value) { response_value }
it_should_behave_like "ec2 resource attribute accessor (describe call)"
end
context '#usage_price' do
let(:attribute) { :usage_price }
let(:response_field) { attribute }
let(:response_value) { 0.06 }
let(:translated_value) { response_value }
it_should_behave_like "ec2 resource attribute accessor (describe call)"
end
context '#product_description' do
let(:attribute) { :product_description }
let(:response_field) { attribute }
let(:response_value) { "Linux/UNIX" }
let(:translated_value) { response_value }
it_should_behave_like "ec2 resource attribute accessor (describe call)"
end
context '#instance_tenancy' do
let(:attribute) { :instance_tenancy }
let(:response_field) { attribute }
let(:response_value) { "default" }
let(:translated_value) { response_value }
it_should_behave_like "ec2 resource attribute accessor (describe call)"
end
context '#currency_code' do
let(:attribute) { :currency_code }
let(:response_field) { attribute }
let(:response_value) { "USD" }
let(:translated_value) { response_value }
it_should_behave_like "ec2 resource attribute accessor (describe call)"
end
end
end
|
require 'contest'
require 'tilt'
begin
require 'mustache'
raise LoadError, "mustache version must be > 0.2.2" if !Mustache.respond_to?(:compiled?)
module Views
class Foo < Mustache
attr_reader :foo
end
end
class MustacheTemplateTest < Test::Unit::TestCase
test "registered for '.mustache' files" do
assert_equal Tilt::MustacheTemplate, Tilt['test.mustache']
end
test "preparing and evaluating templates on #render" do
template = Tilt::MustacheTemplate.new { |t| "Hello World!" }
assert_equal "Hello World!", template.render
end
test "passing locals" do
template = Tilt::MustacheTemplate.new { "<p>Hey {{name}}!</p>" }
assert_equal "<p>Hey Joe!</p>", template.render(nil, :name => 'Joe')
end
test "passing a block for yield" do
template = Tilt::MustacheTemplate.new { "<p>Hey {{yield}}!</p>" }
assert_equal "<p>Hey Joe!</p>", template.render { 'Joe' }
end
test "locating views defined at the top-level" do
template = Tilt::MustacheTemplate.new('foo.mustache') { "<p>Hey {{foo}}!</p>" }
assert_equal Views::Foo, template.engine
end
module Bar
module Views
class Bizzle < Mustache
end
end
end
test "locating views defined in a custom namespace" do
template = Tilt::MustacheTemplate.new('bizzle.mustache', :namespace => Bar) { "<p>Hello World!</p>" }
assert_equal Bar::Views::Bizzle, template.engine
assert_equal "<p>Hello World!</p>", template.render
end
test "locating views in files" do
view_path = File.expand_path('../tilt_mustache_views', __FILE__)
template = Tilt::MustacheTemplate.new('external.mustache', :view_path => view_path) { "<p>{{hello}}!</p>" }
assert defined?(Views::External), "external.rb should have been required"
assert_equal Views::External, template.engine
assert_equal "<p>Stached!</p>", template.render
end
test "copying instance variables from scope object" do
template = Tilt::MustacheTemplate.new('foo.mustache') { "<p>Hey {{foo}}!</p>" }
scope = Object.new
scope.instance_variable_set(:@foo, 'Jane!')
assert_equal "<p>Hey Jane!!</p>", template.render(scope)
end
end
rescue LoadError => boom
warn "Tilt::MustacheTemplate (disabled)\n"
end
|
require 'rails_helper'
require 'shoulda/matchers'
RSpec.describe Contact, type: :model do
let(:contact) {FactoryGirl.build(:contact)}
let(:created_contact) {FactoryGirl.create(:contact, first_name: 'viji', email: 'viji@gmail.com', age: 27, last_name: 'kumar')}
context 'validations' do
it { should validate_presence_of :email }
it { should validate_numericality_of :age }
subject {created_contact}
it { should validate_uniqueness_of(:email).case_insensitive }
end
context 'associations' do
it {should have_many(:addresses) }
it {should have_many(:phonenumbers)}
end
it 'has a valid factory' do
expect(created_contact).to be_valid
end
end
|
class AddArchiveMessages < ActiveRecord::Migration
def self.up
add_column :chat_messages, :archived, :boolean, :default => false
end
def self.down
remove_column :chat_message, :archived
end
end
|
class AddDefaultCategoryForAds < ActiveRecord::Migration
def change
change_column :ads_categories, :category_id, :integer, default: 1
end
end
|
require 'rubygems'
require 'rake'
HAML_GEMSPEC = Gem::Specification.new do |s|
s.name = 'ricogen'
s.rubyforge_project = 'ricogen'
s.summary = "My rails 3 app generator based on hamgen"
s.version = File.read('VERSION').strip
s.authors = ['Hampton Catlin', "David Cuadrado"]
s.email = 'krawek@gmail.com'
s.description = <<-END
A Rails 3.0 generator (like for the whole project) that pre-generates
a bunch of shit I like. Most of it is stolen directly from Hampton's Rails Template
at http://github.com/hcatlin/hamgen but with changes just for ole' me
END
s.add_runtime_dependency('colored', ['~> 1.2'])
s.add_runtime_dependency('rails', ['~> 3.0.0'])
s.add_runtime_dependency('haml', ['~> 3.0.18'])
s.add_development_dependency('rake', ['~> 0.8.7'])
s.executables = ['ricogen']
s.files = Dir['**/**'].to_a.select { |f| f[0..2] != "pkg"}
s.homepage = 'http://www.hamptoncatlin.com/'
end
|
after_bundler do
# Get javascript
get_vendor_javascript 'https://raw.github.com/fancyapps/fancyBox/master/source/jquery.fancybox.js', 'jquery.fancybox'
require_javascript 'jquery.fancybox'
# Get images
get_support_file 'app/assets/images/blank.gif'
get_vendor_image 'https://raw.github.com/fancyapps/fancyBox/master/source/fancybox_loading.gif', 'fancybox_loading.gif'
get_vendor_image 'https://raw.github.com/fancyapps/fancyBox/master/source/fancybox_overlay.png', 'fancybox_overlay.png'
get_vendor_image 'https://raw.github.com/fancyapps/fancyBox/master/source/fancybox_sprite.png', 'fancybox_sprite.png'
# Get css
get_vendor_stylesheet 'https://raw.github.com/fancyapps/fancyBox/master/source/jquery.fancybox.css', 'jquery.fancybox'
require_stylesheet 'jquery.fancybox'
# Update css to use asset pipeline
gsub_file 'vendor/assets/stylesheets/jquery.fancybox.css.scss', "url('blank.gif')", 'image-url("blank.gif")'
gsub_file 'vendor/assets/stylesheets/jquery.fancybox.css.scss', "url('fancybox_loading.gif')", 'image-url("fancybox_loading.gif")'
gsub_file 'vendor/assets/stylesheets/jquery.fancybox.css.scss', "url('fancybox_overlay.png')", 'image-url("fancybox_overlay.png")'
gsub_file 'vendor/assets/stylesheets/jquery.fancybox.css.scss', "url('fancybox_sprite.png')", 'image-url("fancybox_sprite.png")'
# Get media helper
get_vendor_javascript 'https://raw.github.com/fancyapps/fancyBox/master/source/helpers/jquery.fancybox-media.js', 'jquery.fancybox-media'
require_javascript 'jquery.fancybox-media'
end
__END__
name: Fancybox
description: Use Fancybox for jquery lightbox
website: http://fancyapps.com/fancybox
author: mattolson
requires: [jquery]
run_after: [jquery]
category: javascript
|
MRuby::Gem::Specification.new('mruby-example') do |spec|
spec.license = 'MIT'
spec.authors = 'your-name'
end
|
require 'delegate'
require 'active_support/core_ext/array/wrap'
require 'hydramata/works/conversions/translation_key_fragment'
require 'hydramata/works/conversions/view_path_fragment'
module Hydramata
module Works
# Responsible for coordinating the rendering of an in-memory data structure
# object to an output buffer.
class BasePresenter < SimpleDelegator
include Conversions
attr_reader :presentation_context, :translator, :partial_prefixes, :translation_scopes, :renderer
def initialize(object, collaborators = {})
__setobj__(object)
@presentation_context = collaborators.fetch(:presentation_context) { default_presentation_context }
@partial_prefixes = collaborators.fetch(:partial_prefixes) { default_partial_prefixes }
@translator = collaborators.fetch(:translator) { default_translator }
@translation_scopes = collaborators.fetch(:translation_scopes) { default_translation_scopes }
@dom_attributes_builder = collaborators.fetch(:dom_attributes_builder) { default_dom_attributes_builder }
@renderer = collaborators.fetch(:renderer) { default_renderer }
end
def render(template, options = {})
renderer.call(template, options)
end
def translate(key, options = {})
translator.t(key, { scopes: translation_scopes }.merge(options))
end
alias_method :t, :translate
def with_text_for(key, options = {})
translation = translate(key, { raise: true }.merge(options))
yield(translation) if block_given?
translation
rescue StandardError
:no_translation
end
def label(options = {})
translator.t(:label, { scopes: translation_scopes, default: name.to_s }.merge(options))
end
def inspect
format('#<%s:%#0x presenting=%s>', self.class, __id__, __getobj__.inspect)
end
def instance_of?(klass)
super || __getobj__.instance_of?(klass)
end
def dom_class(prefix: nil, suffix: nil)
[prefix, base_dom_class, suffix].compact.join('-')
end
def name
__getobj__.respond_to?(:name) ? __getobj__.name : __getobj__.name_for_application_usage
end
def to_presenter
self
end
def container_content_tag_attributes(options = {})
dom_attributes_builder.call(self, options, default_dom_attributes)
end
def presenter_dom_class(prefix: nil, suffix: nil)
[prefix, base_presenter_dom_class, suffix].compact.join('-')
end
def base_presenter_dom_class
self.class.to_s.split('::').last.sub(/presenter\Z/i,'').downcase
end
def view_path_slug_for_object
raise NotImplementedError.new("You must implmenent #{self.class}#view_path_slug_for_object")
end
private
attr_reader :dom_attributes_builder
def default_dom_attributes_builder
require 'hydramata/works/dom_attributes_builder'
DomAttributesBuilder
end
def default_dom_attributes
{}
end
def base_dom_class
name.to_s.downcase.gsub(/[\W_]+/, '-')
end
def default_partial_prefixes
[]
end
def default_translation_scopes
[]
end
def default_presentation_context
:show
end
def default_translator
require 'hydramata/core'
Hydramata.configuration.translator
end
def default_renderer
require 'hydramata/works/work_template_renderer'
WorkTemplateRenderer.new(self)
end
def require(*args)
# Because the value object may decide to implement #require (I'm glaring
# at you ActionController::Parameters, and your #require method).
::Kernel.require(*args)
end
end
end
end
|
require 'cryptocompare'
class CryptoApiList
def initialize
end
def fetch
list['Data'].reduce([]) do |acc, data|
acc << {
code: data.last['Symbol'], # the API is actually wrong since a symbol should be such as $ € ..
symbol: data.last['Symbol'], # TODO : someday we will add the feature for the symbols of each currency
name: data.last['Name'],
coin_name: data.last['CoinName'],
full_name: data.last['FullName'],
algorithm: data.last['Algorithm'],
proof_type: data.last['ProofType'],
# rank: data.last['SortOrder'], # was replaced by the top 100 and then unknown rank it's in another task
# we manipulate the URL because it's not only a path
# we can change it easily this way.
logo_url: logo_url(data)
}
end
end
private
def logo_url(data)
if data.last['ImageUrl']
"/static/images/coins/#{data.last['ImageUrl']}"
else
""
end
end
def list
@list ||= Cryptocompare::CoinList.all
end
end
|
LatoPages::Engine.routes.draw do
root 'back/pages#index'
resources :pages, module: 'back'
scope '/api/v1/' do
get 'fields', to: 'api/v1/fields#index'
get 'fields/:page', to: 'api/v1/fields#index'
get 'fields/:page/:lang', to: 'api/v1/fields#index'
get 'field/:name/:page', to: 'api/v1/fields#show'
get 'field/:name/:page/:lang', to: 'api/v1/fields#show'
end
end
|
def with_aws_stubbed(stub_responses_per_service)
require "aws-sdk-core"
stub_responses_per_service.each do |service, stub_responses|
if Aws.config.dig(service, :stub_responses).present?
raise "Aws.config[#{service}][:stub_responses] already set"
else
require "aws-sdk-#{service.to_s.downcase}"
(Aws.config[service] ||= {})[:stub_responses] = stub_responses
end
end
yield
ensure
stub_responses_per_service.keys.each do |service|
Aws.config[service].delete(:stub_responses)
end
end
|
# Some snippets that'll come handy while uploading/naming templates from a rails console.
# Test them once before running, they might get outdated.
class NotificationStringsForKatalon
# This will print all notification strings in the format the Katalon Recorder needs.
# You can filter the output or tweak these commands to include only the ones you want to upload.
# Katalon Recorder: https://chrome.google.com/webstore/detail/katalon-recorder-selenium/ljdobmomdgdljniojadhoplhkpialdid
def self.call
include I18n::Backend::Flatten
all_strings = Dir.glob("config/locales/notifications/*").map do |file_name|
flatten_translations(nil, YAML.safe_load(File.open(file_name)), nil, false)
end
all_strings.flat_map(&:to_a).to_h.sort_by(&:first)
.map do |k, v|
{
"name" => k.to_s,
"message" => v.gsub("%{patient_name}", "{#var#}").gsub("%{facility_name}", "{#var#}").gsub("%{appointment_date}", "{#var#}")
}
end
end
end
class NameUnnamedTemplatesOnBulkSms
def self.call
# Make sure to run rake bsnl:get_template_details before
# and after this.
include I18n::Backend::Flatten
all_strings = Dir.glob("config/locales/notifications/*").map do |file_name|
flatten_translations(nil, YAML.safe_load(File.open(file_name)), nil, false)
end.flat_map(&:to_a).to_h.transform_keys(&:to_s)
bsnl_templates = YAML.load_file("config/data/bsnl_templates.yml")
pending = bsnl_templates.select { |_, details| details["Template_Status"] == "0" }.map { |template_name, details| [details["Template_Id"], template_name] }
pending_ids = pending.to_h.map { |k, v| [v[0..-3], k] }.to_h
result = all_strings.map { |k, v| [k, v, pending_ids[k]] }.select { |a| a.third.present? }
list = result.map { |a| [a.first, a.third, a.second.gsub("%{", "{#").gsub("}", "#}")] }
api = Messaging::Bsnl::Api.new
list.map do |name, id, string|
[name, api.name_template_variables(id, string)]
end
end
end
|
class ThinkingSphinx::Excerpter
DefaultOptions = {
:before_match => '<span class="match">',
:after_match => '</span>',
:chunk_separator => ' … ' # ellipsis
}
attr_accessor :index, :words, :options
def initialize(index, words, options = {})
@index, @words = index, words
@options = DefaultOptions.merge(options)
end
def excerpt!(text)
connection.query(Riddle::Query.snippets(text, index, words, options)).
first['snippet']
end
private
def connection
@connection ||= ThinkingSphinx::Connection.new
end
end
|
class Note < ActiveRecord::Base
validates :body, :track_id, :user_id, presence: true
belongs_to :track,
class_name: 'Track',
foreign_key: :track_id,
primary_key: :id
belongs_to :user,
class_name: 'User',
foreign_key: :user_id,
primary_key: :id
end
|
class Article < ApplicationRecord
has_many :votes
has_many :users, through: :votes
has_one :bias, as: :biasable
attr_accessor :bias_structure, :articles_bias
after_create :retrieve_bias
@articles_bias = Struct.new(:libertarian, :green, :liberal, :conservative)
def self.averages
@articles_bias.new(
Article.traverse_association(:bias).average('libertarian'),
Article.traverse_association(:bias).average('green'),
Article.traverse_association(:bias).average('liberal'),
Article.traverse_association(:bias).average('conservative')
)
end
private
def create
run_callbacks :create do
retrieve_bias
end
end
def retrieve_bias
Vendor.init_indico
the_bias = Indico.political(body).deep_transform_keys(&:downcase).deep_symbolize_keys
self.bias = Bias.create(the_bias)
end
end
|
require 'rails_helper'
RSpec.describe Sport, type: :model do
describe 'validations' do
it 'Requires a sport name' do
sport = build(:sport, name: nil)
expect(sport.valid?).to eq(false)
end
it 'requires that each sport name be unique' do
sport = create(:sport)
sport1 = build(:sport)
expect(sport1.valid?).to eq(false)
expect(sport1.errors.full_messages).to eq([
"Name has already been taken"
])
end
end
describe 'relationships' do
it 'has many sub sports' do
sport = create(:sport)
sport.sub_sports.create(name: "NFL", conference_split: true)
sport.sub_sports.create(name: "NCAAF", conference_split: true)
expect(sport.sub_sports.length).to eq(2)
end
end
end
|
class AccountsController < ApplicationController
before_filter :authenticate_user!
before_filter :get_admin, :only => [:edit, :update, :show, :add_credit, :view_credit, :subscribe, :unsubscribe]
def create
# check if user is admin and have account already
if current_user.type == 'Administrator'
admin = current_user.becomes(current_user.type.constantize)
if not admin.account.blank?
redirect_to account_path(admin.account)
return
end
end
current_user.type = 'Administrator'
current_user.save
if params[:account].blank?
flash.now[:type] = "error"
flash.now[:notice] = I18n.t("account.create.fail")
render :action => :new
return
end
@account = Account.create({:administrator_id => current_user.id}.merge(params[:account]))
#respond_to do |format|
if current_user.valid? and @account
flash[:notice] = I18n.t("account.create.success")
redirect_to apps_path
else
flash.now[:type] = "error"
flash.now[:notice] = I18n.t("account.create.fail")
render :action => :new
end
#end
end
def new
@account = Account.new
end
def edit
if @admin.blank?
redirect_to root_path
return
end
@account = @admin.account
respond_to do |format|
if @account.blank? or not @account.id.to_s == params[:id]
format.html { redirect_to root_path }
else
format.html
end
end
end
def show
if @admin.blank?
redirect_to root_path
return
end
@account = @admin.account
respond_to do |format|
if @account.blank? or not @account.id.to_s == params[:id]
format.html { redirect_to root_path }
else
format.html
end
end
end
def update
if @admin.blank?
redirect_to root_path
return
end
@account = @admin.account
respond_to do |format|
if @account.blank? or not @account.id.to_s == params[:id] or params[:account].blank?
redirect_to root_path
return
end
if @account.update_attributes(params[:account])
flash[:notice] = I18n.t("account.update.success")
format.html { redirect_to(account_path(@account)) }
else
flash.now[:type] = 'error'
flash.now[:notice] = I18n.t("account.update.fail")
format.html { render :action => :edit }
end
end
end
def view_credit
if @admin.blank?
respond_to do |format|
format.html { redirect_to root_path }
end
return
end
@account = @admin.account
@plan = params[:plan]
respond_to do |format|
format.html { render :layout => 'iframe' }
end
end
def add_credit
if @admin.blank?
redirect_to root_path
return
end
@account = @admin.account
# "add-credit-quantity-one"=>"0", "add-credit-quantity-few"=>"0", "add-credit-quantity-volume"=>"2", "stripeToken"=>"tok_RlxYOlf8bM8t9E", "total_price"=>"200", "total_credits"=>"100", "account_id"=>"1"}
# credit params check
if params[:total_price].blank? or params[:total_credits].blank? or not params[:total_credits].to_i
result = { 'result' => 'fail',
'reason' => 'Parameter missing' }
respond_to do |format|
format.json { render :json => result }
end
return
end
if params[:total_price].to_i == 0 or params[:total_credits].to_i == 0
result = { 'result' => 'fail',
'reason' => 'You have not purchased anything' }
respond_to do |format|
format.json { render :json => result }
end
return
end
# validate total price and credits
expected_price = 0
expected_credits = 0
PAYMENT_CONFIG['plans'].each do |plan|
quantity = params["add-credit-quantity-#{plan['name']}"].to_i;
expected_price += quantity * plan['price']
expected_credits += quantity * plan['credit']
end
if expected_price != params[:total_price].to_i or expected_credits != params[:total_credits].to_i
result = { 'result' => 'fail',
'reason' => 'Invalid request' } # error msg does not specify details regarding check logic
respond_to do |format|
format.json { render :json => result }
end
return
end
# payment params check
if not params[:stripeToken]
result = { 'result' => 'fail',
'reason' => 'Invalid payment information' }
respond_to do |format|
format.json { render :json => result }
end
return
end
# add credit
# payment
Stripe.api_key = ENV['STRIPE_SECRET_KEY']
token = params[:stripeToken]
charge = Stripe::Charge.create(
:amount => params[:total_price].to_i * 100, # amount in cents
:currency => "usd",
:card => token,
:description => "credit purchase from account #{@account.id} - #{@account.name} - #{@account.administrator.email}"
)
respond_to do |format|
if charge.paid
remaining_credits = @account.remaining_credits
new_credits = @account.add_credits params[:total_credits].to_i
if new_credits == (remaining_credits + params[:total_credits].to_i)
format.json { render :json => { "result" => "success", "remaining_credits" => @account.remaining_credits } }
else
format.json { render :json => { "result" => "fail", "reason" => "Failed to add credit" } }
end
else
format.json { render :json => { "result" => "fail", "reason" => "Failed to charge" } }
end
end
end
def subscribe
if @admin.blank?
redirect_to root_path
return
end
@account = @admin.account
# payment params check
if not params[:stripeToken]
result = { 'result' => 'fail',
'reason' => 'Invalid payment information' }
respond_to do |format|
format.json { render :json => result }
end
return
end
# check if subscription exists
if @account.subscribed_to_unlimited_plan?
result = { 'result' => 'fail',
'reason' => 'Subscribed already' }
respond_to do |format|
format.json { render :json => result }
end
return
end
# create customer and subscribe to unlimited plan
Stripe.api_key = ENV['STRIPE_SECRET_KEY']
token = params[:stripeToken]
begin
customer = Stripe::Customer.create(
:description => "subscription of #{@account.id} - #{@account.name} - #{@account.administrator.email}",
:email => @account.administrator.email,
:card => token,
:plan => "unlimited"
)
rescue
result = { 'result' => 'fail',
'reason' => 'Payment gateway rejected. Please check your credit card information and try again.' }
else
# save record in redis
@account.subscribe "unlimited"
result = { 'result' => 'success' }
end
respond_to do |format|
format.json { render :json => result }
end
end
def unsubscribe
if @admin.blank?
redirect_to root_path
return
end
if !@admin.account.subscribed_to_unlimited_plan?
result = { 'result' => 'fail',
'reason' => 'Not subscribed yet' }
respond_to do |format|
format.json { render :json => result }
end
return
end
@admin.account.unsubscribe
SystemMailer.unsubscribe_notification(@admin.account).deliver
respond_to do |format|
result = { 'result' => 'success' }
format.json { render :json => result }
end
end
protected
def get_admin
if current_user.type == 'Administrator'
@admin = current_user.becomes('Administrator'.constantize)
else
@admin = nil
end
@admin
end
end
|
class CreatePurchase < ActiveRecord::Migration[5.1]
def change
create_table :purchases do |t|
t.integer :customer_id, :product_id, :merchant_id
t.integer :quantity
t.timestamps null: false
end
end
end
|
class AddTokenToItem < ActiveRecord::Migration
def change
add_column :items, :token, :string
add_column :item_images, :item_token, :string
end
end
|
require '../lib/todolist'
require 'test/unit'
class Testcase < Test::Unit::TestCase
def setup
@t=Todolist.new("pavan.txt")
end
def teardown
@t=nil
end
#testing for empty file
def test_aempty
@t.empty
assert_equal 0,@t.pending.size
assert_equal 0,@t.completed.size
assert_equal 0,@t.list.size
end
#testing for first add method
def test_add1
@t.empty
@t.add("hi")
@t.add("hello")
@t.add("hey")
@t.add("bye")
@t.add("tc")
assert_equal 5,@t.pending.size
assert_equal 5,@t.list.size
assert_equal 0,@t.completed.size
assert_equal "hello",@t.show_pending(2)
end
#testing for complete
def test_complete
#before calling method
@t.empty
@t.add("hi")
@t.add("hello")
@t.add("hey")
assert_equal 3,@t.pending.size
assert_equal 3,@t.list.size
assert_equal 0,@t.completed.size
#action
@t.complete(1)
@t.complete(2)
#after calling method
assert_equal 3,@t.list.size
assert_equal 1,@t.pending.size
assert_equal 2,@t.completed.size
end
#testing for pending
def test_pending
@t.empty
@t.add("hi")
@t.add("hello")
@t.add("hey")
assert_equal 3,@t.pending.size
assert_equal 3,@t.list.size
assert_equal 0,@t.completed.size
assert_equal "hi",@t.show_pending(1)
assert_equal "hello",@t.show_pending(2)
assert_equal "hey",@t.show_pending(3)
end
#testing for delete
def test_delete
@t.empty
@t.add("hi")
@t.add("hello")
@t.add("hey")
assert_equal 3,@t.pending.size
assert_equal 3,@t.list.size
assert_equal 0,@t.completed.size
@t.complete(1)
assert_equal 2,@t.pending.size
assert_equal 1,@t.completed.size
@t.delete(1)
assert_equal 2,@t.pending.size
assert_equal 0,@t.completed.size
assert_equal 2,@t.list.size
end
#testing for todo list
def test_list
@t.empty
@t.add("hi")
@t.add("hello")
@t.add("hey")
@t.list
assert_equal 3,@t.list.size
end
#testing for modify
def test_8
@t.empty
@t.add("hi")
@t.add("hello")
@t.add("hey")
assert_equal 3,@t.pending.size
assert_equal 3,@t.list.size
assert_equal 0,@t.completed.size
assert_equal "hi",@t.show_pending(1)
@t.modify(1,"bye")
@t.modify(2,"hi")
assert_equal "bye",@t.show_pending(1)
assert_equal "hi",@t.show_pending(2)
end
#testing for show pending
def test_9
@t.empty
@t.add("hi")
@t.add("hello")
@t.add("hey")
assert_equal "hey",@t.show_pending(3)
end
#testing for show completed
def test_show
@t.empty
@t.add("hi")
@t.add("hello")
@t.add("hey")
@t.complete(1)
@t.complete(3)
assert_equal "hi",@t.show_completed(1)
end
def test_save
@t.empty
@t.add("hi #undone")
@t.add("hello #undone")
assert_equal 2,@t.pending.size
@t.complete_it(1)
assert_equal 1,@t.pending.size
assert_equal 1,@t.completed.size
assert_equal 2,@t.list.size
assert_equal 2,@t.save.size
end
def test_save_to_file
@t.empty
@t.add("hi #undone")
@t.add("hello #undone")
assert_equal 2,@t.pending.size
@t.complete_it(1)
assert_equal 1,@t.pending.size
assert_equal 1,@t.completed.size
assert_equal 2,@t.list.size
assert_equal 2,@t.save.size
@t.save_to_file("pav.txt")
end
def test_load
@t.empty
@t.add("hi #undone")
@t.add("hello #undone")
assert_equal 2,@t.pending.size
assert_equal 0,@t.completed.size
@t.complete_it(1)
assert_equal 1,@t.pending.size
assert_equal 1,@t.completed.size
assert_equal 2,@t.list.size
assert_equal 2,@t.load1.size
end
def test_load_from_file
@t.empty
assert_equal 1,@t.load_from_file("pav.txt").size
assert_equal 2,@t.list.size
end
end
|
require 'spec_helper'
describe Classifier do
before :all do
explanatory_variable :x do
type :numeric
calculate
end
explanatory_variable :y do
type :numeric
calculate
end
end
describe Classifier::SVMachine do
describe "#initialize" do
it "should throw a named exception when given an invalid file name" do
expect {
Classifier::SVMachine.new(TrainingSample.new("nonexistant.file"), [:x, :y])
}.to raise_error IOError
end
end
describe "#predict" do
let(:model) { Classifier::SVMachine.new(TrainingSample.new("./spec/lib/test_training_data.csv"), [:x, :y]) }
it "correctly classify a vector" do
model.predict([1,0]).should == true
model.predict([0,1]).should == false
end
end
end
describe Classifier::DecisionTreeID3 do
describe "#initialize" do
it "should throw a named exception when given an invalid file name" do
expect {
Classifier::DecisionTreeID3.new(TrainingSample.new("nonexistant.file"), [:x, :y])
}.to raise_error IOError
end
end
describe "#predict" do
let(:model) { Classifier::DecisionTreeID3.new(TrainingSample.new("./spec/lib/test_training_data.csv"), [:x, :y]) }
it "correctly classify a vector" do
model.predict([1,0]).should == true
model.predict([0,1]).should == false
end
end
end
describe Classifier::SASDecisionTree do
let(:model) { Classifier::SASDecisionTree.new("./spec/lib/sas_decision_tree_test_model.sas") }
describe "#predict" do
it "correctly classify a vector" do
model.predict([1,1]).should == true
model.predict([0,0]).should == true
model.predict([1,0]).should == true
model.predict([0,1]).should == false
end
end
end
end |
# -*- coding: utf-8 -*-
class Graph
attr :nodes
def initialize
@nodes=[]
end
def to_s
"##<Graph:0x#{self.object_id.to_s(16)} #{@nodes.each { |n| n.to_s }}>"
end
def add_edge(name1, name2)
node1 = @nodes.find {|n| n.name == name1}
if (node1.nil?)
node1 = Node.new(name1)
@nodes.push node1
end
node2 = @nodes.find {|n| n.name == name2}
if (node2.nil?)
node2 = Node.new(name2)
@nodes.push node2
end
node1.add_neighbor([name2, 1])
node2.add_neighbor([name1, 1])
end
def merge(dst, src)
dst_node = @nodes.find { |n| n.name == dst }
src_node = @nodes.find { |n| n.name == src }
return if (dst_node.nil? or src_node.nil?)
dst_node.name = [dst, src].flatten.sort
dst_node.merge_neighbors([dst, src])
src_node.merge_neighbors([dst, src])
dst_node.neighbors.each { |dst_neighbor|
src_neighbor = src_node.neighbors.assoc(dst_neighbor[0])
unless src_neighbor.nil?
dst_neighbor[1] += src_neighbor[1]
src_node.neighbors.delete_if { |other_neighbor|
dst_neighbor[0] == other_neighbor[0]
}
end
}
dst_node.neighbors += src_node.neighbors
dst_node.neighbors.delete_if { |neighbor| neighbor[0] == dst_node.name }
@nodes.each { |node|
dst_node.neighbors.each { |neighbor|
if node.name == neighbor[0]
node.merge_neighbors([dst, src])
end
}
}
@nodes.delete_if { |n| n.name == src }
end
def sort_by_maximum_adjacency_ordering
result = []
result.push @nodes.pop
while @nodes.count > 0
names = result.map { |node| node.name }
nearest = nearest_neighbor(names)
result.push put_nearest_neighbor(names)
@nodes.delete_if { |node| node.name == nearest.name }
end
@nodes = result
end
private
# 名前の配列に対して、もっとも結合度が大きい頂点を返す
def nearest_neighbor(names)
@nodes.max { |a, b|
a_weight = a.neighbors_weight(names)
b_weight = b.neighbors_weight(names)
if (a_weight > b_weight) then 1
elsif a_weight == b_weight then 0
else -1
end
}
end
end
=begin
graph.rb --- グラフを表す
属性
nodes lib/node.rbで定義したNodesで表される頂点を要素に持つ配列
メソッド
add_edge 指定した名前の頂点間に隣接度1の枝を張る。
頂点がなければ、新たに作成して追加する。
merge 指定した2つの名前の頂点を結合する。
結合した頂点に隣接する頂点間の枝の結合度は、それぞれ加算する。
sort_by_maximum_adjacency_ordering
nodesの末尾の頂点を基準として、最大隣接順序を満たすように
頂点を並べ直す。
=end
|
require 'rails_helper'
RSpec.describe "new book form", type: :feature do
it "displays a form to add a new book - includes title, publication year, pages, cover image (optional), and authors" do
visit new_book_path
fill_in "book[title]", with: "the talisman"
fill_in "book[publication_year]", with: 1984
fill_in "book[pages]", with: 921
fill_in "book[cover_image]", with: "https://images-na.ssl-images-amazon.com/images/I/411-vun7rML._SX320_BO1,204,203,200_.jpg"
fill_in "book[authors]", with: "stephen king, peter straub"
click_on "Create Book"
new_book = Book.last
expect(current_path).to eq(book_path(new_book))
expect(page).to have_content(new_book.title)
expect(page).to have_content(new_book.publication_year)
expect(page).to have_content(new_book.pages)
expect(page).to have_css("img[src='#{new_book.cover_image}']")
expect(page).to have_content(new_book.authors.first.name)
end
it "creates book with default image when no image url is given" do
visit new_book_path
fill_in "book[title]", with: "the talisman"
fill_in "book[publication_year]", with: 1984
fill_in "book[pages]", with: 921
fill_in "book[authors]", with: "stephen king, peter straub"
click_on "Create Book"
new_book = Book.last
expect(current_path).to eq(book_path(new_book))
expect(page).to have_css("img[src='#{new_book.cover_image}']")
end
it "displays flash notice when there is an invalid page entry" do
visit new_book_path
fill_in "book[title]", with: "the talisman"
fill_in "book[publication_year]", with: 1984
fill_in "book[pages]", with: -921
fill_in "book[cover_image]", with: "https://images-na.ssl-images-amazon.com/images/I/411-vun7rML._SX320_BO1,204,203,200_.jpg"
fill_in "book[authors]", with: "stephen king, peter straub"
click_on "Create Book"
expect(page).to have_content("Invalid entry. Please try again.")
end
it "displays flash notice when there is a duplicate title entry" do
b1 = Book.create!(title: "The Talisman", publication_year: 1984, pages: 200)
visit new_book_path
fill_in "book[title]", with: "the talisman"
fill_in "book[publication_year]", with: 1984
fill_in "book[pages]", with: 200
fill_in "book[cover_image]", with: "https://images-na.ssl-images-amazon.com/images/I/411-vun7rML._SX320_BO1,204,203,200_.jpg"
fill_in "book[authors]", with: "stephen king, peter straub"
click_on "Create Book"
expect(page).to have_content("Invalid entry. Please try again.")
expect(current_path).to eq(new_book_path)
end
end
|
#
# registrant_fee.rb
# ConstantContact
#
# Copyright (c) 2013 Constant Contact. All rights reserved.
module ConstantContact
module Components
module EventSpot
class RegistrantFee < Component
attr_accessor :id, :amount, :promo_type, :fee_period_type, :type, :name, :quantity
# Factory method to create a RegistrantFee object from a hash
# @param [Hash] props - hash of properties to create object from
# @return [RegistrantFee]
def self.create(props)
obj = RegistrantFee.new
if props
props.each do |key, value|
key = key.to_s
obj.send("#{key}=", value) if obj.respond_to? key
end
end
obj
end
end
end
end
end |
require 'wsdl_mapper/dom/bounds'
module WsdlMapper
module Dom
class Property
class Ref < TypeBase
attr_accessor :containing_type
attr_reader :name, :bounds, :sequence, :default, :fixed, :form
def initialize(name, bounds: Bounds.new, sequence: 0, default: nil, fixed: nil, form: nil)
super name
@name, @bounds, @sequence = name, bounds, sequence
@default = default
@fixed = fixed
@form = form
end
end
attr_reader :name, :type_name, :bounds, :sequence, :default, :fixed, :form
attr_accessor :type, :containing_type
attr_accessor :documentation
def initialize(name, type_name, bounds: Bounds.new, sequence: 0, default: nil, fixed: nil, form: nil)
@name, @type_name, @bounds, @sequence = name, type_name, bounds, sequence
@documentation = Documentation.new
@default = default
@fixed = fixed
@form = form
end
def default?
!!@default
end
def fixed?
!!@fixed
end
def array?
@bounds.max.nil?
end
def single?
@bounds.min == 1 && @bounds.max == 1
end
def optional?
@bounds.min == 0 && @bounds.max == 1
end
def required?
@bounds.min > 0
end
end
end
end
|
#encoding: utf-8
module Restfuls
class Friends < Grape::API
format :json
helpers FriendHelper
resource 'friend' do
desc '申请好友接口'
params do
requires :session_key,type: String,desc: '会话key'
requires :receiver_id,type: Integer,desc: '接收者id'
end
get '/apply' do
apply
end
post '/apply' do
apply
end
desc '关注仇敌'
params do
requires :session_key,type: String,desc: '会话key'
requires :receiver_id,type: Integer,desc: '接收者id'
end
get '/follow' do
follow
end
post '/follow' do
follow
end
desc '回复好友申请'
params do
requires :session_key,type: String,desc: '会话key'
requires :sender_id,type: Integer,desc: '申请者id'
requires :reply_type,type: Integer,desc: '回复类型'
end
get '/reply_apply' do
reply_apply
end
post '/reply_apply' do
reply_apply
end
desc '给好友留言'
params do
requires :session_key,type: String,desc: '会话key'
requires :receiver_id,type: Integer,desc: '收到者id'
requires :message,type: String,desc: '留言内容'
end
get '/leave_message' do
leave_message
end
post '/leave_message' do
leave_message
end
desc '获取关系用户列表接口'
params do
requires :session_key,type: String,desc: '会话key'
requires :relation_type,type: Integer,desc: '关系类型'
end
get '/get_relation_user_list' do
get_relation_user_list
end
post '/get_relation_user_list' do
get_relation_user_list
end
desc '获取留言列表接口'
params do
requires :session_key,type: String,desc: '会话key'
end
get '/get_message_list' do
get_message_list
end
post '/get_message_list' do
get_message_list
end
end
end
end |
# frozen_string_literal: true
module OpenVPNStatusWeb
module Parser
class ModernStateless
def self.parse_status_log(text, sep)
status = Status.new
status.client_list_headers = []
status.client_list = []
status.routing_table_headers = []
status.routing_table = []
status.global_stats = []
text.lines.each do |line|
parts = line.strip.split(sep)
status.client_list_headers = parts[2..] if parts[0] == 'HEADER' && parts[1] == 'CLIENT_LIST'
status.client_list << parse_client(parts[1..], status.client_list_headers) if parts[0] == 'CLIENT_LIST'
status.routing_table_headers = parts[2..] if parts[0] == 'HEADER' && parts[1] == 'ROUTING_TABLE'
status.routing_table << parse_route(parts[1..], status.routing_table_headers) if parts[0] == 'ROUTING_TABLE'
status.global_stats << parse_global(parts[1..2]) if parts[0] == 'GLOBAL_STATS'
end
status
end
private_class_method def self.parse_client(client, headers)
headers.each_with_index do |header, i|
client[i] = parse_date(client[i]) if header.end_with?('Since')
client[i] = client[i].to_i if header.start_with?('Bytes')
end
client
end
private_class_method def self.parse_route(route, headers)
headers.each_with_index do |header, i|
route[i] = parse_date(route[i]) if header.end_with?('Last Ref')
end
route
end
private_class_method def self.parse_global(global)
global[1] = global[1].to_i
global
end
private_class_method def self.parse_date(date_string)
DateTime.strptime(date_string, '%a %b %d %k:%M:%S %Y')
rescue ArgumentError
DateTime.strptime(date_string, '%Y-%m-%d %k:%M:%S')
end
end
end
end
|
require 'grape'
require_relative 'janus/all'
require_relative 'terminus/middleware'
require_relative 'veritas/middleware'
require_relative 'hermes/all'
module Engine
class Records < Grape::API
if ENV['RACK_ENV'] != 'test'
use Veritas::Middleware
end
use Janus::Middleware
use Terminus::Middleware
use Hermes::Middleware
helpers Janus::Helpers
helpers Hermes::Helpers
rescue_from ActiveRecord::RecordNotFound do
Rack::Response.new \
[{ errors: ["Record not found"] }.to_json],
404,
{ "Content-Type" => "application/json" }
end
resource "/:collection_name" do
get do
{
meta: {
page: {
offset: params.offset || 1,
limit: 10,
total: current_repository.count
}
},
data: current_repository.all(params.offset, 10).map(&:to_h)
}
end
post do
validations = current_repository
.create(collection_params)
if validations.ok?
validations.result.to_h
else
status 400
{ errors: validations.errors }
end
end
put "/:id" do
record = current_repository.find(params.id)
validations = current_repository
.update(record, collection_params)
if validations.ok?
validations.result.to_h
else
status 400
{ errors: validations.errors }
end
end
delete "/:id" do
current_repository.delete params.fetch(:id)
end
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Column, type: :model do
context "validations" do
let(:board) { create :board }
let(:valid_params) { { board_id: board.id, name: 'some name' } }
it { expect(described_class.new(board: board)).not_to be_valid }
it { expect(described_class.new(valid_params)).to be_valid }
context 'name' do
before { create :column, valid_params }
it 'rejects duplicate column name on same board' do
expect(described_class.new(valid_params)).not_to be_valid
end
it 'accepts duplicate column name on different board' do
board2 = create :board, name: 'other board'
bad_params = { board: board2, name: valid_params[:name] }
expect(described_class.new(bad_params)).to be_valid
end
end
end
end
|
class UsersController < ApplicationController
before_action :user_instance, only: [:show, :update, :destroy]
def index
@users = User.all
end
def show
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
flash[:success] = "Welcome, #{@user.name}"
redirect_to profile_path
else
flash[:danger] = @user.errors.full_messages.join('<br/>').html_safe
render :new
end
end
def edit
@user = current_user
end
def update
if @user.update(user_params)
flash[:success] = 'Information Updated Successfully'
redirect_to profile_path
else
flash[:danger] = @user.errors.full_messages.join('<br/>').html_safe
end
end
def destroy
@user.destroy
flash[:success] = 'User Deleted'
redirect_to users_path
end
private
def user_params
params.require(:user).permit(:name, :phone_number, :email, :password, :password_confirmation, :favorites, :dislikes)
end
def user_instance
@user = User.find(params[:id])
end
end
|
class TwitchSummoner < ActiveRecord::Base
validates_presence_of :twitch_user, :summoner
validates_uniqueness_of :twitch_user_id, :scope => :summoner_id
belongs_to :twitch_user
belongs_to :summoner
def self.create_by_component(twitch_name, league_name, league_region)
twitch_user = TwitchUser.find_or_create_by(name: twitch_name)
summoner = Summoner.find_or_create_by(name: league_name, region: league_region)
begin
twitch_user.summoners << summoner
rescue ActiveRecord::RecordInvalid
end
twitch_user.twitch_summoners.find_by(summoner: summoner)
end
def to_code
sha = self.twitch_user.sha
id = self.summoner.id
"#{sha}-#{id}"
end
def to_url
sha = self.twitch_user.sha
id = self.summoner.id
"http://127.0.0.1:8080/app/#/#{sha}/#{id}"
end
end
|
source 'https://rubygems.org'
# Rails 的版本
gem 'rails', '3.2.13'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
# 資料庫的 gem
gem 'sqlite3'
gem 'haml'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
# 另一個 Javascript 的工具
gem 'coffee-rails', '~> 3.2.1'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platforms => :ruby
gem "less-rails"
# Javascript 壓縮工具
gem 'uglifier', '>= 1.0.3'
gem "therubyracer"
gem "twitter-bootstrap-rails"
end
# 給予 Rails 一個 Javascript 函式庫的框架
gem 'jquery-rails'
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# To use Jbuilder templates for JSON
# gem 'jbuilder'
# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'debugger'
gem 'mysql2'
gem 'bootstrap-sass'
gem "mongoid", "2.0.0.beta.20"
gem "bson_ext", "1.1.2" |
# encoding: utf-8
#
# --
# @author zires
#
module OpenQq
# 3.0表示OpenAPI版本, 小数点第二位表示SDK版本
VERSION = "3.0.3"
end
|
FactoryGirl.define do
factory :opendata_member_notice, class: Opendata::MemberNotice do
transient do
site nil
member nil
end
site_id { site.present? ? site.id : cms_site.id }
member_id { member.present? ? member.id : nil }
commented_count 11
confirmed { Time.zone.now }
end
end
|
class ToyRobot
attr_reader :position, :direction, :board
DIRECTIONS = [:north, :east, :south, :west]
COMMANDS = [:place, :move, :left, :right, :report]
def initialize(board)
raise TypeError, 'Invalid board' if board.nil?
@board = board
end
# Places the robot on the board in position X,Y and facing NORTH, SOUTH, EAST or WEST
def place(x, y, direction)
raise TypeError, 'Invalid coordinates' unless x.is_a? Integer and y.is_a? Integer
raise TypeError, 'Invalid direction' unless DIRECTIONS.include?(direction)
return false unless valid_position?(x, y)
@position = { x: x, y: y }
@direction = direction
true
end
# Moves the robot one unit forward in the direction it is currently facing
def move
return false if @position.nil?
movements = { north: { x: 0, y: 1 }, east: { x: 1, y: 0 }, south: { x: 0, y: -1 }, west: { x: -1, y: 0 } }
position, movement = @position, movements[@direction]
return false unless valid_position?(position[:x] + movement[:x], position[:y] + movement[:y])
@position = { x: position[:x] + movement[:x], y: position[:y] + movement[:y] }
true
end
# Rotates the robot 90 degrees LEFT and Right
rotate_parameter = { left: -1, right: 1 }
['left', 'right'].each do |rotate_direction|
define_method "rotate_#{rotate_direction}" do
return false if @direction.nil?
index = DIRECTIONS.index(@direction)
@direction = DIRECTIONS.rotate(rotate_parameter[rotate_direction.to_sym])[index]
true
end
end
# Returns the X,Y and Direction of the robot
def report
return "Not on board" if @position.nil? or @direction.nil?
"#{@position[:x]},#{@position[:y]},#{@direction.to_s.upcase}"
end
# Evals and executes a string command.
def eval(input)
return if input.strip.empty?
args = input.split(/\s+/)
command = args.first.to_s.downcase.to_sym
arguments = args.last
raise ArgumentError, 'Invalid command' unless COMMANDS.include?(command)
case command
when :place
raise ArgumentError, 'Invalid command' if arguments.nil?
tokens = arguments.split(/,/)
raise ArgumentError, 'Invalid command' unless tokens.count > 2
x = tokens[0].to_i
y = tokens[1].to_i
direction = tokens[2].downcase.to_sym
place(x, y, direction)
when :move
move
when :left
rotate_left
when :right
rotate_right
when :report
report
else
raise ArgumentError, 'Invalid command'
end
end
private
def valid_position?(x, y)
(x >= 0 && x <= self.board.columns && y >= 0 && y <= self.board.rows)
end
end |
# frozen_string_literal: true
if Rails.env.development? || Rails.env.test?
require 'rspec/core/rake_task'
require 'rubocop/rake_task'
namespace :ci do
desc 'Run specs'
RSpec::Core::RakeTask.new(:specs) do |t|
t.verbose = false
t.rspec_opts = ['--require turnip/rspec',
"--pattern '**/*_spec.rb,**/*.feature'",
'--format documentation',
'-t ~@skip-ci',
'--failure-exit-code 1']
end
desc 'Run rubocop'
RuboCop::RakeTask.new(:rubocop) do |t|
t.fail_on_error = true
t.verbose = false
t.formatters = ['RuboCop::Formatter::SimpleTextFormatter']
t.options = ['-D']
end
desc 'Deletes unneded files.'
task :clean do
dirs_to_clean = ["#{Rails.root}/spec/tmp/attachments/"]
dirs_to_clean.each do |dirname|
next unless File.directory?(dirname)
FileUtils.remove_dir(dirname)
end
end
desc 'Run things for ci'
task build: :clean do
puts "\033[34mRunning rubocop:\033[0m"
Rake::Task['ci:rubocop'].invoke
puts
puts "\033[34mRunning rspec:\033[0m"
ENV['COVERAGE'] = 'true'
Rake::Task['ci:specs'].invoke
end
end
end
|
class Membership < ActiveRecord::Base
self.table_name = 'grp_membership'
self.primary_key = :id
alias_attribute :group_id, :grp_id
alias_attribute :user_id, :usr_id
alias_attribute :start_date, :membership_start
alias_attribute :end_date, :membership_end
belongs_to :group, foreign_key: :grp_id
belongs_to :user, foreign_key: :usr_id
has_many :posts, foreign_key: :grp_member_id
has_many :post_types, through: :posts
LEADER_POST_ID = 3
PAST_LEADER_ID = 4
DEFAULT_POST_ID = 6
PEK_ADMIN_ID = 66
NEW_MEMBER_ID = 104
def leader?
has_post?(LEADER_POST_ID)
end
def newbie?
has_post?(DEFAULT_POST_ID) && end_date.nil? && !archived?
end
def new_member?
has_post?(NEW_MEMBER_ID) && active?
end
def pek_admin?
has_post?(PEK_ADMIN_ID)
end
def has_post?(post_id)
posts.any? { |post| post.post_type.id == post_id }
end
def archived?
!archived.nil?
end
def active?
!newbie? && end_date.nil? && !archived?
end
def inactive?
!end_date.nil? && !archived?
end
def post(post_type)
posts.find_by(post_type_id: post_type)
end
def primary?
active? && user.svie_member_type == SvieUser::INSIDE_MEMBER && user.primary_membership == self
end
def inactivate!
self.end_date = Time.now
user.update(delegated: false) if user.delegated && user.primary_membership == self
save
end
def reactivate!
self.end_date = nil
save
end
def archive!
self.archived = Time.now
user.update(delegated: false) if user.delegated && user.primary_membership == self
save
end
def unarchive!
self.archived = nil
save
end
def accept!
newbie_post = posts.find { |post| post.post_type.id == DEFAULT_POST_ID }
newbie_post.destroy
post_types << PostType.find(NEW_MEMBER_ID)
end
end
|
#in these simulations, I will be attempting to follow along with Primer's "Evolution" simulations,
#recreating each one he does, but in text instead of visually.
#Video 1, around 2:13
class Blob
attr_accessor :alive
def initialize(birth_chance, death_chance)
@birth_chance = birth_chance
@death_chance = death_chance
@alive = true
end
def tick
if rand(0..100) < @death_chance
die
end
end
def die
@alive = false
end
end
class History
attr_accessor :num_blobs, :average_blobs
def initialize(blobs, average)
@num_blobs = blobs
@average_blobs = average
end
end
class Sim
attr_accessor :birth_chance, :death_chance, :history, :blobs
def initialize(birth_chance, death_chance)
@birth_chance = birth_chance
@death_chance = death_chance
@history = []
@blobs = []
end
def tick
puts "new tick"
display_stats
if rand(1..100) < @birth_chance
@blobs.push Blob.new(@birth_chance, @death_chance)
end
@blobs.each {|blob| blob.tick}
enter_history
end
def enter_history
@history.push History.new(num_blobs, average_blobs)
end
def num_blobs
num = 0
@blobs.each do |blob|
if blob.alive
num += 1
end
end
num
end
def average_blobs
total = 0
@history.each do |event|
total += event.num_blobs
end
if @history.length == 0
0
else
total/@history.length
end
end
def display_stats
puts "- -" * 20
puts "ticks: #{@history.length}"
puts "total blobs: #{num_blobs}"
puts "Average blobs: #{average_blobs}"
puts "Birth chance: #{@birth_chance}"
puts "Death chance: #{@death_chance}"
puts "Expected Equillibrium: #{@birth_chance / @death_chance}"
end
end
puts "Commands:"
puts "ENTER - next tick"
# puts "### - number of ticks"
# puts "stop - stop simulation"
sim1 = Sim.new(80, 2)
input = gets.chomp
while input.empty?
sim1.tick
input = gets.chomp
end
|
# == Schema Information
#
# Table name: quotes
#
# id :integer not null, primary key
# ac26_signed_on :date
# ac2_signed_on :date
# check_number :string
# contract_signed_on :date
# created_by :string
# current_payroll_period_lower_date :date
# current_payroll_period_upper_date :date
# current_payroll_year :integer
# effective_end_date :date
# effective_start_date :date
# experience_period_lower_date :date
# experience_period_upper_date :date
# fees :float
# group_code :string
# invoice_number :string
# invoice_signed_on :date
# paid_amount :float
# paid_date :date
# program_type :integer
# program_year :integer
# program_year_lower_date :date
# program_year_upper_date :date
# questionnaire_question_1 :boolean
# questionnaire_question_2 :boolean
# questionnaire_question_3 :boolean
# questionnaire_question_4 :boolean
# questionnaire_question_5 :boolean
# questionnaire_question_6 :boolean
# questionnaire_signed_on :date
# quote :string
# quote_date :date
# quote_generated :string
# quote_tier :float
# quote_year :integer
# quote_year_lower_date :date
# quote_year_upper_date :date
# status :integer
# u153_signed_on :date
# updated_by :string
# created_at :datetime not null
# updated_at :datetime not null
# account_id :integer
#
# Indexes
#
# index_quotes_on_account_id (account_id)
#
# Foreign Keys
#
# fk_rails_... (account_id => accounts.id)
#
require 'rails_helper'
RSpec.describe Quote, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
|
require 'pry'
def second_supply_for_fourth_of_july(holiday_hash)
# given that holiday_hash looks like this:
# {
# :winter => {
# :christmas => ["Lights", "Wreath"],
# :new_years => ["Party Hats"]
# },
# :summer => {
# :fourth_of_july => ["Fireworks", "BBQ"]
# },
# :fall => {
# :thanksgiving => ["Turkey"]
# },
# :spring => {
# :memorial_day => ["BBQ"]
# }
# }
# return the second element in the 4th of July array
holiday_hash[:summer][:fourth_of_july][1]
end
def add_supply_to_winter_holidays(holiday_hash, supply)
holiday_hash.each do |season,data|
if season == :winter
data.each {|holiday,array| array.push(supply)}
end
end
end
def add_supply_to_memorial_day(holiday_hash, supply)
holiday_hash[:spring][:memorial_day].push(supply)
end
def add_new_holiday_with_supplies(holiday_hash, season, holiday_name, supply_array)
holiday_hash[season][holiday_name] = supply_array
end
def all_winter_holiday_supplies(holiday_hash)
winter_values = holiday_hash[:winter].values
winter_values.flatten
end
def all_supplies_in_holidays(holiday_hash)
# iterate through holiday_hash and print items such that your readout resembles:
# Winter:
# Christmas: Lights, Wreath
# New Years: Party Hats
# Summer:
# Fourth Of July: Fireworks, BBQ
# etc.
holiday_hash.each do |season,data|
puts "#{season.capitalize}:"
data.each do |holiday,supplies|
holiday_string = holiday.to_s
split_holiday_string = holiday_string.split("_")
cap_holiday_string = split_holiday_string.collect {|word| word.capitalize}
joined_holiday_string = cap_holiday_string.join(" ")
puts " #{joined_holiday_string}: #{supplies.join(", ")}"
end
end
end
def all_holidays_with_bbq(holiday_hash)
# return an array of holiday names (as symbols) where supply lists
# include the string "BBQ"
holiday_with_BBQ = []
holiday_hash.each do |season,data|
data.each do |holiday,supply|
if supply.include?("BBQ") == true
holiday_with_BBQ.push(holiday)
end
end
end
holiday_with_BBQ
end
|
require 'sinatra'
require 'sinatra/json'
require 'sinatra/activerecord'
set :database_file, 'database.yml'
class Resource < ActiveRecord::Base
validates :name, presence: true, uniqueness: true
end
get '/' do
json Resource.select('id', 'name').all
end
get '/:id' do
resource = Resource.find_by_id(params[:id])
if resource
halt 206
json resource
else
halt 404
end
end
post '/' do
resource = Resource.create(params)
if resource
json resource
else
halt 500
end
end
patch '/:id' do
resource = Resource.find_by_id(params[:id])
if resource
resource.update(params)
else
halt 404
end
end
delete '/:id' do
resource = Resource.find_by_id(params[:id])
if resource
resource.destroy
else
halt 404
end
end
|
require 'json'
def response(data = nil, opts = {})
if data
opts.merge! body: JSON.dump(data)
opts[:headers] ||= {}
opts[:headers].merge! 'Content-Type' => 'application/json'
end
opts
end
|
require_relative 'node'
class BinarySearchTree
def initialize(root)
@root = root
end
def insert(root, node)
current = root
while true
if node.rating < current.rating
if current.left
current = current.left
else
current.left = node
return
end
elsif node.rating > current.rating
if current.right
current = current.right
else
current.right = node
return
end
else
# duplicate value
return nil
end
end
end
# Recursive Depth First Search
def find(root, data) # data is a title, not a node
if root.title == data
# base case, data matches
return root
else
if root.left
left = find(root.left, data)
end
if root.right
right = find(root.right, data)
end
if left
return left
elsif right
return right
else
# no match found toward the left or the right
return nil
end
end
end
def delete(root, data) # data is a title, not a node
parent = findParent(root, data)
if parent == true
# matching node is the tree root
@root = nil
elsif parent == nil
# no matching node found
return nil
else
if (parent.left) && (parent.left.title == data)
nextNode = parent.left
else
nextNode = parent.right
end
if nextNode.rating < parent.rating
parent.left = nextNode.left
else
parent.right = nextNode.left
end
end
end
# written as a helper function for delete
# same as find, except tracks & returns parent of the matching node
def findParent(root, data, parent=true)
if root.title == data
# base case, data matches
return parent
else
if root.left
left = findParent(root.left, data, root)
end
if root.right
right = findParent(root.right, data, root)
end
if left
return left
elsif right
return right
else
# no match found toward the left or the right
return nil
end
end
end
# Recursive Breadth First Search
#def printf(children=nil) <- suggested by Bloc
def printf(list=[@root], output='')
# remove front list item & add it to the output
first = list.shift()
print_string = first.title + ': ' + first.rating.to_s + "\n"
output << print_string
# add its children to the back of the list
if first.left
list << first.left
end
if first.right
list << first.right
end
# repeat until all nodes have been visited, then print output
if list.empty?
puts output
return
else
printf(list, output)
end
end
end
|
class CommentsController < ApplicationController
def create
comment = Comment.new comment_params
if comment.save
redirect_to :back
else
flash[:errors] = post.errors.full_messages
redirect_to :back
end
end
def destroy
Comment.find(params[:id]).destroy
redirect_to :back
end
private
def comment_params
params.require(:comment).permit(:content, :user_id, :post_id, :name)
end
end
|
require "date"
module Models
class Rental
attr_accessor :car
attr_accessor :id, :car_id, :start_date, :end_date, :distance, :deductible_reduction
attr_accessor :transactions
attr_accessor :rental_modifications
# Should be read from config or database, but constants are fine for now
DEDUCTIBLE_FEE_PER_DAY = 400
PROFIT_MARGIN = 0.3
INSURANCE_PERCENT = 0.5
ASSISTANCE_FEE = 100
DAY_DISCOUNTS = {
"2..4" => 0.9,
"5..10" => 0.7,
"10+" => 0.5
}
def initialize data
data.each_pair do |k, v|
self.send "#{k}=".to_sym , v
end
@transactions = []
end
def start_date=(date)
@start_date = date.is_a?(Date) ? date : Date.parse(date)
end
def end_date=(date)
@end_date = date.is_a?(Date) ? date : Date.parse(date)
end
def duration
(end_date - start_date).to_i + 1 # last day included
end
def actors
[ :driver, :owner, :insurance, :assistance, :drivy ]
end
def distribute_funds!
actors.each do |destination|
amount = case destination
when :driver
-driver_price
when :owner
to_owner
when :insurance
commission[:insurance_fee]
when :assistance
commission[:assistance_fee]
when :drivy
drivy_profit
end
@transactions << Models::Transaction.new(item: self, destination: destination, amount: amount)
end
end
def deductible_fee
if deductible_reduction
duration * DEDUCTIBLE_FEE_PER_DAY
else
0
end
end
def driver_price
price + deductible_fee
end
def drivy_profit
commission[:drivy_fee] + deductible_fee
end
def to_owner
price - (price * PROFIT_MARGIN).floor
end
def commission
income = price - to_owner
[:insurance_fee, :assistance_fee, :drivy_fee].inject({}) do |sum, n|
case n
when :insurance_fee
sum[n] = (income - (income *= INSURANCE_PERCENT)).ceil # no extra penny for gangsters
when :assistance_fee
sum[n] = (income - (income -= ASSISTANCE_FEE * duration )).ceil
else
# this is obviously not correct, watch Office Space movie
# for careful accounting, matters of cents do count as well
sum[n] = income.floor
end
sum
end
end
def price
daily_prices = []
(1..duration).each do |day|
case day
when 1
daily_prices << car.price_per_day
when 2..4
daily_prices << car.price_per_day * DAY_DISCOUNTS["2..4"]
when 5..10
daily_prices << car.price_per_day * DAY_DISCOUNTS["5..10"]
else
daily_prices << car.price_per_day * DAY_DISCOUNTS["10+"]
end
end
daily_prices.inject(:+).floor + (distance * car.price_per_km)
end
end
end |
class UsersController < ApplicationController
before_action :authenticate_user!
def show
@bookmarks = current_user.bookmarks.all
@tags = user_tags
@likes = tag_contains_likes
end
def update
if current_user.update_attributes(user_params)
redirect_to edit_user_registration_path, notice: "User information updated."
else
render "devise/registrations/edit"
end
end
private
def user_params
params.require(:user).permit(:name)
end
def user_tag_ids
@bookmarks.map do |b|
b.tags.pluck(:id)
end
end
def user_tags
# Unique tags only
tag_ids_array = user_tag_ids.flatten.uniq
tag_ids_array.map do |tag_id|
Tag.find(tag_id)
end
end
def user_liked_tag_ids
@likes.map do |like|
like.bookmark.id
end
end
def tag_contains_likes
all_tags = Tag.all
tag_contains_liked_bookmark = []
all_tags.map do |tag|
# check if tag contains liked bookmarks and add to array
if current_user.likes.find_by(bookmark_id: tag.bookmarks.map(&:id))
tag_contains_liked_bookmark << tag.id
end
end
tag_contains_liked_bookmark.reject
end
end |
class AddMatchIndex < ActiveRecord::Migration
def change
add_index :matches, :match_id
end
end
|
require 'minitest/autorun'
require 'minitest/pride'
require 'csv'
require './lib/transaction-repo'
class TestTransactionRepository < Minitest::Test
def test_we_can_initialize_transactions
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal CSV::Table, t_repo.transactions.class
end
def test_we_can_make_transaction_id_with_table
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal "1", t_repo.make_transactions.first.id
end
def test_we_can_make_transaction_credit_card_number_with_table
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal "4654405418249632", t_repo.make_transactions.first.credit_card_number
end
def test_we_can_make_transaction_invoice_id_with_table
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal "1", t_repo.make_transactions.first.invoice_id
end
def test_we_can_make_transaction_credit_card_experation_date_with_table
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal nil, t_repo.all.first.credit_card_expiration_date
end
def test_we_can_make_transaction_result_with_table
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal "success", t_repo.make_transactions.first.result
end
def test_we_can_make_transaction_creation_date_with_table
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal "2012-03-27 14:54:10 UTC", t_repo.make_transactions.last.created_at
end
def test_we_can_make_transaction_update_time_with_table
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal "2012-03-27 14:54:10 UTC", t_repo.make_transactions.last.updated_at
end
def test_all_transactions
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.all.first.class
end
def test_random_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.random.class
end
def test_find_by_id_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_by_id("2").class
end
def test_find_by_invoice_id_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_by_invoice_id("1").class
end
def test_find_by_credit_card_number_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_by_credit_card_number("4515551623735607").class
end
def test_find_by_credit_card_expiration_date_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_by_credit_card_expiration_date(nil).class
end
def test_find_by_result_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_by_result("success").class
end
def test_find_by_created_at_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_by_created_at("2012-03-27 14:54:10 UTC").class
end
def test_find_by_updated_at_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_by_updated_at("2012-03-27 14:54:10 UTC").class
end
def test_find_all_by_id_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_all_by_id("2").last.class
end
def test_find_all_by_invoice_id_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_all_by_invoice_id("1").first.class
end
def test_find_all_by_credit_card_number_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_all_by_credit_card_number("4515551623735607").first.class
end
def test_find_all_by_credit_card_expiration_date_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_all_by_credit_card_expiration_date(nil).first.class
end
def test_find_all_by_result_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_all_by_result("success").first.class
end
def test_find_all_by_created_at_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_all_by_created_at("2012-03-27 14:54:10 UTC").first.class
end
def test_find_all_by_updated_at_method
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRepository.new(data)
assert_equal Transaction, t_repo.find_all_by_updated_at("2012-03-27 14:54:10 UTC").first.class
end
end |
# == Schema Information
#
# Table name: invoices
#
# id :bigint not null, primary key
# billing_date :date
# number :string
# payment_date :date
# total :float
# your_references :string
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint not null
#
# Indexes
#
# index_invoices_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
class Invoice < ApplicationRecord
belongs_to :user
DUTCH_TAX = 0.21
has_many :invoice_fields, inverse_of: :invoice
accepts_nested_attributes_for :invoice_fields, reject_if: :all_blank, allow_destroy: true
before_validation do
self.number = generate_number
self.total = count_total
end
def generate_number
loop do
gen = "invoice-#{Date.today}-#{SecureRandom.hex(4)}"
break gen if Invoice.find_by(number: gen).blank?
end
end
def count_total
arr = invoice_fields.map do |invoice_field|
invoice_field.total = invoice_field.count_total
invoice_field.total
end
arr.sum
end
def tax
total.to_f * DUTCH_TAX
end
def total_with_tax
total * (1 + DUTCH_TAX)
end
end
|
class FixturesController < ApplicationController
before_action :authenticate_user!
before_action :set_fixture, only: [:show, :edit, :update, :destroy]
def index
@fixtures = Fixture.all
end
def new
@fixture = Fixture.new
end
def create
Fixture.create(fixture_params)
redirect_to(fixtures_path)
end
def show
end
def destroy
@fixture.destroy
redirect_to(fixtures_path)
end
def edit
end
def update
@fixture.update(fixture_params)
redirect_to(fixtures_path)
end
private
def set_fixture
@fixture = Fixture.find(params[:id])
end
def fixture_params
params.require(:fixture).permit(:result, :home_team_id, :away_team_id)
end
end |
module PingPong
class Service
def initialize(match:, victor:)
@match = match
@victor = victor
end
def record!
if @match.finished?
false
elsif !@match.first_service
# This is a rally for service, winner has first serve
@match.first_service_by = @victor
else
# Record this point for the winner
@match.points.create! victor: @victor
end
end
end
end
|
class Indocker::ContextArgs
attr_reader :parent, :name
def initialize(name, context_args, parent, container = nil)
@name = name
@parent = parent
@container = container
@context_args = context_args
end
def method_missing(name, *args)
if args.size > 0
raise ArgumentError.new("context args does not accept any arguments")
end
value = @context_args.fetch(name) do
Indocker.logger.warn("build arg '#{format_arg(name)}' is not defined#{@container ? " for container :#{@container.name}" : ""}")
Indocker.logger.warn("available args: #{@context_args.inspect}")
nil
end
if value.is_a?(Hash)
Indocker::ContextArgs.new(name, value, self, @container)
else
value
end
end
private
def format_arg(name)
string = name
parent = @parent
while parent do
name = parent.name
string = "#{name}.#{string}" if name
parent = parent.parent
break if !parent
end
string
end
end |
require 'spec_helper'
describe LocaleFlash::Config do
let(:config) { LocaleFlash::Config }
# Config follows a singleton concept, so ensure goes back to default
# after for every spec.
after { config.template = LocaleFlash::Config::DEFAULT_TEMPLATE }
describe '#template and #template=' do
it 'returns the default template when nothing is configured' do
config.template.should eq LocaleFlash::Config::DEFAULT_TEMPLATE
end
it 'returns the configured template if available' do
template = -> { render 'layouts/flash', type: type, message: message }
config.template = template
config.template.should eq template
end
end
end
|
def recursive_dump(export_path, page)
FileUtils.mkdir_p export_path
unless page.description && page.description.match(/ignore_export/)
puts "exporting #{page.title}"
recursive_path = File::join(export_path, page.title.parameterize)
File.open("#{recursive_path}.yml", 'w') do |out|
page_hash = page.attributes.reject{|key,value| %w{ layout_id parent_id virtual position delta published_at status_id lock_version updated_by_id created_at updated_at skin_page site_id id created_by_id}.include?(key)}
page_hash["layout_name"] = page.layout.name if page.layout_id
out.write(page_hash.to_yaml)
end
parts_path = "#{recursive_path}_parts"
FileUtils.mkdir_p parts_path
page.parts.each do |part|
File.open(File.join(parts_path,"#{part.name.parameterize}.yml"), 'w') do |out|
part_hash = part.attributes.reject{|key,value| %w{ skin_page_part id page_id content}.include?(key)}
out.write(part_hash.to_yaml)
end
File.open(File.join(parts_path,"#{part.name.parameterize}.#{part.filter.filter_name.nil? ? "html": part.filter.filter_name.downcase}"), 'w') do |out|
out.write(part.content)
end
end
page.children.each do |child|
recursive_dump("#{recursive_path}_children", child)
end
end
end
namespace :radiant do
namespace :extensions do
namespace :site_theme do
desc "Runs the migration of the Site Theme extension"
task :migrate => :environment do
require 'radiant/extension_migrator'
if ENV["VERSION"]
SiteThemeExtension.migrator.migrate(ENV["VERSION"].to_i)
else
SiteThemeExtension.migrator.migrate
end
end
desc "Copies public assets of the Site Theme to the instance public/ directory."
task :update => :environment do
is_svn_or_dir = proc { |path| path =~ /\.svn/ || File.directory?(path) }
puts "Copying assets from SiteThemeExtension"
Dir[SiteThemeExtension.root + "/public/**/*"].reject(&is_svn_or_dir).each do |file|
path = file.sub(SiteThemeExtension.root, '')
directory = File.dirname(path)
mkdir_p RAILS_ROOT + directory, :verbose => false
cp file, RAILS_ROOT + path, :verbose => false
end
end
desc "export pages to path, use SITE_ID and EXPORT_PATH to specify options"
task :export_pages => :environment do
require 'highline/import'
say "ERROR: you must specify a SITE_ID #{ENV['SITE_ID']}" and exit if !ENV['SITE_ID']
export_path = ENV['EXPORT_PATH'] ? ENV['EXPORT_PATH'] : File::join(RAILS_ROOT, 'tmp', 'export','pages')
root_page = Page.find(:first, :conditions => ["site_id = ? AND slug = ?", ENV['SITE_ID'], "/"])
recursive_dump(export_path, root_page)
end
desc "export snippets to path, use SITE_ID and EXPORT_PATH to specify options"
task :export_snippets => :environment do
require 'highline/import'
say "ERROR: you must specify a SITE_ID #{ENV['SITE_ID']}" and exit if !ENV['SITE_ID']
export_path = ENV['EXPORT_PATH'] ? ENV['EXPORT_PATH'] : File::join(RAILS_ROOT, 'tmp', 'export','snippets')
FileUtils.mkdir_p export_path
Snippet.find(:all,:conditions => ["site_id = ? ", ENV['SITE_ID']]).each do |snippet|
puts "exporting #{snippet.name}"
extension = snippet.filter.filter_name.nil? ? "html" : snippet.filter.filter_name.downcase
path = File::join(export_path, "#{snippet.name.strip}.#{extension}")
File.open("#{path}", 'w') do |out|
out.write(snippet.content)
end
end
end
desc "export stylesheets to path, use SITE_ID and EXPORT_PATH to specify options"
task :export_stylesheets => :environment do
require 'highline/import'
say "ERROR: you must specify a SITE_ID #{ENV['SITE_ID']}" and exit if !ENV['SITE_ID']
export_path = ENV['EXPORT_PATH'] ? ENV['EXPORT_PATH'] : File::join(RAILS_ROOT, 'tmp', 'export','stylesheets')
FileUtils.mkdir_p export_path
Stylesheet.find(:all,:conditions => ["site_id = ? ", ENV['SITE_ID']]).each do |stylesheet|
puts "exporting #{stylesheet.name}"
path = File::join(export_path, stylesheet.name)
File.open("#{path}", 'w') do |out|
out.write(stylesheet.content)
end
end
end
desc "export javascripts to path, use SITE_ID and EXPORT_PATH to specify options"
task :export_javascripts => :environment do
require 'highline/import'
say "ERROR: you must specify a SITE_ID #{ENV['SITE_ID']}" and exit if !ENV['SITE_ID']
export_path = ENV['EXPORT_PATH'] ? ENV['EXPORT_PATH'] : File::join(RAILS_ROOT, 'tmp', 'export','javascripts')
FileUtils.mkdir_p export_path
Javascript.find(:all,:conditions => ["site_id = ? ", ENV['SITE_ID']]).each do |javascript|
puts "exporting #{javascript.name}"
path = File::join(export_path, javascript.name)
File.open("#{path}", 'w') do |out|
out.write(javascript.content)
end
end
end
desc "export forms to path, use SITE_ID and EXPORT_PATH to specify options"
task :export_forms => :environment do
require 'highline/import'
say "ERROR: you must specify a SITE_ID #{ENV['SITE_ID']}" and exit if !ENV['SITE_ID']
export_path = ENV['EXPORT_PATH'] ? ENV['EXPORT_PATH'] : File::join(RAILS_ROOT, 'tmp', 'export','forms')
FileUtils.mkdir_p export_path
Form.find(:all,:conditions => ["site_id = ? ", ENV['SITE_ID']]).each do |form|
puts "exporting #{form.title}"
path = File::join(export_path, form.title.parameterize)
File.open("#{path}.yml", 'w') do |out|
out.write(form.attributes.reject{|key,value| %w{body config content updated_by_id created_at updated_at skin site_id id created_by_id}.include?(key)}.to_yaml)
end
FileUtils.mkdir_p path
%w{body content config}.each do |part|
File.open(File.join(path,part), 'w') do |out|
out.write(form.send(part))
end
end
end
end
desc "export layouts to path, use SITE_ID and EXPORT_PATH to specify options"
task :export_layouts => :environment do
require 'highline/import'
say "ERROR: you must specify a SITE_ID #{ENV['SITE_ID']}" and exit if !ENV['SITE_ID']
export_path = ENV['EXPORT_PATH'] ? ENV['EXPORT_PATH'] : File::join(RAILS_ROOT, 'tmp', 'export','layouts')
FileUtils.mkdir_p export_path
Layout.find(:all,:conditions => ["site_id = ? ", ENV['SITE_ID']]).each do |layout|
puts "exporting #{layout.name}"
path = File::join(export_path, layout.name)
File.open("#{path}.yml", 'w') do |out|
out.write(layout.attributes.reject{|key,value| %w{ content lock_version updated_by_id created_at updated_at skin_layout site_id id created_by_id}.include?(key)}.to_yaml)
end
File.open(path, 'w') do |out|
out.write(layout.content)
end
end
end
desc "export site, use SITE_ID and EXPORT_PATH to specify options"
task :export_site => :environment do
Rake::Task['radiant:extensions:site_theme:export_stylesheets'].execute
Rake::Task['radiant:extensions:site_theme:export_javascripts'].execute
Rake::Task['radiant:extensions:site_theme:export_layouts'].execute
Rake::Task['radiant:extensions:site_theme:export_pages'].execute
Rake::Task['radiant:extensions:site_theme:export_forms'].execute
Rake::Task['radiant:extensions:site_theme:export_snippets'].execute
end
end
end
end
|
class Connection < ActiveRecord::Base
belongs_to :engine, foreign_key: "engineName", primary_key: "engineName"
default_scope {order(:idconnections => :ASC)}
end |
# frozen_string_literal: true
require 'spec_helper'
class HappyPath
include RailwayOperation::Operator
add_step 0, :step1
add_step 0, :step2
add_step 0, :step3
def step1(argument, **_info)
argument << :step1
end
def step2(argument, **_info)
argument << :step2
end
def step3(argument, **_info)
argument << :step3
end
end
class NoSteps
include RailwayOperation::Operator
end
describe 'smoke test RailwayOperation::Operator' do
describe '.run' do
it 'executes the steps in the operation' do
result, info = HappyPath.run([])
expect(result).to eq([:step1, :step2, :step3])
expect(info.execution).to eq(
[
{ track_identifier: 0, step_index: 0, argument: [], noop: false },
{ track_identifier: 0, step_index: 1, argument: [:step1], noop: false },
{ track_identifier: 0, step_index: 2, argument: [:step1, :step2], noop: false },
{ track_identifier: 0, step_index: 3, argument: [:step1, :step2, :step3], noop: true }
]
)
end
it 'does not mutate arguments passed to the operation' do
argument = ["don't change"]
result, info = HappyPath.run(argument)
expect(argument).to eq(["don't change"])
expect(result).to eq(["don't change", :step1, :step2, :step3])
expect(info.execution).to eq(
[
{ track_identifier: 0, step_index: 0, argument: ["don't change"], noop: false },
{ track_identifier: 0, step_index: 1, argument: ["don't change", :step1], noop: false },
{ track_identifier: 0, step_index: 2, argument: ["don't change", :step1, :step2], noop: false },
{ track_identifier: 0, step_index: 3, argument: ["don't change", :step1, :step2, :step3], noop: true }
]
)
end
it 'can accept splatted hash' do
result, info = HappyPath.run([:original])
expect(result).to eq([:original, :step1, :step2, :step3])
expect(info.execution).to eq(
[
{ track_identifier: 0, step_index: 0, argument: [:original], noop: false },
{ track_identifier: 0, step_index: 1, argument: [:original, :step1], noop: false },
{ track_identifier: 0, step_index: 2, argument: [:original, :step1, :step2], noop: false },
{ track_identifier: 0, step_index: 3, argument: [:original, :step1, :step2, :step3], noop: true }
]
)
end
it 'does nothing when no steps are specified' do
argument = 'noop'
result, info = NoSteps.run(argument)
expect(result).to eq(argument)
expect(info.execution).to eq(
[{ track_identifier: 0, step_index: 0, argument: 'noop', noop: true }]
)
end
end
end
|
class Itpro < ActiveRecord::Base
has_many :tickets
def show_serviced_users
ticket_ids = Ticket.where(itpro_id: self.id, status: 'done').pluck(:user_id)
User.find(ticket_ids)
end
def show_servicing_users
ticket_ids = Ticket.where(itpro_id: self.id, status: 'in_work').pluck(:user_id)
User.find(ticket_ids)
end
end
|
class UsersController < ApplicationController
def new
session[:user_id] = nil if logged_in?
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to user_path(@user)
else
@errors = @user.errors.full_messages
render :new
end
end
def show
@user = User.find_by(id: current_user.try(:id))
ein = @user.current_charity_ein
url = "data.orghunter.com/v1/charitysearch?user_key=#{ENV['CHARITY_TOKEN']}&ein=#{ein}"
encoded_url = URI.encode(url)
response = HTTParty.get('http://'"#{encoded_url}")
@charity = response['data'][0]
if logged_in? && @user.id == session[:user_id]
@user.update_bucket
@user.save
if request.xhr?
render json: @user
else
render :show
end
else
redirect_to new_session_path
end
end
def edit
if logged_in?
@user = User.find_by(id: current_user.try(:id))
else
redirect_to new_session_path
end
end
def update
@user = User.find_by(id: current_user.try(:id))
@user.update_attributes(user_params)
@user.cap_donation
render :edit
end
# this is a custom update just to update the charity. so in future if we are updating user information, it can be completely separate from the update method.
def charity_update
@user = User.find_by(id: current_user.try(:id))
@user.current_charity_ein = params[:charity_ein]
@user.current_charity_name = params[:charity_name].titleize
@user.save
redirect_to user_path(@user)
end
def charity_pause
@user = User.find_by(id: current_user.try(:id))
@user.stop_donation
redirect_to user_path(@user)
end
def donation_history
if logged_in? && params[:id].to_i == current_user.id
user = User.find_by(id: params[:id].to_i)
if user
@donations = user.donations.where(:pending => false).order(updated_at: :desc)
render :history
else
redirect_to root_path
end
else
redirect_to new_session_path
end
end
private
def user_params
params.require(:user).permit(:password, :email, :first_name, :last_name, :max_donation)
end
end
|
#!/usr/bin/env ruby
gem 'minitest', '>= 5.0.0'
require 'minitest/autorun'
require_relative 'code'
class RaindropsTest < Minitest::Test
def test_3
assert_equal 'Pling', Raindrops.convert(3)
end
def test_5
assert_equal 'Plang', Raindrops.convert(5)
end
def test_7
assert_equal 'Plong', Raindrops.convert(7)
end
def test_8
assert_equal '8', Raindrops.convert(8)
end
def test_105
assert_equal 'PlingPlangPlong', Raindrops.convert(105)
end
end
|
require "rails_helper"
RSpec.describe Api::V1::SessionsController, type: :controller do
describe "GET#index" do
before(:each) do
User.create(username: "Penguin", password: "ilovepenguins")
end
it "returns the current user hash when a user is signed in" do
session[:user_id] = 1
response = get :index
parsed_json = JSON.parse(response.body)
expect(parsed_json).to be_kind_of(Hash)
end
it "does not return a different type of object when a user is signed in" do
session[:user_id] = 1
response = get :index
parsed_json = JSON.parse(response.body)
expect(parsed_json).to_not be_kind_of(Array)
expect(parsed_json).to_not be_kind_of(Symbol)
expect(parsed_json).to_not be_kind_of(String)
end
it "returns the correct id" do
session[:user_id] = 1
response = get :index
parsed_json = JSON.parse(response.body)
expect(parsed_json["id"]).to eq(1)
end
it "returns the correct username" do
session[:user_id] = 1
response = get :index
parsed_json = JSON.parse(response.body)
expect(parsed_json["username"]).to eq("Penguin")
end
it "does not return the password" do
session[:user_id] = 1
response = get :index
parsed_json = JSON.parse(response.body)
expect(parsed_json["password"]).to eq(nil)
expect(parsed_json["password_digest"]).to eq(nil)
end
it "returns nil when there is no user signed in" do
response = get :index
expect(JSON.parse(response.body)).to eq(nil)
end
end
describe "POST#create" do
before(:each) do
User.create(username: "Penguin", password: "ilovepenguins")
end
context "when the user provides a valid username and password" do
it "returns a user hash" do
payload = { username: "Penguin", password: "ilovepenguins" }.to_json
response = post :create, body: payload
parsed_json = JSON.parse(response.body)
expect(parsed_json).to be_kind_of(Hash)
end
it "does not return a different type of object when a user is signed in" do
payload = { username: "Penguin", password: "ilovepenguins" }.to_json
response = post :create, body: payload
parsed_json = JSON.parse(response.body)
expect(parsed_json).to_not be_kind_of(Array)
expect(parsed_json).to_not be_kind_of(Symbol)
expect(parsed_json).to_not be_kind_of(String)
end
it "returns the correct id" do
payload = { username: "Penguin", password: "ilovepenguins" }.to_json
response = post :create, body: payload
parsed_json = JSON.parse(response.body)
expect(parsed_json["user"]["id"]).to eq(1)
end
it "returns the correct username" do
payload = { username: "Penguin", password: "ilovepenguins" }.to_json
response = post :create, body: payload
parsed_json = JSON.parse(response.body)
expect(parsed_json["user"]["username"]).to eq("Penguin")
end
it "does not return the password" do
payload = { username: "Penguin", password: "ilovepenguins" }.to_json
response = post :create, body: payload
parsed_json = JSON.parse(response.body)
expect(parsed_json["user"]["password"]).to eq(nil)
expect(parsed_json["user"]["password_digest"]).to eq(nil)
end
it "sets the user id in the session hash" do
payload = { username: "Penguin", password: "ilovepenguins" }.to_json
response = post :create, body: payload
expect(session[:user_id]).to eq(1)
end
it "does not put something else in the session hash" do
payload = { username: "Penguin", password: "ilovepenguins" }.to_json
response = post :create, body: payload
expect(session[:user_id]).to_not eq("1")
expect(session[:user_id]).to_not eq(2)
expect(session[:user_id]).to_not eq(nil)
end
end
context "when the user provides an invalid username or password" do
it "returns a response that cannot be parsed" do
payload = { username: "bad_data", password: "bad_data" }.to_json
response = post :create, body: payload
expect{ JSON.parse(response.body) }.to raise_error(JSON::ParserError)
end
it "returns the correct body" do
payload = { username: "bad_data", password: "bad_data" }.to_json
response = post :create, body: payload
expect(response.body).to eq("Invalid email or password")
end
it "returns a 403" do
payload = { username: "bad_data", password: "bad_data" }.to_json
response = post :create, body: payload
expect(response.status).to eq(403)
end
end
end
describe "GET#destroy" do
before(:each) do
User.create(username: "Penguin", password: "ilovepenguins")
end
it "sets the user_id in the session has to nil" do
session[:user_id] = 1
response = get :destroy
expect(session[:user_id]).to eq(nil)
end
it "returns the correct body" do
session[:user_id] = 1
response = get :destroy
expect(response.body).to eq("Successfully logged out")
end
it "returns a 200" do
session[:user_id] = 1
response = get :destroy
expect(response.status).to eq(200)
end
it "returns a response that cannot be parsed" do
session[:user_id] = 1
response = get :destroy
expect{ JSON.parse(response.body) }.to raise_error(JSON::ParserError)
end
end
end
|
# https://en.wikipedia.org/wiki/Solitaire_(cipher)
#
# ENCYPTING MESSAGE
# 1. Discard any non A to Z characters, and uppercase all remaining letters.
# Split the message into five character groups, using Xs to pad the last group, if needed.
# 2. Use Solitaire to generate a keystream letter for each letter in the message.
# 3. Convert the message from step 1 into numbers, A = 1, B = 2, etc:
# 4. Convert the keystream letters from step 2 using the same method:
# 5. Add the message numbers from step 3 to the keystream numbers from step 4 and subtract 26 from the result if it is greater than 26.
# 6. Convert the numbers from step 5 back to letters:
#
class Encryptor
def initialize(keygen)
@keygen = keygen
end
def scrunch(msg)
msg.upcase!
msg.gsub!(/[^A-Z]/, "")
msg << "X" * ((5 - msg.length % 5) % 5)
end
def mod(num)
num -= 26 if num > 26
num += 26 if num < 1
num
end
def process(msg, &cryptor)
scrunched = scrunch(msg).chars.map {|char| (mod(cryptor.call(char)) + 64).chr}.join
scrunched.scan(/.{5}/).join(" ")
end
def encrypt(msg)
process(msg) { |char| char.ord - 64 + @keygen.get_key }
end
def decrypt(msg)
process(msg) { |char| char.ord - 64 - @keygen.get_key }
end
end
# GENERATE KEYSTREAM
# 1. Key the decks by shuffling or using some secret indicator. (This script, however, will be using UNKEYED decks.)
# 2. Move Joker A one card down, then move Joker B two cards down.
# 3. Perform triple cut around Jokers.
# 4. Perform count cut using bottom cards value.
# 5. Convert the top card to it's value and count down that many cards to find the first key
# 6. Repeat 2 - 5 for the rest of the keys
# 7. Output array of keys
#
class Deck
def initialize
@deck = (1..52).to_a << "A" << "B"
end
def move_down(card)
old_pos = @deck.index(card)
new_pos = old_pos > 52 ? old_pos - 52 : old_pos + 1
@deck.insert(new_pos, @deck.delete_at(old_pos))
end
def triple_cut
top_J, bottom_J = [@deck.index("A"), @deck.index("B")].sort
@deck.replace( [@deck[(bottom_J + 1)..-1],
@deck[top_J..bottom_J],
@deck[0...top_J]].flatten)
end
def count_cut
@deck.insert(-2, *@deck.slice!(0..(@deck[-1] - 1)))
end
def mod(num)
num > 26 ? num -= 26 : num
end
def compose
move_down("A")
2.times { move_down("B") }
triple_cut
count_cut
end
def get_key
compose
pos = (@deck[0].is_a?(Fixnum) ? @deck[0] : 53)
@deck[pos].is_a?(Fixnum) ? mod(@deck[pos]) : get_key
end
end
|
require_relative '../helper.rb'
describe Later do
let(:redis) { Redis.new db: 15 }
let(:key) { Nest.new 'Events', redis }
describe '.[]' do
it 'returns a schedule with the given key' do
schedule = Later[key]
assert_instance_of Later::Schedule, schedule
assert_equal key, schedule.key
end
end
end
|
class Tag < ActiveRecord::Base
attr_accessible :name
# ++++++++++++++++++++
# validation
# ++++++++++++++++++++
validates :name, :presence => true
# ++++++++++++++++++++
# association
# ++++++++++++++++++++
belongs_to :user
belongs_to :article
# ++++++++++++++++++++
# query api
# ++++++++++++++++++++
# 返回某个用户某tag下对应文章个数
def Tag.countAritlces(user_id, tag_name)
Tag.where("user_id = #{user_id} and name = '#{tag_name}'").size
end
# return {"tagName1":2,"tagName2":3}
def Tag.user_tag(user_id)
result = {}
User.find(user_id).tags.each do |tag|
result[tag.name] ||= 0
result[tag.name] = result[tag.name] + 1
end
result.sort do |a, b| # tag按count排序
b[1] <=> a[1]
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Bike.create(
brand: 'Trek',
model: "Marlin 5",
description: "Marlin 5 is a trail-worthy daily rider that's perfectly suited for everyday adventures, on and off the trail. A front suspension fork with 100mm of travel, 21 speeds, and mounts for a rack and kickstand make it an ideal choice for new trail riders or anyone looking for a comfortable, stable commuter with the ruggedness of a real mountain bike.",
price: 549.00
)
Bike.create(
brand: 'Trek',
model: "Roscoe 8",
description: "Roscoe 8 is a trail hardtail for anyone looking to have some serious fun out in the dirt. Its 27.5+ mid-fat tires, a wide-range 1x12 drivetrain, and 120mm suspension fork make it a blast on every trail, from packed singletrack to the loose stuff. It's a laid-back trail mountain bike dressed in a high-quality spec that's ready to party.",
price: 549.00
) |
class RemoveAvatarPathFromContacts < ActiveRecord::Migration[5.1]
def change
remove_column :contacts, :avatar_path, :string
end
end
|
GOOGLE_OAUTH = 'https://accounts.google.com/o/oauth2/auth'
GOOGLE_PARAMS = "?response_type=code&client_id=#{ENV['CLIENT_ID']}"
# Visualizations for Canvas LMS Classes: Teacher login
class CanvasVisualizationAPI < Sinatra::Base
include AppLoginHelper
google_client_id = lambda do
"#{GOOGLE_OAUTH}#{GOOGLE_PARAMS}&redirect_uri=#{ENV['APP_URL']}"\
'oauth2callback_gmail&scope=email'
end
encrypt_email_address = lambda do
access_token = CallbackGmail.new(params).call
email = GoogleTeacherEmail.new(access_token).call
encrypted_email =
if find_teacher(email) then EncryptPayload.new(email).call
else SaveTeacher.new(email).call
end
{ encrypted_email: encrypted_email, email: email }.to_json
end
verify_password = lambda do
email = TokenClearingHouse.new(env['HTTP_AUTHORIZATION']).call
halt(*email.values) if email.class == Hash
password = params['password']
VerifyPassword.new(email, password).call
end
save_password_return_jwt = lambda do
email = TokenClearingHouse.new(env['HTTP_AUTHORIZATION']).call
halt(*email.values) if email.class == Hash
password = params['password']
SaveTeacherPassword.new(email, password).call
end
get '/api/v1/client_id/?', &google_client_id
get '/api/v1/use_callback_code/?', &encrypt_email_address
get '/api/v1/verify_password/?', &verify_password
post '/api/v1/save_password/?', &save_password_return_jwt
end
|
class CreatePropertyDocs < ActiveRecord::Migration
def change
create_table :property_docs do |t|
t.column :name, :string
t.timestamps
end
add_attachment :property_docs, :doc
end
end
|
require_relative '../lib/go_fish_server.rb'
describe 'GoFishServer' do
let(:server) { GoFishServer.new }
let(:clients) { [] }
def create_and_accept_client
client = TCPSocket.new('localhost', server.port_number)
clients << client
server.accept_connection
client
end
before(:each) do
server.start
end
after(:each) do
server.stop
clients.each { |client| client.close }
end
it 'returns the port number' do
expect(server.port_number).to eq 3336
end
context '#accept_connection' do
it 'accepts a client' do
client = create_and_accept_client
expect(server.clients.count).to eq 1
end
it 'rescue no client error' do
expect(server.accept_connection).to eq 'No client to accept'
end
end
context '#recieve_message' do
it 'reads a message from a socket' do
client = create_and_accept_client
message = 'Hello'
client.puts message
expect(server.recieve_message(server.clients[0])).to eq message
end
it 'rescues the exception if there is no message' do
client = create_and_accept_client
expect(server.recieve_message(server.clients[0])).to eq 'No message'
end
end
context '#send_message' do
it 'sends a message to a client' do
client = create_and_accept_client
message = 'Hello'
server.send_message(server.clients[0], message)
expect(client.gets.chomp).to eq message
end
end
context '#create_game_if_possible' do
it 'creates a game when the maximum player count is met' do
GoFishServer::MAXIMUM_NUMBER_OF_PLAYERS.times { create_and_accept_client }
server.create_game_if_possible
expect(server.game_interfaces.count).to eq 1
expect(server.clients.count).to eq 0
end
end
end
|
# frozen_string_literal: true
module ActionView
module Helpers #:nodoc:
module RecordTagHelper
def div_for(*) # :nodoc:
raise NoMethodError, "The `div_for` method has been removed from " \
"Rails. To continue using it, add the `record_tag_helper` gem to " \
"your Gemfile:\n" \
" gem 'record_tag_helper', '~> 1.0'\n" \
"Consult the Rails upgrade guide for details."
end
def content_tag_for(*) # :nodoc:
raise NoMethodError, "The `content_tag_for` method has been removed from " \
"Rails. To continue using it, add the `record_tag_helper` gem to " \
"your Gemfile:\n" \
" gem 'record_tag_helper', '~> 1.0'\n" \
"Consult the Rails upgrade guide for details."
end
end
end
end
|
module XFS
#
# Directory Entry when stored internal to an inode.
# Small directories are packed as tightly as possible so as to fit into the
# literal area of the inode. These "shortform" directories consist of a
# single header followed by zero or more dir entries. Due to the different
# inode number storage size and the variable length name field in the dir
# entry all these structures are variable length, and the accessors in
# this file should be used to iterate over them.
#
DIRECTORY_SHORTERFORM_HEADER = BinaryStruct.new([
'C', 'entry_count', # count of entries
'C', 'i8byte_count', # count of 8-byte inode #s
'I>', 'parent_ino_4byte', # parent dir inode # stored as 4 8-bit values
])
SIZEOF_DIRECTORY_SHORTERFORM_HEADER = DIRECTORY_SHORTERFORM_HEADER.size
DIRECTORY_SHORTFORM_HEADER = BinaryStruct.new([
'C', 'entry_count', # count of entries
'C', 'i8byte_count', # count of 8-byte inode #s
'Q>', 'parent_ino_8byte', # parent dir inode # stored as 8 8-bit values
])
SIZEOF_DIRECTORY_SHORTFORM_HEADER = DIRECTORY_SHORTFORM_HEADER.size
class ShortFormHeader
attr_reader :short_form_header, :entry_count, :parent_inode, :size, :small_inode
def initialize(data)
@short_form_header = DIRECTORY_SHORTERFORM_HEADER.decode(data)
@entry_count = @short_form_header['entry_count']
i8byte_count = @short_form_header['i8byte_count']
@parent_inode = @short_form_header['parent_ino_4byte']
@size = SIZEOF_DIRECTORY_SHORTERFORM_HEADER
@small_inode = true
if @entry_count == 0
@entry_count = i8byte_count
@short_form_header = DIRECTORY_SHORTFORM_HEADER.decode(data)
@parent_inode = @short_form_header['parent_ino_8byte']
@size = SIZEOF_DIRECTORY_SHORTFORM_HEADER
@small_inode = nil
end
end
end # class ShortFormHeader
end # module XFS
|
class TheBumpCli::Article
attr_accessor :author, :title, :subtitle, :content, :stage
@@all = []
def initialize
@@all << self
end
def self.find_by_stage(stage)
@@all.select {|article| article.stage == stage}
end
def self.new_from_hash(hash)
article = TheBumpCli::Article.new
hash.each do |attribute, value|
article.send("#{attribute}=", value)
end
article.content = article.content.reject {|para| para.text==""}
end
def self.all
@@all
end
def self.reset_all
@@all = []
end
end
|
# encoding: utf-8
require 'pathstring_interface'
require 'pathstring_root'
# we want a string, a little bit more intelligent though, so...
class Pathstring < PathstringInterface
# a little more borrowing from Forwardable
def_delegators :@absolute, :file?, :directory?, :extname, :size, :readlines
# relying on our own now
peddles PathstringRoot, accessors: [:relative_root]
# only writer, getter is implicitly defined within the read method
attr_accessor :content
def initialize(path, relative_path=nil)
super
stringified = path.to_s
relative_root_with relative_path || ''
# if path argument is not absolute, then it's relative...
relative_with stringified if absolute != stringified
# if path argument is not set yet and we're given a relative_path argument
relative_with @absolute.relative_path_from(@relative_root) if !@relative && relative_path
end
# (re)set the relative origin
# set the relative facade in the process
def with_relative_root(*root)
# Tap because i like tap
# No, tap because i want this to be chainable with `new` for example
tap do |p|
relative_root_with File.join(root)
relative_with @absolute.relative_path_from(@relative_root)
absolute? || replace(self, relative)
end
end
# read through a mere delegation to pathname
# fill up content attribute in the process
def read
@content = @absolute.read if exist?
end
# rename not only string value, but resets the internal pathname
# to return apt values to basename or dirname for instance
def rename(new_name)
relative_with new_name.sub(@relative_root.to_s, '')
absolute_with @relative_root, @relative
replace new_name
end
# common gateway to persistence
# persist being the implementation
# performs if parent dir exists
def save(*data)
persist *data
end
# common gateway to persistence
# persist being the implementation
# mkdir -p on parent dir
def save!(*data)
FileUtils.mkdir_p absolute_dirname
persist *data
end
# DWIM open
# default mode is 'w'
# if you need to read, then `read`
def open(mode=nil)
File.new(@absolute, mode || 'w').tap do |f|
if block_given?
yield f
f.close
end
end
end
private
# here persistence is simply saving
# content to file
def persist(*data)
@content = data.first if data.any?
open { |f| f.write(@content || read) } if absolute_dirname.exist?
end
# allows instance to instantiate sister instances
def foster(path)
self.class.new path, relative_root.send(path_facade(path))
end
# facade is relative or absolute ?
def path_facade(path)
(Pathname.new(path).absolute? && 'absolute') || 'relative'
end
end
|
require 'hamster/versions/ref'
describe Hamster::Versions::Ref do
it("refers an empty hash by default") { expect(subject.deref).to eq Hamster::Hash.empty }
it("dosync creates a new generation") { expect(subject.dosync(name: 'Alvin').deref[:name]).to eq 'Alvin' }
it("older is nil") { expect(subject.older).to be_nil }
it("newer is nil") { expect(subject.newer).to be_nil }
context "second generation" do
before { subject.dosync(name: 'Alvin') }
it("dosync creates a newer generation") { expect(subject.newer.deref[:name]).to eq 'Alvin' }
context "third generation" do
before { subject.newer.dosync(name: 'Simon') }
it("") { expect(subject.newest.deref[:name]).to eq 'Simon' }
it("#newest is a shorthand to the newest generation") { expect(subject.newest).to be subject.newer.newer }
it("#oldest is a shorthand to the oldest generation") { expect(subject.newest.oldest).to be subject }
it("the second generation cannot be changed anymore") { expect{subject.newer.dosync(name: 'Theodore') }.to raise_error(RuntimeError, /can't modify frozen/) }
end
end
end
|
class CustomerNeedsController < ApplicationController
before_action :set_customer_need, only: [:show, :update, :destroy]
# GET /customer_needs
def index
@customer_needs = CustomerNeed.all
render json: @customer_needs
end
# GET /customer_needs/1
def show
render json: @customer_need
end
# POST /customer_needs
def create
@customer_need = CustomerNeed.new(customer_need_params)
if @customer_need.save
render json: @customer_need, status: :created, location: @customer_need
else
render json: @customer_need.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /customer_needs/1
def update
if @customer_need.update(customer_need_params)
render json: @customer_need
else
render json: @customer_need.errors, status: :unprocessable_entity
end
end
# DELETE /customer_needs/1
def destroy
@customer_need.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_customer_need
@customer_need = CustomerNeed.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def customer_need_params
params.require(:customer_need).permit(:customer_id, :need_type_id, :created_by, :updated_by)
end
end
|
# =============================================================================
#
# MODULE : test/test_continuation.rb
# PROJECT : DispatchQueue
# DESCRIPTION :
#
# Copyright (c) 2016, Marc-Antoine Argenton. All rights reserved.
# =============================================================================
require '_test_env.rb'
module DispatchQueue
describe Continuation do
subject { Continuation.new }
it "passes this one" do
subject.must_be_instance_of Continuation
end
end
end
|
module AdminArea::People::Cell
class Show < Show.superclass
# Takes the person, shows their card recommendations. Has a header that
# says 'Recommendation' and a link to add a new rec for the person. If the
# person has any recs, they'll be shown in a <table>. If they don't have
# any, the table will still be rendered, but hidden with CSS (to be shown
# by JS if the admin makes a recommendation), and there'll be a <p> that
# tells you there's no recs.
#
# @!method self.call(person, options = {})
# @param person [Person] make sure that card_accounts => card_product => bank
# is eager-loaded.
class CardRecommendations < Abroaders::Cell::Base
property :card_recommendations
private
def table
id = 'admin_person_card_recommendations_table'
cell_class = AdminArea::CardRecommendations::Cell::Table
cell(cell_class, visible_recommendations, html_id: id)
end
def wrapper(&block)
# Always output the table onto the page, but hide it with CSS if there
# are no recs. It will be shown later by JS if the admin makes a rec.
content_tag(
:div,
id: 'admin_person_card_recommendations',
class: 'admin_person_card_recommendations',
style: visible_recommendations.any? ? '' : 'display:none;',
&block
)
end
def visible_recommendations
@_vr ||= card_recommendations.reject(&:opened?)
end
end
end
end
|
puts "What is your first name?"
first_name = gets.chomp
puts "What is your middle name?"
middle_name = gets.chomp
puts "What is your last name?"
last_name = gets.chomp
puts "Hello," + first_name.capitalize + middle_name.capitalize + last_name.capitalize + "! Nice to meet you!"
puts "What's your favorite number?"
fave_num = gets.chomp
better_num = fave_num + 1
puts "My favorite number is #{better_num}. It's better than yours because it's bigger!"
=begin
How do you define a local variable?
- Local variables are local to the code in which they were created. For example if a local variable was created in a loop, then it cannot be accessed outside this loop. Local variables must being with a lower case letter or an underscore. Global variables, on the other hand, can be accessed from anywhere in Ruby, once created. Global variables should be used sparingly because they can show up anytime in the program and can be changed at any time in the program and it's hard to keep track of. So local variables should be used instead.
How do you define a method?
- Everything in Ruby is an object. Variables can point to objects. Methods are how objects can communicate to each other. A method is a function of an object.
What is the difference between a local variable and a method?
- The difference between the local variable and method is how they interact with the object. The variable holds information for the object, while the method performs for the object. Also, the local variable can only be called in the method in which it was created.
How do you run a ruby program from the command line?
- After saving your file as filename.rb, go to the file directory, then run it in the command line by typing "ruby filename.rb."
How do you run an RSpec file from the command line?
- Go into the file directory, then type "rspec filename.rb."
What was confusing about this material? What made sense?
- Nothing was confusing about this material. It was actually very familiar because a similar lesson was in Codecademy. I completed it a few months ago so it was a great refresher.
<<<<<<< HEAD
link to my solution file: https://github.com/jinlaur/DBC-Phase0/blob/master/week-4/define-method/my_solution.rb
=======
>>>>>>> 70893d826c91e9aad28647762d6a4717491634ab
=end |
# frozen_string_literal: true
require_relative '../../../app/api'
require 'rack/test'
require 'ox'
require 'byebug'
module ExpenseTracker
RSpec.describe API do
include Rack::Test::Methods
def app
API.new(ledger: ledger)
end
def json_parsed
JSON.parse(last_response.body)
end
def xml_parsed
Ox.parse_obj(last_response.body)
end
let(:ledger) { instance_double('ExpenseTracker::Ledger') }
let(:expense) do
{
'payee' => 'Starbucks',
'amount' => 5.75,
'date' => '2017-06-10'
}
end
def assert_error_expense_response(error_message, mime_type = 'application/json')
expect(json_parsed).to include('error' => error_message) if mime_type == 'application/json'
expect(xml_parsed).to include('error' => error_message) if mime_type == 'text/xml'
expect(last_response.headers['Content-Type']).to eq(mime_type)
expect(last_response.status).to eq(422)
end
def assert_expense_response(expense_id, mime_type = 'application/json')
expect(json_parsed).to include('expense_id' => expense_id) if mime_type == 'application/json'
expect(xml_parsed).to include('expense_id' => expense_id) if mime_type == 'text/xml'
expect(last_response.headers['Content-Type']).to eq(mime_type)
expect(last_response.status).to eq(200)
end
describe 'POST /expenses' do
context 'when the expense is successfully recorded' do
before do
allow(ledger).to receive(:record).with(expense)
.and_return(RecordResult.new(true, 417, nil))
end
context 'with supported format but invalid expense payload format' do
it 'returns an error message and responds with a 422 (Unprocessable entity)' do
header 'Content-Type', 'application/json'
post '/expenses', Ox.dump(expense)
assert_error_expense_response('Expense payload does not match the format advertised')
end
end
context 'with Unsupported format' do
it 'returns an error message and responds with a 422 (Unprocessable entity)' do
header 'Content-Type', 'application/json203'
post '/expenses', JSON.generate(expense)
assert_error_expense_response('Unsupported format')
end
end
context 'with JSON format' do
it 'returns the expense id with HTTP 200 (OK)' do
header 'Content-Type', 'application/json'
post '/expenses', JSON.generate(expense)
assert_expense_response(417)
end
end
context 'with XML format' do
it 'returns the expense id and HTTP 200 (OK)' do
header 'Content-Type', 'text/xml'
post '/expenses', Ox.dump(expense)
assert_expense_response(417, 'text/xml')
end
end
end
context 'when the expense fails validation' do
before do
allow(ledger).to receive(:record)
.with(expense)
.and_return(RecordResult.new(false, 417, 'Expense incomplete'))
end
context 'with JSON format' do
it 'returns an error message and responds with a 422 (Unprocessable entity)' do
header 'Content-Type', 'application/json'
post '/expenses', JSON.generate(expense)
assert_error_expense_response('Expense incomplete')
end
end
context 'with XML format' do
it 'returns an error message and responds with a 422 (Unprocessable entity)' do
header 'Content-Type', 'text/xml'
post '/expenses', Ox.dump(expense)
assert_error_expense_response('Expense incomplete', 'text/xml')
end
end
end
end
describe 'GET /expenses/:date' do
context 'when expenses exist on the given date' do
before do
allow(ledger).to receive(:expenses_on).with('2017-06-12')
.and_return(%w[expense_1 expense_2])
end
context 'with unsupported format' do
it 'returns an error message and responds with a 422 (Unprocessable entity)' do
header 'Content-Type', 'text/xml1'
get 'expenses/2017-06-12'
expect(json_parsed).to include('error' => 'Unsupported format')
expect(last_response.status).to eq(422)
end
end
context 'with JSON format' do
it 'returns the expense records as JSON and respond with a 200 (OK)' do
header 'Content-Type', 'application/json'
get 'expenses/2017-06-12'
expect(json_parsed).to eq(%w[expense_1 expense_2])
expect(last_response.status).to eq(200)
end
end
context 'with XML format' do
it 'returns the expense records as XML and respond with a 200 (OK)' do
header 'Content-Type', 'text/xml'
get 'expenses/2017-06-12'
expect(xml_parsed).to eq(%w[expense_1 expense_2])
expect(last_response.status).to eq(200)
end
end
end
context 'when there are no expenses on the given date' do
before do
allow(ledger).to receive(:expenses_on).with('2017-06-12')
.and_return([])
end
context 'with JSON format' do
it 'returns an empty array as JSON' do
header 'Content-Type', 'application/json'
get 'expenses/2017-06-12'
expect(json_parsed).to eq([])
expect(last_response.status).to eq(200)
end
end
context 'with XML format' do
it 'returns an empty array as XML' do
header 'Content-Type', 'text/xml'
get 'expenses/2017-06-12'
expect(xml_parsed).to eq([])
expect(last_response.status).to eq(200)
end
end
end
end
end
end
|
class FullTextController < ApplicationController
def show
page = params[:page] || 1
search = Etablissement.search do
fulltext params[:id]
paginate page: page, per_page: 10
end
results = search.results
if results.nil?
render json: { message: 'no results found' }, status: 404
else
results_payload = {
total_results: search.total,
total_pages: results.total_pages,
per_page: results.per_page,
page: page,
etablissement: results
}
render json: results_payload, status: 200
end
end
def full_text_params
params.permit(:id, :page)
end
end
|
require 'rails_helper'
RSpec.feature 'Session', type: :feature do
before :each do
User.create(name: 'john', email: 'john@mail.com')
end
context 'User Login' do
scenario 'Successfully logged in' do
visit new_session_path
fill_in 'Email', with: 'john@mail.com'
click_button 'Login'
expect(page).to have_content('Welcome')
end
scenario 'Invalid login' do
visit new_session_path
fill_in 'Email', with: 'another_user@mail.com'
click_button 'Login'
expect(page).to have_content('Invalid email')
end
end
end |
class Locales < Grape::API
format :json
params do
requires :project, type: String
requires :lang, type: String
requires :namespace, type: String
end
get 'locales/:project/:lang/:namespace' do
GetTranslation.call(permitted_params)
end
params do
requires :project, type: String
requires :lang, type: String
requires :namespace, type: String
optional :jwt, type: String
end
post 'locales/:project/:lang/:namespace' do
AddTranslation.call(params)
end
end |
class AddWatchedFieldToVideoFile < ActiveRecord::Migration
def change
add_column :video_files, :watched, :boolean, default: false
end
end
|
cask 'firefox-custom' do
version "78.0.2"
sha256 'b0896794ae95282946bbe9203083d24cbd2b40768dd5fe1291694dba3bf166a0'
# download-installer.cdn.mozilla.net/pub/firefox/releases was verified as official when first introduced to the cask
url "http://artifactory.generagames.com:8081/artifactory/generic-local/macos/utilities/firefox/78.0.2/firefox-78.0.2.dmg"
appcast "https://aus5.mozilla.org/update/3/Firefox/#{version}/0/Darwin_x86_64-gcc3-u-i386-x86_64/en-US/release/Darwin%2015.3.0/default/default/update.xml?force=1",
checkpoint: 'bbdc283149077f5f20b512935e1a330ceeacb460bf7a38ace8391343b8b2652d'
name 'Mozilla Firefox'
homepage 'https://www.mozilla.org/firefox/'
auto_updates true
conflicts_with cask: [
'firefox-beta',
'firefox-esr',
]
app 'Firefox.app'
zap trash: [
'/Library/Logs/DiagnosticReports/firefox_*',
'~/Library/Application Support/Firefox',
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/org.mozilla.firefox.sfl*',
'~/Library/Caches/Firefox',
'~/Library/Caches/Mozilla/updates/Applications/Firefox',
'~/Library/Preferences/org.mozilla.firefox.plist',
],
rmdir: [
'~/Library/Application Support/Mozilla', # May also contain non-Firefox data
'~/Library/Caches/Mozilla/updates/Applications',
'~/Library/Caches/Mozilla/updates',
'~/Library/Caches/Mozilla',
]
end
|
require "lucie/log"
module Lucie
module IO
def info message
Lucie::Log.info message
stdout.puts message
end
def debug message
Lucie::Log.debug message
stderr.puts message
end
def error message
Lucie::Log.error message
stderr.puts message
end
def stdout
messenger || $stdout
end
def stderr
messenger || $stderr
end
def messenger
@debug_options ? @debug_options[ :messenger ] : nil
end
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
before :each do
@user = User.new(
first_name: "first_name",
last_name: "last_name",
email: "email@gmail.com",
password: "password",
password_confirmation: "password",
)
end
describe "Validations" do
it "is valid with valid attributes" do
expect(@user).to be_valid
end
it "is not valid without a first name" do
@user.first_name = nil
expect(@user).to_not be_valid
end
it "is not valid without a last name" do
@user.last_name = nil
expect(@user).to_not be_valid
end
it "is not valid without an email" do
@user.email = nil
expect(@user).to_not be_valid
end
it "is not valid without a password" do
@user.password = nil
expect(@user).to_not be_valid
end
it "is not valid if the password does not have a minimum length of 5 characters" do
@user.password = "four"
expect(@user).to_not be_valid
end
it "is not valid without a password confirmation" do
@user.password_confirmation = nil
expect(@user).to_not be_valid
p @user.errors.full_messages
end
it "is not valid if password and password confirmation do not match" do
@user.password = "not the same"
@user.password_confirmation = "different"
expect(@user).to_not be_valid
p @user.errors.full_messages
end
it "is not valid if the email is not unique (not case sensitive)" do
@user2 = User.new(
first_name: "first_name",
last_name: "last_name",
email: "email@gmail.COM",
password: "password",
password_confirmation: "password"
)
@user.save
@user2.save
expect(@user2).to_not be_valid
p @user2.errors.full_messages
end
end
describe '.authenticate_with_credentials' do
before :each do
@user.save
end
it "is valid with a valid email and password" do
expect(User.authenticate_with_credentials(@user.email, @user.password)).to be_instance_of(User)
end
it "is valid with whitespace around email" do
@user.email = " email@gmail.com "
expect(User.authenticate_with_credentials(@user.email, @user.password)).to be_instance_of(User)
end
it "is valid with whitespace around email" do
@user.email = " email@gmail.com "
expect(User.authenticate_with_credentials(@user.email, @user.password)).to be_instance_of(User)
end
it "is valid with mixed case email" do
@user.email = "EMAIL@gmail.com "
expect(User.authenticate_with_credentials(@user.email, @user.password)).to be_instance_of(User)
end
end
end
|
# frozen_string_literal: true
describe Facts::Sles::Memory::System::AvailableBytes do
describe '#call_the_resolver' do
it 'returns a fact' do
expected_fact = double(Facter::ResolvedFact, name: 'memory.system.available_bytes', value: 4_900_515_840)
allow(Facter::Resolvers::Linux::Memory).to receive(:resolve)
.with(:memfree)
.and_return(4_900_515_840)
allow(Facter::ResolvedFact).to receive(:new)
.with('memory.system.available_bytes', 4_900_515_840)
.and_return(expected_fact)
fact = Facts::Sles::Memory::System::AvailableBytes.new
expect(fact.call_the_resolver).to eq(expected_fact)
end
end
end
|
class Phone < ActiveRecord::Base
belongs_to :user
validates_formatting_of :number, using: :us_phone
end
|
# Copyright 2016 OCLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
describe "the record page" do
before(:all) do
url = 'https://authn.sd00.worldcat.org/oauth2/accessToken?authenticatingInstitutionId=128807&contextInstitutionId=128807&grant_type=client_credentials&scope=WorldCatDiscoveryAPI'
stub_request(:post, url).to_return(:body => mock_file_contents("token.json"), :status => 200)
end
context "when displaying a music album (226390945)" do
before(:all) do
stub_request(:get, "https://beta.worldcat.org/discovery/offer/oclc/226390945?heldBy=OCPSB").
to_return(:status => 200, :body => mock_file_contents("offer_set_226390945.rdf"))
get '/catalog/226390945'
@doc = Nokogiri::HTML(last_response.body)
end
it "should display the title" do
xpath = "//h1[@id='bibliographic-resource-name'][text()='Song for an uncertain lady']"
expect(@doc.xpath(xpath)).not_to be_empty
end
it "should display the alternate name" do
xpath = "//p[@property='schema:alternateName'][text()='Songs for an uncertain lady']"
expect(@doc.xpath(xpath)).not_to be_empty
end
it "should display the see_alsos" do
@see_alsos = @doc.xpath("//ul[@id='see_alsos']/li/span/a/text()")
expect(@see_alsos.count).to eq(11)
@see_alsos = @see_alsos.map {|see_also| see_also.to_s.gsub("\n", '').squeeze(' ').strip}
expect(@see_alsos).to include("Sorrow's children.")
expect(@see_alsos).to include("Lisa.")
expect(@see_alsos).to include("Autumn on your mind.")
expect(@see_alsos).to include("Waiting for an old friend.")
expect(@see_alsos).to include("Maybelline.")
expect(@see_alsos).to include("Song for an uncertain lady.")
expect(@see_alsos).to include("Child for now.")
expect(@see_alsos).to include("Africa.")
expect(@see_alsos).to include("One I thought was there.")
expect(@see_alsos).to include("Only time will make you see.")
expect(@see_alsos).to include("Let tomorrow be.")
end
it "should display the subjects" do
@subjects = @doc.xpath("//ul[@id='subjects']/li/span/a/text()")
expect(@subjects.count).to eq(3)
@subjects = @subjects.map {|subject_value| subject_value.to_s}
expect(@subjects).to include("Rock music")
expect(@subjects).to include("Folk music")
expect(@subjects).to include("Folk-rock music")
end
it "should display the format" do
xpath = "//span[@id='format'][text()='Music Album, Compact Disc']"
expect(@doc.xpath(xpath)).not_to be_empty
end
it "should display the language" do
xpath = "//span[@id='language'][text()='English']"
expect(@doc.xpath(xpath)).not_to be_empty
end
it "should display the publication places" do
@publiciationPlaces = @doc.xpath("//span[@property='library:placeOfPublication']/text()")
expect(@publiciationPlaces.count).to eq(3)
@publiciationPlaces = @publiciationPlaces.map {|publiciationPlace| publiciationPlace.to_s}
expect(@publiciationPlaces).to include("Merenberg, Germany :")
expect(@publiciationPlaces).to include("Kingston, N.Y. :")
end
it "should display the publisher" do
xpath = "//span[@property='schema:publisher']/span[@property='schema:name'][text()='ZYX-Music GMBH [distributor]']"
expect(@doc.xpath(xpath)).not_to be_empty
end
it "should display the date published" do
xpath = "//span[@property='schema:datePublished'][text()='20uu']"
expect(@doc.xpath(xpath)).not_to be_empty
end
it "should display the OCLC Number" do
xpath = "//span[@property='library:oclcnum'][text()='226390945']"
expect(@doc.xpath(xpath)).not_to be_empty
end
it "should display the descriptions" do
@descriptions = @doc.xpath("//p[@property='schema:description']/text()")
expect(@descriptions.size).to eq(1)
@descriptions = @descriptions.map {|description| description.to_s}
File.open("#{File.expand_path(File.dirname(__FILE__))}/../text/226390945_descriptions.txt").each do |line|
expect(@descriptions).to include(line.chomp)
end
end
it "should have the right music_by" do
author_name = @doc.xpath("//h2[@id='author-name']/a/text()")
expect(author_name.to_s.gsub("\n", '').squeeze(' ').strip).to be == "Randy Burns"
end
it "should have the right by_artists" do
@by_artists = @doc.xpath("//ul[@id='artists']/li/span/a/text()")
expect(@by_artists.size).to eq(7)
@by_artists = @by_artists.map {|by_artist| by_artist.to_s.gsub("\n", '').squeeze(' ').strip}
expect(@by_artists).to include("Bruce Samuels")
expect(@by_artists).to include("Randy Burns")
expect(@by_artists).to include("Bob Sheehan")
expect(@by_artists).to include("Matt Kastner")
expect(@by_artists).to include("John O'Leary")
expect(@by_artists).to include("Bergert Roberts")
expect(@by_artists).to include("Andy 'Dog' Merwin")
end
end
context "when displaying a music album (38027615)" do
before(:all) do
stub_request(:get, "https://beta.worldcat.org/discovery/offer/oclc/38027615?heldBy=OCPSB").
to_return(:status => 200, :body => mock_file_contents("offer_set_38027615.rdf"))
get '/catalog/38027615'
@doc = Nokogiri::HTML(last_response.body)
end
it "should have the right alternate name" do
xpath = "//p[@property='schema:alternateName'][text()='Angels on high']"
expect(@doc.xpath(xpath)).not_to be_empty
end
it "should have the right parts" do
@parts = @doc.xpath("//ul[@id='parts']/li/span/a/text()")
expect(@parts.size).to eq(5)
@parts = @parts.map {|part| part.to_s.gsub("\n", '').squeeze(' ').strip}
expect(@parts).to include("First Nowell.")
expect(@parts).to include("Carol of the birds.")
expect(@parts).to include("Veni Emmanuel.")
expect(@parts).to include("What is this lovely fragrance?")
expect(@parts).to include("Als ich bei meinen Schafen wacht.")
end
it "should have the right see_alsos" do
@see_alsos = @doc.xpath("//ul[@id='see_alsos']/li/span/a/text()")
expect(@see_alsos.size).to eq(11)
@see_alsos = @see_alsos.map {|see_also| see_also.to_s.gsub("\n", '').squeeze(' ').strip}
expect(@see_alsos).to include("Musae Sioniae,")
expect(@see_alsos).to include("Hymn to the Virgin.")
expect(@see_alsos).to include("Musique.")
expect(@see_alsos).to include("Weihnachts-Oratorium.")
expect(@see_alsos).to include("Alleluia.")
expect(@see_alsos).to include("Carol-anthems.")
expect(@see_alsos).to include("Ave Maria.")
expect(@see_alsos).to include("O magnum mysterium.")
expect(@see_alsos).to include("Adeste fideles.")
expect(@see_alsos).to include("Svete tikhiĭ.")
expect(@see_alsos).to include("Ceremony of carols.")
end
end
context "when displaying a music album (609569619)" do
before(:all) do
stub_request(:get, "https://beta.worldcat.org/discovery/offer/oclc/609569619?heldBy=OCPSB").
to_return(:status => 200, :body => mock_file_contents("offer_set_609569619.rdf"))
get '/catalog/609569619'
@doc = Nokogiri::HTML(last_response.body)
end
it "should have the right performers" do
@performers = @doc.xpath("//ul[@id='performers']/li/span/a/text()")
expect(@performers.size).to eq(2)
@performers = @performers.map {|performer| performer.to_s.gsub("\n", '').squeeze(' ').strip}
expect(@performers).to include("Grace Potter, 1983-")
expect(@performers).to include("Nocturnals (Musical group)")
'Potter, Grace, 1983-'
end
end
end
|
require 'oj'
require 'typhoeus'
class BTCAccount
def initialize
json_config = Oj.load_file('features/config', Oj.default_options)
@config = json_config
@uuid = @config['BTC']
end
def send_to_account(account, amount)
# uri = URI.parse(@config['URL'])
# header = {'Content-Type': 'application/x-www-form-urlencoded', 'X-Api-Key': @config['API_KEY']}
res = Typhoeus::Request.post(@config['URL'],
body: {'amount': amount, 'amount_currency': 'BTC', 'from_account':@uuid, 'to_account':account},
:headers=>{'Content-type'=>'application/x-www-form-urlencoded', 'X-Api-Key'=>@config['API_KEY']})
return Oj.load(res.body, Oj.default_options)
end
def get_balance
res = Typhoeus::Request.get(@config['URL_A'], :headers=>{'Content-type'=>'application/json', 'X-Api-Key'=>@config['API_KEY']})
for value in Oj.load(res.body, Oj.default_options)
if value['currency'] == 'BTC'
return value['balance']
end
end
end
def get_uuid
@config['BTC']
end
end |
#Pseudocode
=begin
INPUT: Obtain a string
STEPS:
CREATE a html_entity hash
entities = {
> => <
< => >
& => &
¢ => ¢
£ => £
¥ => ¥
€ => €
© => ©
® => ®
}
Create a variable called character_array.
Split the string and store it in the character_array
FOR each char in the character array THEN
check to see if the character is a key in the entitites hash
IF true then replace the char with the entities[key]
END IF
END FOR
join the character array together
OUTPUT: Return the string with it's html entity
=end
def convert(string)
entities = {
'>' => '>',
'<' => '<',
'&' => '&',
'¢' => '¢',
'£' => '£',
'¥' => '¥',
'€' => '€',
'©' => '©',
'®' => '®',
'"' => '"',
"'" => '''
}
character_array = string.split("")
character_array.map! { |char| entities.has_key?(char) ? char = entities[char] : char }.join("")
end
p convert("Dolce & Gabbana") #should return Dolce & Gabbana.
p convert("Hamburgers < Pizza < Tacos") #should return Hamburgers < Pizza < Tacos.
p convert("Sixty > twelve") #should return Sixty > twelve.
p convert('Stuff in "quotation marks"') #should return Stuff in "quotation marks".
p convert("Shindler's List") #should return Shindler's List.
p convert("<>") #should return <>.
p convert("abc") #should return abc. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.