text stringlengths 10 2.61M |
|---|
module Paperclip
class StringioAdapter < AbstractAdapter
def initialize(target)
@target = target
cache_current_values
@tempfile = copy_to_tempfile(@target)
end
attr_writer :content_type
private
def cache_current_values
@original_filename = @target.original_filename if @target.respond_to?(:original_filename)
@original_filename ||= "stringio.txt"
@original_filename = @original_filename.strip
@content_type = @target.content_type if @target.respond_to?(:content_type)
@content_type ||= "text/plain"
@size = @target.size
end
def copy_to_tempfile(src)
while data = src.read(16*1024)
destination.write(data)
end
destination.rewind
destination
end
end
end
Paperclip.io_adapters.register Paperclip::StringioAdapter do |target|
StringIO === target
end
|
# == Schema Information
#
# Table name: rlcraft_map_locations
#
# id :integer not null, primary key
# x_coord :integer
# y_coord :integer
# title :string
# location_type :string
# description :string
# created_at :datetime not null
# updated_at :datetime not null
#
class RlcraftMapLocation < ApplicationRecord
def self.graphable_data
find_each.map do |location|
location.to_graphable_data
end
end
def self.location_types
[
"Waystone",
"Book",
"Player Base",
"Black Dragon",
"Red Dragon",
"Green Dragon",
"White Dragon",
"Blue Dragon",
"Other"
]
end
def to_graphable_data
{
id: id,
x: x_coord,
y: y_coord,
type: location_type.presence,
title: title.presence,
description: description.presence,
removed: destroyed?
}
end
end
|
#
require "string_container"
module Mail
#
class StreamMessage < Message
#
def body=(*args)
@body = args
end
attr_reader :body
#
def encoded
ready_to_send!
::StringContainer.new(
header.encoded, "\r\n",
*body)
end
private
# Encodes the message, calls encode on all its parts, gets an email message
# ready to send
def ready_to_send!
identify_and_set_transfer_encoding
add_required_fields
end
def identify_and_set_transfer_encoding
self.content_transfer_encoding = "binary"
end
def add_required_fields
add_required_message_fields
end
end
end
|
class Board
attr_accessor :board_values
attr_reader :current_board, :filled_board, :board
def initialize
reset
end
private
def reset
@board_values = [1,2,3,4,5,6,7,8,9]
@filled_board = []
create_board
@@winning_combination = [
[1,2,3],
[1,4,7],
[1,5,9],
[2,5,8],
[3,6,9],
[3,5,7],
[4,5,6],
[7,8,9]
]
end
def create_board
@board = "\t #{@board_values[0]} | #{@board_values[1]} | #{@board_values[2]} \n" +
"\t---+---+---\n" +
"\t #{@board_values[3]} | #{@board_values[4]} | #{@board_values[5]} \n" +
"\t---+---+---\n" +
"\t #{@board_values[6]} | #{@board_values[7]} | #{@board_values[8]} \n"
end
public
def add_move(letter, index)
@filled_board.push(index)
@board_values[index] = letter
create_board
end
def game_over?
@filled_board.length == @board_values.length
end
def won?(user_selections)
@@winning_combination.each do |combo|
if combo - user_selections == []
return true
end
end
false
end
end |
require "rails_helper"
RSpec.describe "BloodSugars sync", type: :request do
let(:sync_route) { "/api/v4/blood_sugars/sync" }
let(:request_user) { create(:user) }
let(:patient) { create(:patient, registration_facility: request_user.facility) }
let(:model) { BloodSugar }
let(:build_payload) { -> { build_blood_sugar_payload(build(:blood_sugar, patient: patient, facility: request_user.facility)) } }
let(:build_invalid_payload) { -> { build_invalid_blood_sugar_payload } }
let(:update_payload) { ->(blood_sugar) { updated_blood_sugar_payload blood_sugar } }
def to_response(blood_sugar)
Api::V4::BloodSugarTransformer.to_response(blood_sugar)
end
include_examples "v4 API sync requests"
end
|
class InnerDeclaration
def initialize(type, declarator_list, mode, value, lineno)
@declarator_list = declarator_list
@type = type
@mode = mode
@value = value
@lineno = lineno
end
def code(scope)
if @mode.nil?
code_no_expr(scope)
else
code_expr(scope)
end
end
private
def code_no_expr(scope)
@declarator_list.reduce('') do |acc, id|
reg = scope.new_register(false)
if id.is_a? Hash
acc + array_allocation(id[:id], "%#{reg}", id[:size], scope) #+ "store #{type} 0, #{type}* #{reg}\n"
else
scope.new_id(id, reg, @type)
acc + allocation("%#{reg}")
end
end
end
def code_expr(scope)
if @mode == :expr
expr_type = @value.type(scope)
# OPTIMIZATION
begin
expr_val = Type.val_to_llvm(expr_type, @value.try_eval)
expr_code = ''
rescue StandardError
expr_code, expr_val = @value.code(scope)
end
elsif @mode == :reg
expr_code = ''
expr_val = @value[:reg]
expr_type = @value[:type]
else
raise StandardError, "Not a valid mode '#{@mode.to_s}'"
end
alloc_code = @declarator_list.reduce('') do |acc, id|
reg = scope.new_register(false)
begin
scope.new_id(id, reg, @type)
conversion_code, expr_val = Type.build_conversion(expr_type, @type, expr_val, scope)
acc + allocation("%#{reg}") + conversion_code + store("%#{reg}", expr_val)
rescue LanguageError => msg
ErrorHandler.instance.register_error(msg: msg, lineno: @lineno)
acc
end
end
expr_code + alloc_code
end
def allocation(reg)
llvm_type = Type.to_llvm(@type)
" #{reg} = alloca #{llvm_type}\n"
end
def array_allocation(id, reg, size, scope)
llvm_type = Type.to_llvm(@type)
size_code, size_reg = size.code(scope)
size_type = size.type(scope)
convert_code, convert_reg = Type.build_conversion(size_type, :long, size_reg, scope)
stack_reg = scope.new_register
array_reg = scope.new_register(false)
scope.new_id(id, array_reg, @type, size_reg)
" #{reg} = alloca i8*\n" + size_code + convert_code +
" store i8* #{stack_reg}, i8** #{reg}\n" +
" #{stack_reg} = call i8* @llvm.stacksave()\n" +
" %#{array_reg} = alloca #{llvm_type}, i64 #{convert_reg}\n"
end
def store(reg, expr_reg)
llvm_type = Type.to_llvm(@type)
" store #{llvm_type} #{expr_reg}, #{llvm_type}* #{reg}\n"
end
end |
module SlackNotify
module Connection
def send_payload(payload)
conn = Faraday.new(@webhook_url) do |c|
c.use(Faraday::Request::UrlEncoded)
c.adapter(Faraday.default_adapter)
c.options.timeout = 5
c.options.open_timeout = 5
end
response = conn.post do |req|
req.body = JSON.dump(payload.to_hash)
end
handle_response(response)
end
def handle_response(response)
unless response.success?
if response.body.include?("\n")
raise SlackNotify::Error
else
raise SlackNotify::Error.new(response.body)
end
end
end
end
end
|
require 'spec_helper'
describe StripeWrapper::Charge do
let(:token) do
Stripe::Token.create({
card: {
number: card_number,
exp_month: 5,
exp_year: 2020,
cvc: '314',
},
}).id
end
context 'with valid card' do
let(:card_number) { '4242424242424242' }
it 'charges the card successfully', :vcr do
response = StripeWrapper::Charge.create(amount: 999, source: token)
expect(response).to be_successful
expect(response.amount).to eq(999)
expect(response.currency).to eq('eur')
end
end
context 'with invalid card' do
let(:card_number) { '4000000000000002'}
let(:response) { StripeWrapper::Charge.create(amount: 300, source: token) }
it 'does not charge the card successfully', :vcr do
expect(response).to_not be_successful
end
it 'contains an error message', :vcr do
expect(response.error_message).to eq('Your card was declined.')
end
end
end |
class Order < ApplicationRecord
has_and_belongs_to_many :product
belongs_to :billingaddr, :class_name => 'Address'
belongs_to :shippingaddr, :class_name => 'Address'
belongs_to :user
end
|
# frozen_string_literal: true
class AddDescriptionToSkills < ActiveRecord::Migration[5.0]
def change
add_column :skills, :skill_description, :text
end
end
|
require 'spec_helper'
shared_examples_for "a product" do |resource_class|
let!(:subscription) { Factory(:subscription) }
pluralized_resource_class_name = resource_class.to_s.demodulize.underscore.pluralize
singularize_resource_class_name = resource_class.to_s.demodulize.underscore
def valid_session
{}
end
describe "GET index" do
it "assigns all #{pluralized_resource_class_name} as @#{pluralized_resource_class_name}" do
a_product = Factory(singularize_resource_class_name.to_sym)
get :index, {}, valid_session
assigns(pluralized_resource_class_name.to_sym).should eq([a_product])
end
end
describe "GET show" do
it "assigns the requested #{singularize_resource_class_name} as @#{singularize_resource_class_name}" do
a_product = Factory(singularize_resource_class_name.to_sym)
get :show, {:id => a_product.to_param}, valid_session
assigns(singularize_resource_class_name.to_sym).should eq(a_product)
end
end
describe "GET new" do
it "assigns a new #{singularize_resource_class_name} as @#{singularize_resource_class_name}" do
get :new, {}, valid_session
assigns(singularize_resource_class_name.to_sym).should be_a_new(resource_class)
end
end
describe "GET edit" do
it "assigns the requested #{singularize_resource_class_name} as @#{singularize_resource_class_name}" do
a_product = Factory(singularize_resource_class_name.to_sym)
get :edit, {:id => a_product.to_param}, valid_session
assigns(singularize_resource_class_name.to_sym).should eq(a_product)
end
end
describe "POST create" do
describe "with valid params" do
it "creates a new AutoRenewalSubscription" do
expect {
post :create, {singularize_resource_class_name.to_sym => valid_attributes, :subscription_id => subscription}, valid_session
}.to change(resource_class, :count).by(1)
end
it "assigns a newly created #{singularize_resource_class_name} as @#{singularize_resource_class_name}" do
post :create, {singularize_resource_class_name.to_sym => valid_attributes, :subscription_id => subscription}, valid_session
assigns(singularize_resource_class_name.to_sym).should be_a(resource_class)
assigns(singularize_resource_class_name.to_sym).should be_persisted
end
it "redirects to the created #{singularize_resource_class_name}" do
post :create, {singularize_resource_class_name.to_sym => valid_attributes, :subscription_id => subscription}, valid_session
response.should redirect_to(subscription_products_path(subscription))
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved #{singularize_resource_class_name} as @#{singularize_resource_class_name}" do
resource_class.any_instance.stub(:save).and_return(false)
post :create, {singularize_resource_class_name.to_sym => {}, :subscription_id => subscription}, valid_session
assigns(singularize_resource_class_name.to_sym).should be_a_new(resource_class)
end
it "re-renders the 'new' template" do
post :create, {singularize_resource_class_name.to_sym => {}, :subscription_id => subscription}, valid_session
response.should render_template("new")
end
end
end
describe "PUT update" do
describe "with valid params" do
it "updates the requested #{singularize_resource_class_name}" do
a_product = Factory(singularize_resource_class_name.to_sym)
put :update, {:id => a_product.to_param, singularize_resource_class_name.to_sym => {'product_id' => 'valid_id'}, :subscription_id => a_product.subscription}, valid_session
end
it "assigns the requested #{singularize_resource_class_name} as @#{singularize_resource_class_name}" do
a_product = Factory(singularize_resource_class_name.to_sym)
put :update, {:id => a_product.to_param, singularize_resource_class_name.to_sym => valid_attributes, :subscription_id => a_product.subscription}, valid_session
assigns(singularize_resource_class_name.to_sym).should eq(a_product)
end
it "redirects to the #{singularize_resource_class_name}" do
a_product = Factory(singularize_resource_class_name.to_sym)
put :update, {:id => a_product.to_param, singularize_resource_class_name.to_sym => valid_attributes, :subscription_id => a_product.subscription}, valid_session
response.should redirect_to(subscription_products_path(a_product.subscription))
end
end
describe "with invalid params" do
it "assigns the #{singularize_resource_class_name} as @#{singularize_resource_class_name}" do
a_product = Factory(singularize_resource_class_name.to_sym)
put :update, {:id => a_product.to_param, singularize_resource_class_name.to_sym => {'product_id' => nil}, :subscription_id => a_product.subscription}, valid_session
assigns(singularize_resource_class_name.to_sym).should eq(a_product)
end
it "re-renders the 'edit' template" do
a_product = Factory(singularize_resource_class_name.to_sym)
put :update, {:id => a_product.to_param, singularize_resource_class_name.to_sym => {'product_id' => nil}, :subscription_id => a_product.subscription}, valid_session
response.should render_template("edit")
end
end
end
describe "DELETE destroy" do
it "destroys the requested #{singularize_resource_class_name}" do
a_product = Factory(singularize_resource_class_name.to_sym)
expect {
delete :destroy, {:id => a_product.to_param, :subscription_id => a_product.subscription}, valid_session
}.to change(resource_class, :count).by(-1)
end
it "redirects to the #{pluralized_resource_class_name} list" do
a_product = Factory(singularize_resource_class_name.to_sym)
delete :destroy, {:id => a_product.to_param, :subscription_id => a_product.subscription}, valid_session
response.should redirect_to(subscription_products_path(a_product.subscription))
end
end
end
module BakerServer
describe AutoRenewalSubscriptionsController do
it_behaves_like "a product", AutoRenewalSubscription do
def valid_attributes
subscription_duration = Factory(:subscription_duration)
Factory.attributes_for(:auto_renewal_subscription, subscription_duration_id: subscription_duration)
end
end
end
describe FreeSubscriptionsController do
it_behaves_like "a product", FreeSubscription do
def valid_attributes
Factory.attributes_for(:free_subscription)
end
end
end
describe NonRenewingSubscriptionsController do
it_behaves_like "a product", NonRenewingSubscription do
def valid_attributes
Factory.attributes_for(:non_renewing_subscription)
end
end
end
end
|
class BusinessReview < ActiveRecord::Base
belongs_to :business
belongs_to :review
end |
class Question < ActiveRecord::Base
attr_accessible :max_selections, :min_selections, :query, :ranked, :answers, :question_options_attributes
belongs_to :user
has_many :question_options
has_many :answers, :through => :question_options
accepts_nested_attributes_for :question_options, allow_destroy: true
validates :query, :presence => true
validates :max_selections, :presence => true, :numericality => {only_integer: true, greater_than_or_equal_to: :min_selections}
validates :min_selections, :presence => true, :numericality => {only_integer: true, less_than_or_equal_to: :max_selections, greater_than: 0}
with_options :if => :ranked? do |ranked|
ranked.validates :min_selections, :numericality => {greater_than: 1, equal_to: :max_selections}
end
#validate :max_selections, :numericality => {less_than_or_equal_to: :question_options.count}
validates_associated :question_options
end |
class Skill < ActiveRecord::Base
belongs_to :user
validates :skill, length: { maximum: 20 }, presence: true
end
|
# frozen_string_literal: true
require 'apipie-params'
require 'algebrick'
require 'thread'
require 'set'
require 'base64'
require 'concurrent'
require 'concurrent-edge'
logger = Logger.new($stderr)
logger.level = Logger::INFO
Concurrent.global_logger = lambda do |level, progname, message = nil, &block|
logger.add level, message, progname, &block
end
# TODO validate in/output, also validate unknown keys
# TODO performance testing, how many actions will it handle?
# TODO profiling, find bottlenecks
# FIND change ids to uuid, uuid-<action_id>, uuid-<action_id-(plan, run, finalize)
module Dynflow
class << self
# Return the world that representing this process - this is mainly used by
# Sidekiq deployments, where there is a need for a global-level context.
#
# @return [Dynflow::World, nil]
def process_world
return @process_world if defined? @process_world
@process_world = Sidekiq.options[:dynflow_world]
raise "process world is not set" unless @process_world
@process_world
end
end
class Error < StandardError
def to_hash
{ class: self.class.name, message: message, backtrace: backtrace }
end
def self.from_hash(hash)
self.new(hash[:message]).tap { |e| e.set_backtrace(hash[:backtrace]) }
end
end
require 'dynflow/utils'
require 'dynflow/round_robin'
require 'dynflow/dead_letter_silencer'
require 'dynflow/actor'
require 'dynflow/actors'
require 'dynflow/errors'
require 'dynflow/serializer'
require 'dynflow/serializable'
require 'dynflow/clock'
require 'dynflow/stateful'
require 'dynflow/transaction_adapters'
require 'dynflow/coordinator'
require 'dynflow/persistence'
require 'dynflow/middleware'
require 'dynflow/flows'
require 'dynflow/execution_history'
require 'dynflow/execution_plan'
require 'dynflow/delayed_plan'
require 'dynflow/action'
require 'dynflow/director'
require 'dynflow/executors'
require 'dynflow/logger_adapters'
require 'dynflow/world'
require 'dynflow/connectors'
require 'dynflow/dispatcher'
require 'dynflow/serializers'
require 'dynflow/delayed_executors'
require 'dynflow/semaphores'
require 'dynflow/throttle_limiter'
require 'dynflow/telemetry'
require 'dynflow/config'
require 'dynflow/extensions'
if defined? ::ActiveJob
require 'dynflow/active_job/queue_adapter'
class Railtie < ::Rails::Railtie
config.before_initialize do
::ActiveJob::QueueAdapters.send(
:include,
Dynflow::ActiveJob::QueueAdapters
)
end
end
end
if defined? Rails
require 'dynflow/rails'
end
end
|
require 'test_helper'
require 'rails/generators'
require 'rails/generators/migration'
require 'generators/multi_recipient_threaded_messages/models/models_generator'
class ModelsGeneratorTest < Rails::Generators::TestCase
tests MultiRecipientsThreadedMessages::Generators::ModelsGenerator
destination File.expand_path("../tmp", File.dirname(__FILE__))
setup :prepare_destination
def test_generates_correct_file_name
run_generator
assert_file "app/models/message.rb"
assert_file "app/models/received_message.rb"
assert_migration "db/migrate/create_messages.rb"
assert_migration "db/migrate/create_received_messages.rb"
end
end |
require 'rspec'
require_relative 'node'
describe Node do
let(:node) { Node.new("initial") }
describe '#new' do
it 'can be created with the correct data' do
expect(node.value).to eq "initial"
end
end
describe '#reverse' do
it 'can be reversed' do
binding.pry
end
end
describe 'to_s' do
it 'prints off itself when alone' do
expect(node.to_s).to eq "initial\n"
end
it 'prints off itself and next' do
node.push("hi")
expect(node.to_s).to eq "initial\nhi\n"
end
end
describe '#nth_value' do
it 'errors when larger than length' do
expect { node.nth_value(5) }.to raise_error
end
it 'errors when less than 0' do
expect { node.nth_value(-1) }.to raise_error
end
it 'returns initial when 0' do
expect(node.nth_value(0)).to eq "initial"
end
it 'returns index when more than one' do
node.push "hi"
node.push "sup"
expect(node.nth_value(2)).to eq "sup"
end
end
describe '#push' do
it 'adds an element to the end' do
expect { node.push("new value") }.to change { node.length }.by 1
expect(node.next_node).to be_a Node
expect(node.next_node.value).to eq "new value"
end
end
describe '#pop' do
context 'with one' do
it 'returns itself' do
expect(node.pop).to be_a Node::EmptyNode
end
end
context 'with more than one' do
before { node.push "pop me" }
it 'returns the last value and changes the length' do
expect(node.length).to be 2
node.pop
expect(node.value).to eq "initial"
expect(node.length).to be 1
end
end
end
describe '#shift' do
it 'adds an element to the front' do
new_node = node.shift("new value")
expect(new_node.length).to be 2
expect(new_node).to be_a Node
expect(new_node.value).to eq "new value"
expect(new_node.next_node).to be_a Node
expect(new_node.next_node.value).to eq "initial"
end
end
describe '#unshift' do
context 'with more than one' do
before { node.push "new guy" }
it 'removes the first element and returns the next' do
expect(node.length).to be 2
unshifted = node.unshift
expect(unshifted).to be_a Node
expect(unshifted.value).to eq "new guy"
expect(unshifted.length).to eq 1
end
end
end
describe '#length' do
it 'returns 1 when no more elements' do
expect(node.length).to eq 1
end
it 'returns 2 when two elements' do
node.push "value"
expect(node.length).to eq 2
end
it 'returns 3 when three elements' do
2.times { node.push "value" }
expect(node.length).to eq 3
end
end
end
|
class RemoveXlSpecficStuff < ActiveRecord::Migration[4.2]
def self.up
drop_table 'label_relations'
remove_column :labels, 'rev'
remove_column :labels, 'published_version_id'
remove_column :labels, 'published_at'
remove_column :labels, 'locked_by'
remove_column :labels, 'expired_at'
remove_column :labels, 'follow_up'
remove_column :labels, 'to_review'
remove_column :labels, 'rdf_updated_at'
end
def self.down
add_column :labels, 'rev', :integer, default: 1
add_column :labels, 'published_version_id', :integer
add_column :labels, 'published_at', :date
add_column :labels, 'locked_by', :integer
add_column :labels, 'expired_at', :date
add_column :labels, 'follow_up', :date
add_column :labels, 'to_review', :boolean
add_column :labels, 'rdf_updated_at', :date
create_table 'label_relations', force: true do |t|
t.string 'type'
t.integer 'domain_id'
t.integer 'range_id'
t.datetime 'created_at'
t.datetime 'updated_at'
end
add_index 'label_relations', ['domain_id', 'range_id', 'type'], name: 'index_label_relations_on_domain_id_and_range_id_and_type'
add_index 'label_relations', ['type'], name: 'index_label_relations_on_type'
end
end
|
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
def assert_error(record, options)
assert_not record.valid?
options.each do |attribute, message|
assert record.errors.added?(attribute, message), "Expected #{attribute} to have the following error: #{message}"
end
end
end
|
# frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2019-2023, by Samuel Williams.
# Copyright, 2019, by Bryan Powell.
# Copyright, 2020, by Michael Adams.
# Copyright, 2021, by Cédric Boutillier.
require_relative 'console/version'
require_relative 'console/logger'
module Console
class << self
def logger
Logger.instance
end
def logger= instance
Logger.instance= instance
end
def debug(...)
Logger.instance.debug(...)
end
def info(...)
Logger.instance.info(...)
end
def warn(...)
Logger.instance.warn(...)
end
def error(...)
Logger.instance.error(...)
end
def fatal(...)
Logger.instance.fatal(...)
end
def call(...)
Logger.instance.call(...)
end
end
def logger= logger
warn "Setting logger on #{self} is deprecated. Use Console.logger= instead.", uplevel: 1
end
def logger
Logger.instance
end
end
|
module Bouncer
class Token < Virtus::Attribute
COERCABLE_TYPES = {
encrypted: Bouncer::Tokens::Encrypted,
plain: Bouncer::Tokens::Plain
}
def coerce(value)
return value unless value.is_a? ::Hash
COERCABLE_TYPES[value['type'].to_sym].new(value['token'])
end
end
end |
class SessionsController < Devise::OmniauthCallbacksController
include ApplicationHelper
before_filter :authenticate_user!
def new
if user_signed_in?
redirect_to index_path
else
if test_mode?
# homepage with two login options (CAS or dummy) if app is still running in test mode
redirect_to root_path
else
# in real application (non-test-mode) redirect users directly to CAS login page
redirect_to user_omniauth_authorize_path(:cas)
end
end
end
# Authenticate user with CAS login
def cas
@user = User.find_or_create_from_auth_hash(auth_hash, current_user)
if @user.persisted?
session[:cas_login] = true # use session to differentiate login with cas or not
flash[:success] = I18n.t "devise.omniauth_callbacks.success", :kind => "Thoughtworks CAS"
sign_in_and_redirect @user, :event => :authentication
end
end
def destroy_cas
if user_signed_in?
session[:cas_login] = nil
sign_out_and_redirect current_user
else
redirect_to root_path
end
end
# Overwriting the sign_out redirect path method
def after_sign_in_path_for(resource_or_scope)
index_path
end
def after_sign_out_path_for(resource_or_scope)
cas_logout_path
end
protected
def auth_hash
request.env['omniauth.auth']
end
end |
class Category < ActiveRecord::Base
has_and_belongs_to_many :products
has_many :campaigns
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def currentUserIsAdmin
isUserOnline
@user = currentUser
if @user.isAdmin == false
redirect_to root_path
end
end
def currentUser
@currentUser = User.find(session[:userid]) if session[:userid] #||=
end
def isUserOnline
if currentUser.nil?
redirect_to root_path
end
end
end
|
require 'csv'
require_relative './common.rb'
def import_trash(t, c, m)
csv_data = retrieve_csv 'trash', raw: true
column_headers = %i[category name material variable_material brands weight]
CSV.parse csv_data do |row|
trash = t.new
# from [ $category, $name, ...]
# to { category: $category, name: $name, ... }
hash = Hash[*column_headers.zip(row).flatten]
category = Category.find_by_name hash[:category].downcase
material = Material.find_by_name hash[:material].downcase
trash.category = category
trash.material = material
trash.name = hash[:name]
trash.variable_material = hash[:variable_material]
trash.weight = hash[:weight]
trash.brands = hash[:brands]
trash.is_miscellaneous = trash.name.include? 'iscellaneous'
trash.save
end
end
|
class Section < ActiveRecord::Base
has_many :products
belongs_to :parent, :class_name => 'Section', :foreign_key => :parent_id
has_many :children, :class_name => 'Section', :foreign_key => :parent_id
has_and_belongs_to_many :discounts
has_attached_file :cover
def slow_all_products
self.children.where(:active=>true).inject(self.products.where(:active=>true)){|prods, child| prods + child.all_products }.sort{|a, b| a.priority? && b.priority? ? ( - (a.priority <=> b.priority)) : ( b.priority.nil? && a.priority.nil? ? 0 : (a.priority? ? -1 : 1) ) }
end
def all_products
Product.where(:active => true, :section_id => self.tree_to_list.map(&:id))
end
def tree_to_list
self.class.subtree_by_levels([self])
end
def self.subtree_by_levels(arr)
return [] if arr.empty?
arr | self.subtree_by_levels(self.where(:active => true, :parent_id => arr.map(&:id)))
end
def self.parents_to_root(init_sections)
return [] if init_sections.empty?
init_sections | self.parents_to_root(self.where(:id => init_sections.map(&:parent_id).compact.uniq))
end
end
|
require 'test_helper'
require_relative '../lib/code_survey/helpers'
KEYWORDS = {
'nouns' => [
'Time Warp',
'rabbit'
],
'articles' => [
'the'
]
}.freeze
class MergeHashesTest < Minitest::Test
def test_no_match
line = "I've got to keep control"
result = occurences_hash(line, KEYWORDS)
assert result.nil?
end
def test_simple_occurrences_hash
line = "Let's do the Time Warp again"
result = occurences_hash(line, KEYWORDS)
assert result['nouns']['Time Warp'] == 1
assert result['articles']['the'] == 1
end
def test_multiple_occurences_in_line_hash
line = "I remember doing the Time Warp Let's do the Time Warp again"
result = occurences_hash(line, KEYWORDS)
# Not detecting right now.
assert result['nouns']['Time Warp'] == 1
assert result['articles']['the'] == 1
end
end
|
When(/^I go to the (.+)page$/) do |page|
case page
when "home"
visit('/')
when "restaurant "
visit('/restaurants/1')
when "new restaurant "
visit('/restaurants/new')
else
raise "Page doesn't match predefined page names"
end
end
Given (/^I am signed up$/) do
visit('/users/sign_up')
user_sign_up("mjcalvey2@gmail.com", "Password123")
end
Given (/^I am signed in$/) do
user_sign_in("owner@gmail.com", "Password123")
end
Given (/^([0-9]+) restaurant(s)? exist(s)?$/) do |num_times, i, j|
user_sign_up("owner@gmail.com", "Password123")
user_sign_out
num_times.to_i.times {add_restaurant("Dio's Develish Doner Kebabs #{num_times}",
"Bluuuurb of Dio's Develish Kebabs",
"desc of doner kebabs",
"W1K2SE")}
end
And (/^has reviews with (.+)$/) do |ratings|
ratings.split(",").map(&:to_i).each do |rating|
user_sign_up("ab#{rating}@email.com", "password")
visit '/restaurants/1'
fill_in_review_form(rating, "comment")
click_button "Add Review"
user_sign_out
end
end
Then(/^I should see a (.*) element with ID "(.*)"$/) do |tag, id|
element = find_by_id(id.to_s)
element.assert_matches_selector(tag)
end
And (/^I click the (.*) button$/) do |btn|
click_button "#{btn}"
end
Then(/^I can see the hardcoded reviews$/) do
expect(page).to have_text("Bluuuurb of Dio's Develish Kebabs")
end
Then(/^I can modify a restaurant's description$/) do
fill_in "restaurant_description", with: "where magic food happens"
end
Then(/^I see the new modified changes$/) do
expect(page).to have_text("where magic food happens")
end
|
require "patch"
require "iota/version"
require "iota/utils/input_validator"
require "iota/utils/object_validator"
require "iota/utils/ascii"
require "iota/utils/utils"
require "iota/utils/broker"
require "iota/api/commands"
require "iota/api/wrappers"
require "iota/api/transport"
require "iota/api/api"
require "iota/crypto/pow_provider"
require "iota/crypto/curl"
require "iota/crypto/kerl"
require "iota/crypto/converter"
require "iota/crypto/bundle"
require "iota/crypto/signing"
require "iota/crypto/hmac"
require "iota/crypto/private_key"
require "iota/multisig/address"
require "iota/multisig/multisig"
require "iota/models/base"
require "iota/models/input"
require "iota/models/transfer"
require "iota/models/seed"
require "iota/models/transaction"
require "iota/models/bundle"
require "iota/models/account"
module IOTA
class Client
attr_reader :version, :host, :port, :provider, :sandbox, :token, :broker, :api, :utils, :validator, :multisig, :batch_size
def initialize(settings = {})
setSettings(settings)
@utils = IOTA::Utils::Utils.new
@validator = @utils.validator
@multisig = IOTA::Multisig::Multisig.new(self)
end
def changeNode(settings = {})
setSettings(settings)
self
end
private
def setSettings(settings)
settings = symbolize_keys(settings)
@host = settings[:host] ? settings[:host] : "http://localhost"
@port = settings[:port] ? settings[:port] : 14265
@provider = settings[:provider] || @host.gsub(/\/$/, '') + ":" + @port.to_s
@sandbox = settings[:sandbox] || false
@token = settings[:token] || false
@timeout = settings[:timeout] || 120
@batch_size = settings[:batch_size] || 500
@local_pow = settings[:local_pow] || false
if @sandbox
@sandbox = @provider.gsub(/\/$/, '')
@provider = @sandbox + '/commands'
end
@broker = IOTA::Utils::Broker.new(@provider, @token, @timeout, user: settings[:user], password: settings[:password])
@api = IOTA::API::Api.new(@broker, @sandbox, @batch_size, @local_pow)
end
def symbolize_keys(hash)
hash.inject({}){ |h,(k,v)| h[k.to_sym] = v; h }
end
end
end
|
#
# Cookbook Name:: my-jenkins
# Recipe:: default
#
# Copyright (c) 2016 The Authors, All Rights Reserved.
include_recipe 'yum::default'
yum_repository 'jenkins-ci' do
baseurl "http://pkg.jenkins-ci.org/redhat"
gpgkey 'http://pkg.jenkins-ci.org/redhat/jenkins-ci.org.key'
end
package 'jenkins'
# The package install creates the Jenkins user so now is the time to set the home
# directory permissions.
directory '/var/lib/jenkins' do
owner 'root'
group 'jenkins'
mode '0755'
recursive true
end
# template '/etc/sysconfig/jenkins' do
# source 'jenkins-config-rhel.erb'
# mode '0644'
# notifies :restart, 'service[jenkins]', :immediately
# end
service 'jenkins' do
supports [:stop, :start, :restart]
action [:enable, :start]
end
|
class Notification < ActiveRecord::Base
validates :message, :date, :presence => true
validates_with AttachmentSizeValidator, attributes: :picture, less_than: 1.megabytes
has_attached_file :picture, styles: { medium: "1024x1024>", thumb: "100x100>" }, :storage => :dropbox,
:dropbox_credentials => Rails.root.join("config/dropbox.yml"), :dropbox_visibility => 'public'
validates_attachment_content_type :picture, content_type: /\Aimage\/.*\Z/
def self.today
where("date = ?", Time.zone.now.beginning_of_day)
end
def picture_url
picture_url = picture.url(:medium)
end
after_save :create_published_notification
def create_published_notification
self.create_activity :published if (self.is_published_changed? && self.is_published == true)
end
include PublicActivity::Common
end
|
require 'to_spreadsheet/railtie'
describe ToSpreadsheet::Railtie do
it "registers a renderer" do
expect(ToSpreadsheet.renderer).to eq(:html2xlsx)
expect(ActionController::Renderers::RENDERERS).to include(ToSpreadsheet.renderer)
end
end
|
class User < ActiveRecord::Base
has_secure_password
has_many :posts, dependent: :destroy
end
|
require 'rails_helper'
describe User do
describe 'associations' do
it { should belong_to(:team) }
end
describe 'validations' do
it { should validate_presence_of(:slack_user_id) }
it { should validate_presence_of(:name) }
it { should validate_presence_of(:team) }
end
end
|
class Todoist::Base
protected
def http
self.class.send :http
end
def self.http
Todoist::HTTP
end
def alter_hash(hash, generate_method = true)
hash.each do |key, value|
iv = "@#{key}"
instance_variable_set iv, value
if generate_method && !self.respond_to?(key)
self.class.send :define_method, key do
instance_variable_get iv
end
end
end
end
end
|
# == Schema Information
#
# Table name: items
#
# id :integer not null, primary key
# name :string(40)
# description :text
# story_id :integer
# created_at :datetime
# updated_at :datetime
# usable :boolean default(FALSE)
# attr :string(255) default("")
# modifier :integer default(0)
#
class Item < ActiveRecord::Base
belongs_to :story, touch: true
has_many :adventurers, through: :adventurers_items
has_many :modifiers_items, dependent: :destroy
has_many :modifiers_shops, dependent: :destroy
has_many :decisions, foreign_key: :item_validator
validates :name, presence: true
scope :weapons, -> { where(type: 'Weapon') }
scope :usable_items, -> { where(type: 'UsableItem') }
scope :key_items, -> { where(type: 'KeyItem') }
scope :by_story, -> (story_id) { where(story_id: story_id) }
end
|
# encoding: utf-8
require 'digest/md5'
module ActiveMerchant #:nodoc:
module Billing #:nodoc:
module Integrations #:nodoc:
module RbkMoney
class Helper < ActiveMerchant::Billing::Integrations::Helper
mapping :account, 'eshopId'
mapping :amount, 'recipientAmount'
mapping :currency, 'recipientCurrency'
mapping :order, 'orderId'
mapping :return_url, 'successUrl'
mapping :cancel_return_url, 'failUrl'
mapping :description, 'serviceName'
mapping :email, 'user_email'
mapping :due_date, 'DueDate'
attr_accessor :order_lines
CUSTOM_OPTIONS = Set.new [
:description,
:cancel_return_url,
:return_url,
:email,
:order_lines,
:due_date,
]
ORDER_LINES_FIELDS = Set.new [
:Name,
:Description,
:TotalPrice,
:Count,
]
# userFields never used actually
SIGNATURE_FIELDS = %w(eshopId recipientAmount recipientCurrency user_email serviceName orderId userFields)
def initialize(order, account, options)
options = options.dup
@secret_key = options.delete(:secret_key)
fields = options.extract!(*CUSTOM_OPTIONS)
super(order, account, options).tap {
fields.each { |field, value| send "#{field}=", value }
}
end
def signature(fields)
s = SIGNATURE_FIELDS.map{|key| fields[key]}.join('::') + "::#{@secret_key}" # Seriously, fuck this shit
Digest::MD5.hexdigest(s)
end
def form_fields
result = super
result['hash'] = signature(result)
order_lines.try(:each_with_index) do |line, i|
ORDER_LINES_FIELDS.each do |field|
result["PurchaseItem_#{i}_#{field}"] = line[field]
end
end
result
end
end
end
end
end
end
|
class RenameTables < ActiveRecord::Migration
def self.up
rename_table(:tables, :mod_tables)
end
end
|
require 'spec_helper'
module Annealing
describe Polygon do
it "is a list of points" do
p = Polygon.new([
Point.new(1,2),
Point.new(2,3)
])
expect(p.points.first).to eq Point.new(1,2)
end
it "supports equality checking" do
p1 = Polygon.new([Point.new(1,2), Point.new(2,3)])
p2 = Polygon.new([Point.new(1,2), Point.new(2,3)])
p3 = Polygon.new([Point.new(3,2), Point.new(2,3)])
p4 = Polygon.new([Point.new(2,3), Point.new(1,2)])
expect(p1).to eq p2
expect(p1).to_not eq p3
expect(p1).to eq p4 # order independent
end
it "supports equality checking with make" do
p1 = Polygon.make([1.0,2.0], [2.0,3.0])
p2 = Polygon.make([1,2], [2,3])
p3 = Polygon.make([3,2], [2,3])
p4 = Polygon.make([2,3], [1,2])
expect(p1).to eq p2
expect(p1).to_not eq p3
expect(p1).to eq p4 # order independent
end
it "constructs a little more easily" do
p = Polygon.make([100,200], [200,300], [100,300])
p2 = Polygon.new([ Point.new(100,200), Point.new(200,300), Point.new(100,300) ])
expect(p).to eq(p2)
end
it "makes with a Point" do
p = Polygon.make(Point.new(100,200), [200,300], [100,300])
p2 = Polygon.new([ Point.new(100,200), Point.new(200,300), Point.new(100,300) ])
expect(p).to eq(p2)
end
describe "#area" do
it "returns the area of the polygon" do
p = Polygon.make([100,200], [200,300], [100,300])
expect(p.area).to eq(5000.0)
end
it "is always positive" do
p = Polygon.make([20.0,5.0], [15.0,12.5], [20.0,12.5])
expect(p.area).to eq(18.75)
end
end
describe "#triangulate" do
let(:square) { Polygon.make([100,200], [200,200], [200,100], [100,100]) }
it "cuts a square up properly" do
triangulated = PolyGroup.new([
Polygon.make([100,200], [200,200], [200,100]),
Polygon.make([100,200], [200,100], [100,100])
])
expect(square.triangulate).to eq(triangulated)
end
it "is idempotent" do
triangulated = PolyGroup.new([
Polygon.make([100,200], [200,200], [200,100]),
Polygon.make([100,200], [200,100], [100,100])
])
expect(square.triangulate.triangulate).to eq(triangulated)
end
end
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
rescue_from PG::ForeignKeyViolation, with: :has_associated_records
private
def has_associated_records
redirect_to :back
flash[:error] = I18n.t('.has_associated_records')
end
end
|
require('rspec')
require('word_count')
describe('String#word_count') do
it('will compare first string with an identical second string and return a count of one for its number of occurences') do
expect("duck".word_count("duck")).to(eq(1))
end
it('will compare first string with a different second string and return a count of zero for its number of occurences') do
expect("duck".word_count("dog")).to(eq(0))
end
it('will compare a string of multiple words with a single word string and return a count of 1 for its number of occurrences in first string') do
expect("keep calm and quack on".word_count("quack")).to(eq(1))
end
it('will compare a string of multiple words with a single word string and return a count of 0 for its number of occurrences in first string') do
expect("keep calm and quack on".word_count("yo")).to(eq(0))
end
it('will compare a string of multiple words with a single word string and return a count of 3 for its number of occurrences in first string') do
expect("keep calm and quack quack quack on".word_count("quack")).to(eq(3))
end
it('will compare a string of multiple words with a single word string and return a count of 2 despite capitalization') do
expect("KEEP CALM and QUACK QUACK ON".word_count("quack")).to(eq(2))
end
it('will compare a string of multiple words with a single word string and return a count of 4 despite capitalization') do
expect("keep calm and quack quack quack quack on".word_count("QUACK")).to(eq(4))
end
it('will compare a string of multiple words with a single word string and return a count of 2 taking into account partial matches and punctuation') do
expect("Hello Ducks, welcome to introDUCKtion!".word_count("duck")).to(eq(2))
end
end
|
RSpec::Matchers.define :fail do
supports_block_expectations
match do |block|
begin
block.call
false
rescue Yt::Error => error
@reason ? error.reasons.include?(@reason) : true
end
end
chain :with do |reason|
@reason = reason
end
end |
require File.join(File.dirname(__FILE__), "spec_helper")
describe "ClauseCluster" do
before(:all) do
@required = [:operator, :lhs, :rhs]
@typed = {:operator => String}
@polymophic = {:lhs => [Clause, ClauseCluster], :rhs => [Clause, ClauseCluster]}
@enumerated = {:operator => [ClauseCluster::AND, ClauseCluster::OR]}
@readable = "Property1 of Entity1 DOES NOT EQUAL Value1 AND Property2 of Entity2 EQUALS Value2"
end
before(:each) do
@obj = ClauseCluster.new
@obj.operator = ClauseCluster::AND
@obj.lhs = Clause.new
@obj.rhs = Clause.new
@obj.lhs.comparator = Clause::NOT_EQUAL
@obj.lhs.property_value = "Value1"
@obj.lhs.property = Property.new
@obj.lhs.entity = Entity.new
@obj.lhs.property.name = "Property1"
@obj.lhs.entity.name = "Entity1"
@obj.rhs.comparator = Clause::EQUAL
@obj.rhs.property_value = "Value2"
@obj.rhs.property = Property.new
@obj.rhs.entity = Entity.new
@obj.rhs.property.name = "Property2"
@obj.rhs.entity.name = "Entity2"
end
it_should_behave_like "Validatable"
it_should_behave_like "Readable"
it_should_behave_like "Clonable"
describe "evaluate(rule_base)" do
before(:each) do
@rule_base = RuleBase.new
@fact1 = Fact.new
@fact1.entity = @obj.lhs.entity
@fact1.property = @obj.lhs.property
@fact2 = Fact.new
@fact2.entity = @obj.rhs.entity
@fact2.property = @obj.rhs.property
@rule_base.add_fact(@fact1)
@rule_base.add_fact(@fact2)
end
it "should return UNKNOWN if lhs or rhs are UNKNOWN" do
@obj.evaluate(@rule_base).should == Rule::UNKNOWN
end
describe "operator is OR" do
before(:each) do
@obj.operator = ClauseCluster::OR
end
it "should return TRUE if either lhs or rhs are TRUE" do
@fact1.property_value = @obj.lhs.property_value
@fact1.comparator = @obj.lhs.comparator
@obj.evaluate(@rule_base).should == Rule::TRUE
end
it "should return FALSE if both lhs or rhs are FALSE" do
@fact1.property_value = @obj.lhs.property_value
@fact1.comparator = Clause::EQUAL
@fact2.property_value = @obj.rhs.property_value
@fact2.comparator = Clause::NOT_EQUAL
@obj.evaluate(@rule_base).should == Rule::FALSE
end
end
describe "operator is AND" do
before(:each) do
@obj.operator = ClauseCluster::AND
end
it "should return TRUE if both lhs and rhs are TRUE" do
@fact1.property_value = @obj.lhs.property_value
@fact1.comparator = Clause::NOT_EQUAL
@fact2.property_value = @obj.rhs.property_value
@fact2.comparator = Clause::EQUAL
@obj.evaluate(@rule_base).should == Rule::TRUE
end
it "should return FALSE if either lhs or rhs are FALSE" do
@fact1.property_value = @obj.lhs.property_value
@fact1.comparator = Clause::EQUAL
@fact2.property_value = @obj.rhs.property_value
@fact2.comparator = Clause::EQUAL
@obj.evaluate(@rule_base).should == Rule::FALSE
end
end
end
describe "entities()" do
it "should contain the list of entities from the clauses" do
entities = @obj.entities
entities.length.should == 2
entities.include?(@obj.lhs.entity).should == true
entities.include?(@obj.rhs.entity).should == true
end
it "should not duplicate entities" do
cc = ClauseCluster.new
cc.operator = ClauseCluster::AND
cc.lhs = @obj
cc.rhs = Clause.new
cc.rhs.comparator = Clause::EQUAL
cc.rhs.property_value = "Value2"
cc.rhs.property = Property.new
cc.rhs.property.name = "Property3"
cc.rhs.entity = cc.lhs.rhs.entity
entities = cc.entities
entities.length.should == 2
entities.include?(@obj.lhs.entity).should == true
entities.include?(@obj.rhs.entity).should == true
end
end
end |
FactoryGirl.define do
factory :election do
name { Faker::Name.name }
category { Faker::Name.name }
end
end |
require 'rails_helper'
describe User do
it {should have_many(:photos)}
it {should have_many(:comments)}
end
|
require "integration/factories/collection_factory"
class SqlInstancesFactory < CollectionFactory
def initialize(example)
super(Fog::Google[:sql].instances, example)
end
def cleanup
super
end
def params
# Name has a time suffix due to SQL resources API objects having
# a _very_ long life on the backend (n(days)) after deletion.
{ :name => "#{resource_name}-#{Time.now.to_i}",
:region => TEST_SQL_REGION,
:tier => TEST_SQL_TIER }
end
end
|
class ChangeModeId < ActiveRecord::Migration
def up
#http://stackoverflow.com/questions/8503156/altered-my-database-structure-in-development-so-tried-to-reset-heroku-deployed
remove_index :vim_commands, [:language, :mode_id, :command]
rename_column :vim_commands, :mode_id, :old_mode_id
add_column :vim_commands, :mode_id, :integer
VimCommand.reset_column_information
VimCommand.all.each {|e| e.update_attribute(:mode_id, e.old_mode_id.to_i) }
remove_column :vim_commands, :old_mode_id
add_index :vim_commands, [:language, :mode_id, :command], unique: true, name: "idx_l_m_c"
end
def down
raise IrreversibleMigration
end
end
|
require "./core/game.rb"
require "./core/factory.rb"
require "./places/place.rb"
# require_relative "../place"
# require_relative "blacksmith"
# require_relative "sorceress"
# require_relative "iron_market"
# require_relative "iron_house"
# require_relative "iron_church"
# require_relative "iron_knight_order"
# require_relative "iron_horse_stable"
class IronVillage < Place
include Game
def go
clear
show_sign
end
def show_sign
out "iron_village_sign_says", :speak_say
out "iron_village_welcome", :speak_text
out "iron_village_sign2_says", :speak_say
out "iron_village_sign2", :speak_text
end
def avaliable_commands
super + [ :go, :level, :life, :places ]
end
def avaliable_places
iron_forest = Factory.instance.iron_forest
iron_castle = Factory.instance.iron_castle
[ iron_forest, iron_castle]
end
def name
text("iron_village_name")
end
def symbol
:iron_village
end
end
|
require 'decisiontree'
require 'zlib'
class Analyzer
ATTRIBUTES = [
'Existing chequing balance',
'Loan duration in months',
'Credit history status',
'Purpose for loan',
'Loan amount',
'Value of savings',
'Present employment length',
'Relationship status and sex',
'Other debtors/guarantors',
'Property status',
'Age in years',
'Other loans',
'Housing status',
'Job status',
'Foreign worker status'
].freeze
def predict(testing_array)
tree.predict(testing_array)
end
def sync
if File.file?("#{Rails.root}/lib/data/german_credit.decision_tree")
data_modified = File.mtime("#{Rails.root}/lib/data/german.data")
tree_modified = File.mtime(
"#{Rails.root}/lib/data/german_credit.decision_tree"
)
if data_modified > tree_modified ||
File.zero?("#{Rails.root}/lib/data/german_credit.decision_tree")
construct_tree
end
else
construct_tree
end
end
def test(test_standard)
data = formatted_data
training_range = ((data.length * 80) / 100.to_f).ceil
test_range = data.length - training_range
training = data.first(training_range)
test = data.last(test_range)
dec_tree = DecisionTree::Bagging.new(ATTRIBUTES, training, 2, :continuous)
dec_tree.train
correct = 0
test.each do |t|
predict = dec_tree.predict(t)
correct += 1 if predict.first == t.last
end
(correct.to_f / test.length.to_f) > test_standard
end
private
def tree
marshalled_tree = File.read(
"#{Rails.root}/lib/data/german_credit.decision_tree"
)
marshalled_tree = Zlib::Inflate.inflate(marshalled_tree)
Marshal.load(marshalled_tree)
end
def construct_tree
data = formatted_data
dec_tree = DecisionTree::Bagging.new(ATTRIBUTES, data, 2, :continuous)
dec_tree.train
save_tree(dec_tree)
end
def save_tree(dec_tree)
marshalled_tree = Marshal.dump(dec_tree)
marshalled_tree = Zlib::Deflate.deflate(marshalled_tree)
File.open("#{Rails.root}/lib/data/german_credit.decision_tree", 'wb') do |f|
f.write(marshalled_tree)
end
end
def formatted_data
data = File.readlines("#{Rails.root}/lib/data/german.data").map do |line|
line.split.map do |item|
new_value = if item == 'A410'
10
else
item[0] == 'A' ? item[-1, 1] : item
end
new_value.to_f
end
end
data.shuffle
end
end
|
module ApplicationHelper
# def current_user
# if !cookies[:user_identifier].nil?
# @user = User.find_by_identifier( cookies[:user_identifier])
# if @user.nil?
# create_user
# else
# @user
# end
# else
# create_user
# end
# end
# def create_user
# @user = User.new
# @user.identifier = generate_token
# @user.save
# cookies[:user_identifier] = @user.identifier
# @user
# end
# def generate_token
# loop do
# random_token = SecureRandom.urlsafe_base64(nil, false)
# break random_token unless User.exists?(identifier: random_token)
# end
# end
end
|
class Pick < ActiveRecord::Base
belongs_to :user
belongs_to :game
belongs_to :winner, class_name: "Team"
validates :user, :game, :winner, presence: true
end
|
# You want to add up your expenses for the year. Create an array of numbers (integers or floats) that represents your expenses, eg:
# [250, 7.95, 30.95, 16.50]
# Add up the numbers and output the result.
# Tip: you may need a variable to keep track of the sum total. What value should it start at?
# Put this code into a method. The method should take an array as an argument and return the sum of the expenses in the array. Call the method twice with different arrays.
expenses1 = [250, 7.95, 30.95, 16.50]
expenses2 = [6, 5, 88, 9.9]
def total_sum(expenses)
sum = 0
expenses.each do |number|
sum = sum + number
end
return sum
end
puts total_sum(expenses1)
puts total_sum(expenses2)
# def add_array(expenses)
# total = expenses.sum
# return total
# end
# puts add_array(expenses1)
# puts add_array(expenses2) |
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:email])
if user
if user.authenticate(params[:password])
session["user_id"] = user.id
flash["notice"] = "Welcome back, #{user.name}"
cart = Cart.new
cart.user_id = user.id
cart.save
session["cart_id"] = cart.id
redirect_to categories_url
return
else
end
else
end
redirect_to login_url, notice: "Invalid email or password"
end
def destroy
reset_session
redirect_to categories_url
end
end |
#encoding: UTF-8
class IndividualOption
include Mongoid::Document
include Mongoid::Timestamps
store_in collection: "IndividualOption", database: "dishgo"
field :name, localize: true
field :price, type: Float
field :published, type: Boolean
field :size_prices, type: Array
field :draft_size_prices, type: Array
field :size_ind_opt_id, type: String
field :position, type: Integer
field :price_according_to_size, type: Boolean, default: false
field :draft, type: Hash
belongs_to :options, index: true, :class_name => 'DishOption', index: true, inverse_of: :individual_option
belongs_to :draft_options, index: true, :class_name => 'DishOption', index: true, inverse_of: :draft_individual_option
belongs_to :icon, class_name: "Icon", index: true
belongs_to :draft_icon, class_name: "Icon", index: true
belongs_to :restaurant, index: true
belongs_to :odesk, index: true
default_scope -> {asc(:position)}
index({ _id:1 }, { unique: true, name:"id_index" })
def load_data_from_json individual_option, request_restaurant
draft = {}
if individual_option["size_prices"]
self.draft_size_prices = individual_option["size_prices"]
end
icon = individual_option["icon"]
if icon and !icon["id"].blank?
img = Icon.find(icon["id"])
self.draft_icon = img unless self.draft_icon == img
end
draft[:name] = individual_option["name"]
draft[:price] = individual_option["price"].to_f
draft[:price_according_to_size] = individual_option["price_according_to_size"].to_bool
self.draft = draft
self.save
end
def odesk_load_data_from_json individual_option, odesk_request
# Rails.logger.warn "Individual Options\n---------"
draft = {}
if individual_option["size_prices"]
self.draft_size_prices = individual_option["size_prices"]
end
icon = individual_option["icon"]
if icon and !icon["id"].blank?
img = Icon.find(icon["id"])
self.draft_icon = img unless self.draft_icon == img
end
draft[:name] = individual_option["name"]
draft[:price] = individual_option["price"].to_f
draft[:price_according_to_size] = individual_option["price_according_to_size"].to_bool
self.draft = draft
# Rails.logger.warn "End Ind_Opts\n---------"
self.save
end
def publish_menu
self.name_translations = self.draft["name"]
self.price = self.draft["price"]
self.size_prices = self.draft_size_prices
self.price_according_to_size = self.draft["price_according_to_size"]
self.icon_id = self.draft_icon_id
self.save
end
def reset_draft_menu
draft = {}
draft["name"] = self.name_translations
draft["price"] = self.price
draft["price_according_to_size"] = self.price_according_to_size
self.draft = draft
self.draft_size_prices = self.size_prices
self.draft_icon = self.icon
self.save
end
def api_as_document
hash = self.as_document
hash["size_prices"] = hash["size_prices"].collect do |s|
s["id"] = self.id.to_s + s["size_id"].to_s
next s
end if self.price_according_to_size
return hash
end
end |
require "serverspec"
require "docker"
#require 'pry-byebug'
describe "jenkins Dockerfile" do
before(:all) do
image = Docker::Image.build_from_dir('images/jenkins')
set :os, family: :debian
set :backend, :docker
set :docker_image, image.id
set :docker_container_create_options, {'Cmd' => ['/usr/local/bin/jenkins.sh']}
end
it "jenkins user" do
expect(ps_aux).to include("jenkins")
end
def ps_aux
command("ps aux").stdout
end
describe process("java") do
it { should be_running }
end
end
|
require 'test_helper'
class AlertTest < ActiveSupport::TestCase
subject { @alert || Alert.new }
should belong_to(:account)
should belong_to(:cinstance)
should validate_presence_of(:utilization)
should validate_presence_of(:level)
should validate_numericality_of(:level)
should validate_numericality_of(:utilization)
def test_by_level
FactoryBot.create(:limit_alert, level: 50)
FactoryBot.create(:limit_alert, level: 80)
alerts = Alert.by_level(80)
assert_kind_of Alert::ActiveRecord_Relation, alerts
assert_equal 1, alerts.count
end
context 'Alert#kind' do
should 'should return :alert if its alert' do
assert_equal :alert, Alert.new(:level => 99).kind
assert_equal :alert, Alert.new(:level => 0).kind
end
should 'should return :violation if its violation' do
assert_equal :violation, Alert.new(:level => 100).kind
assert_equal :violation, Alert.new(:level => 300).kind
end
end
end
|
# /*
# Enter your query below.
# Please append a semicolon ";" at the end of the query
# */
# select buyer_id + 'TOTAL_WORTH'
# from house
# Join price
# on house.house_id = price.house_id
# Group by buyer_id
# having (SUM(price.price) > 100000000) AND (Count(*)>1)
# ;
# @param {Integer[]} bits
# @return {Boolean}
def is_one_bit_character(bits)
until bits.length <=2
if bits.first == 1
2.times {bits.shift}
else
bits.shift
end
end
bits == [0] || bits ==[0,0]
end
class KthLargest
=begin
:type k: Integer
:type nums: Integer[]
=end
attr_accessor :k, :nums
def initialize(k, nums)
@k=k
@nums=nums.sort
end
=begin
:type val: Integer
:rtype: Integer
=end
def log_insert(arr,val)
return if arr.empty?
if arr.length==1
return val<arr.first ? 0 : 1
end
mid_idx = arr.length/2
mid_two = arr[mid_idx-1..mid_idx]
return mid_idx if val > mid_two.first && val < mid_two.last
if val > mid_two.last
res = log_insert(arr[mid_idx+1..-1],val)
return res + (mid_idx*2)-1 if res
else
return log_insert(arr[0...mid_idx-1],val)
end
end
def add(val)
insert_idx = self.log_insert(@nums,val)
if insert_idx == 0
@nums.unshift(val)
else
@nums = @nums[0...insert_idx] + [val] + @nums[insert_idx..-1]
end
@nums[-k]
end
end
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest.new(k, nums)
# param_1 = obj.add(val) |
require "rails_helper"
RSpec.describe DialUserIntoIncomingCall do
describe "#call" do
it "updates the call when the connection succeeds" do
incoming_call = create(:incoming_call, :with_participant)
stub_const("ConnectCall", spy(call: Result.success(sid: "1234")))
result = described_class.new(
incoming_call
).call
expect(result.success?).to be(true)
expect(incoming_call.sid).to eq("1234")
expect(incoming_call.in_state?(:initiated)).to be(true)
end
it "marks the call as failed when the connection does not succeed" do
incoming_call = create(:incoming_call, :with_participant)
stub_const("ConnectCall", spy(call: Result.failure("failed")))
result = described_class.new(
incoming_call
).call
expect(result.success?).to be(false)
expect(result.errors).not_to be_empty
expect(incoming_call.in_state?(:failed)).to be(true)
end
end
end
|
class ChangeSessionTableToGame < ActiveRecord::Migration
def self.up
rename_table :sessions, :games
end
def self.down
rename_table :games, :session
end
end
|
require 'test_helper'
class SessionsControllerTest < ActionController::TestCase
test 'create invalid' do
User.stub_any_instance :authenticate, nil do
post :create
end
assert_redirected_to :root
end
test 'create valid' do
u = users(:base)
User.stub_any_instance :authenticate, u do
assert_difference lambda { LogEntry.logins.count } do
post :create, params: { email: u.email }
end
end
assert_redirected_to :posts
assert_equal u.id, session['user_id']
end
test 'create valid admin, without todays entry' do
u = users(:admin)
u.entries.delete_all
User.stub_any_instance :authenticate, u do
assert_difference lambda { LogEntry.logins.count } do
post :create, params: { email: u.email }
end
end
assert_redirected_to entries_url
assert_equal u.id, session['user_id']
end
end
|
# encoding: utf-8
require 'devise/mapping'
module Devise #:nodoc:
module Oauth2Authenticatable #:nodoc:
# OAuth2 view helpers to easily add the link to the OAuth2 connection popup and also the necessary JS code.
#
module Helpers
# Creates the link to
def link_to_oauth2(scope, link_text, options={})
callback_url = send("#{scope}_oauth_callback_url")
link_to link_text, Devise::oauth2_client.web_server.authorize_url(
:redirect_uri => callback_url,
:scope => Devise::requested_scope
), options
end
end
end
end
::ActionView::Base.send :include, Devise::Oauth2Authenticatable::Helpers |
class UsersController < ApplicationController
def create
@user = User.new(user_params)
if @user.save
redirect_to map_path
else
redirect_to root_path
end
end
private
def user_params
params.require(:user).permit(:name, :email)
end
end
|
require 'spec_helper'
describe Spree::Asset do
before(:each) do
@asset = Spree::Asset.new
end
it "should return true if asset has_alt?" do
@asset.alt = "omg"
expect(@asset.has_alt?).to eq(true)
end
it "should return false unless asset has_alt?" do
expect(@asset.has_alt?).to eq(false)
end
end
|
# == Schema Information
#
# Table name: goals
#
# id :integer not null, primary key
# user_id :integer not null
# name :text(255) not null
# created_at :datetime
# updated_at :datetime
# completed :boolean
#
class Goal < ActiveRecord::Base
validates :user_id, null: false
belongs_to(
:user,
class_name: "User",
foreign_key: :user_id,
primary_key: :id
)
has_many(
:comments,
as: :commentable
)
end
|
class AddAddresseeToMicroposts < ActiveRecord::Migration
def change
add_column :microposts, :addressee_id, :integer
end
end |
class SystemDecorator
def initialize(system)
@system=system
end
def set_message_and_message_color
closed_incident_count=@system.incidents.where(status: 'Closed').count
last_incident_date=@system.last_incident_date
days_since_last_incident=(Date.today-last_incident_date).to_i if last_incident_date
if (closed_incident_count>0)
incident='Incident'.pluralize(closed_incident_count)
return 'system-red',"#{closed_incident_count} #{incident} in the last 24 hours"
elsif (last_incident_date==nil)
return 'system-green', 'No previous incidents recorded'
elsif (days_since_last_incident>0)
day='Day'.pluralize(days_since_last_incident)
return 'system-green', "#{days_since_last_incident} #{day} since the last incident"
else
return 'system-red', "Houston we have a problem!"
end
end
def method_missing(method_name, *args, &block)
@system.send(method_name, *args, &block)
end
def respond_to_missing?(method_name, include_private=false)
@system.respond_to?(method_name, include_private) || super
end
end |
class HomeController < ApplicationController
before_action :set_entry, only: [:show, :edit, :update, :destroy]
def index
if user_signed_in? && Entry.today(current_user).exists?
respond_to do |format|
format.html { redirect_to reports_path }
end
elsif user_signed_in? && !Entry.today(current_user).exists?
respond_to do |format|
format.html { redirect_to new_entry_path }
end
else
@entry = Entry.new
end
end
end
|
class Indocker::Containers::ContainerBuilder
attr_reader :container
def initialize(name:, configuration:, container: nil)
@container = container || Indocker::Containers::Container.new(name)
@configuration = configuration
configuration.add_container(@container)
end
def command(name)
@container.set_start_command(name)
end
def build_args(opts)
raise ArgumentError.new("build args should be a Hash") if !opts.is_a?(Hash)
opts = Indocker::HashMerger.deep_merge(@container.build_args, opts) # merge with already defined args
@container.set_build_args(opts)
self
end
def tags(*tag_list)
if !tag_list.is_a?(Array)
tag_list = [tag_list]
end
@container.set_tags(tag_list)
self
end
def image(name)
path = Indocker.image_files[name]
if !path
raise ArgumentError.new("Image :#{name} was not found in bounded contexts folder")
else
require path
end
image = @configuration.images.detect do |image|
image.name == name
end
if !image
Indocker.logger.error("image :#{name} was not found in configuration :#{@configuration.name}")
exit 1
end
@container.set_image(image)
self
end
def servers(*server_list)
server_list.uniq!
extra_servers = server_list - Indocker.servers.map(&:name)
if !extra_servers.empty?
Indocker.logger.error("unrecognized servers #{extra_servers.inspect} for container :#{@container.name} in configuration :#{@configuration.name}")
exit 1
end
servers = Indocker.servers.select {|s| server_list.include?(s.name)}
@container.set_servers(servers)
self
end
def networks(*network_list)
network_list.uniq!
networks = Indocker.networks.select do |network|
network_list.include?(network.name)
end
extra_networks = network_list - networks.map(&:name)
if !extra_networks.empty?
raise ArgumentError.new("unknown networks: #{extra_networks.inspect} for container :#{@container.name}")
end
@container.set_networks(networks)
self
end
def volumes(*volume_list)
volume_list.uniq!
volumes = Indocker.volumes.select do |volume|
volume_list.include?(volume.name)
end
extra_volumes = volume_list - volumes.map(&:name)
if !extra_volumes.empty?
raise Indocker.logger.error("unknown volumes: #{extra_volumes.inspect} for container :#{@container.name}")
exit 1
end
@container.set_volumes(volumes)
self
end
def daemonize(flag)
@container.daemonize(flag)
self
end
def depends_on(*container_list)
if !container_list.is_a?(Array)
container_list = [container_list]
end
container_list.uniq!
container_list.each do |name|
path = Indocker.container_files.fetch(name) do
Indocker.logger.error("Dependent container :#{name} was not found in bounded contexts dir for container :#{@container.name}")
exit 1
end
require path
end
containers = @configuration.containers.select do |container|
container_list.include?(container.name)
end
containers.each do |container|
@container.add_dependent_container(container)
end
self
end
def soft_depends_on(*container_list)
container_list = Array(container_list).uniq
container_list.each do |name|
path = Indocker.container_files.fetch(name) do
Indocker.logger.error("Soft dependent container :#{name} was not found in bounded contexts dir for container :#{@container.name}")
exit 1
end
require path
end
containers = @configuration.containers.select do |container|
container_list.include?(container.name)
end
containers.each do |container|
@container.add_soft_dependent_container(container)
end
self
end
def before_start(proc)
container.set_before_start_proc(proc)
self
end
def after_start(proc)
container.set_after_start_proc(proc)
self
end
def after_deploy(proc)
container.set_after_deploy_proc(proc)
self
end
def start(opts)
opts = Indocker::HashMerger.deep_merge(container.start_options, opts)
container.set_start_options(opts)
self
end
def scale(number)
container.set_scale(number)
end
def redeploy_schedule(schedule)
container.set_redeploy_schedule(schedule)
self
end
end |
#Encrypt
#Write a method with an argument(password)
#Write a loop to iterate through each letter and replace with the next one.
#Use conditional statement to eliminate edge cases.
#Decrypt
#Write a method that takes an argument(password)
#Write a loop to iterate through each letter.
#Replace each letter with the previous one.
# METHOD DECLARATIONS
#Encripts a string by advancing one letter forward
def encrypt(password)
counter = 0
#declare emty string to add to
result = ""
#loop over the string letters
while counter < password.length
letter = password[counter]
#eliminate edge cases
if letter == " "
result << " "
elsif letter == "z"
result << "a"
else
result << letter.next
end
counter += 1
end
result
end
#decrypt password by going back one letter backwards
def decrypt(password)
counter = 0
alphabet = "abcdefghijklmnopqrstuvwxyz"
#declare emty string to add to
result = ""
#loop over the string letters
while counter < password.length
letter = password[counter]
#eliminate edge cases
if letter == " "
result << " "
elsif letter == "a"
result << "z"
else
#Use index built in method to get the index from the alphabet minus one
alph_index = alphabet.index(letter) - 1
#add the alphabet letter coresponding to the index and add it to result string
result << alphabet[alph_index]
end
counter += 1
end
result
end
#Driver CODE
#Ask the agent what they want to do
puts "Do you want to encrypt or decrypt?"
answer = gets.chomp
puts "Type a password!"
password = gets.chomp.downcase
if answer == "encrypt"
puts encrypt(password)
else
puts decrypt(password)
#say good bye
end
puts "Have a nice day!"
# decrypt(encrypt("swordfish")) works because first the string is encripted (what is inside the right barackets is evaluated)and then the decrypt method is executed.
|
require 'rails_helper'
# Acceptance Criteria:
#
# - Reviews have a vote score
# -- Vote score is net value of all up and down votes
# - With no vote registered, upvoting or downvoting set the vote
# - Clicking again on an already-made vote removes it
# - Clicking on the other option after a vote is made switches it to the new choice
# - A user can only vote once per review
# - Feature must use AJAX to avoid page reloads
feature "User votes on a review without logging in" do
before(:each) do
item = create(:item)
create(:review, item: item)
visit item_path(item)
end
scenario "User tries to upvote and isn't logged in (no AJAX)" do
first(".upvote-0").click
expect(page).to have_content "Please sign in to cast your vote!"
end
scenario "User tries to downvote and isn't logged in (no AJAX)" do
first(".downvote-0").click
expect(page).to have_content "Please sign in to cast your vote!"
end
scenario "User tries to upvote and isn't logged in (with AJAX)", js: true do
first(".upvote-0").click
expect(page).to have_content "Please sign in to cast your vote!"
end
scenario "User tries to downvote and isn't logged in (with AJAX)", js: true do
first(".downvote-0").click
expect(page).to have_content "Please sign in to cast your vote!"
end
end
|
require_relative 'board'
require_relative 'player'
class Game
attr_accessor :first_player, :second_player, :current_player, :board
def initialize(board = Board.new)
@board = board
@first_player = nil
@second_player = nil
@current_player = nil
end
def create_game
combatents
@board.show
play_turns
result
end
def create_player(number, duplicate_choice = nil)
puts "Player ##{number}, what is your name?"
name = gets.chomp.upcase
choice = choice_input(duplicate_choice)
Player.new(name, choice.downcase)
end
def turn(number)
choice = valid_input(number)
@board.position(choice, current_player.choice)
@board.show
end
def play_turns
@current_player = first_player
until @board.full?
puts "#{current_player.name} please pick a position on the board!"
position = gets.chomp.to_i
turn(position)
break if @board.game_over?
@current_player = switch_players
end
end
def combatents
@first_player = create_player(1)
@second_player = create_player(2, first_player.choice)
end
private
def choice_input(duplicate_choice)
puts 'and your weapon of choice? (choose a letter)'
input = gets.chomp.downcase
while input == duplicate_choice
puts 'That weapon is taken, please choose another.'
input = gets.chomp.downcase
end
input
end
def valid_input(number) #work on this
input = number.to_i
unless input.positive? && input <= 7
puts 'Please enter a number ranging from 1-7'
input = gets.chomp.to_i
valid_input(input)
end
input.to_i
end
def switch_players
if current_player == first_player
@current_player = second_player
else
@current_player = first_player
end
end
def result
if @board.game_over?
puts "Yay #{current_player.name} has come out victorious!"
else
puts 'Tie game!'
end
play_again?
end
def play_again?
puts 'Would you like to play again? y or n?'
input = gets.chomp.downcase
if input == 'y'
@board = Board.new
create_game
else
puts 'Thanks for playing!'
end
end
end |
class GamesCreateJobPostings < ActiveRecord::Migration
def change
create_table :job_postings do |t|
t.references :game
t.references :assignment
t.datetime :posted_at
end
end
end
|
require File.dirname(__FILE__) + '/../spec_helper'
# Why so many fixed arg tests? JRuby and I assume other Ruby impls have
# separate call paths for simple fixed arity methods. Testing up to five
# will verify special and generic arity code paths for all impls.
#
# Method naming conventions:
# P - Pre Required Args
# O - Optional Arg
# R - Rest Arg
# Q - Post Required Args (1.9)
describe "Calling a method" do
it "with no arguments is ok" do
def fooP0; 100 end
fooP0.should == 100
end
it "with simple required arguments works" do
def fooP1(a); [a]; end
fooP1(1).should == [1]
def fooP2(a,b); [a,b]; end
fooP2(1,2).should == [1,2]
def fooP3(a,b,c); [a,b,c]; end
fooP3(1,2,3).should == [1,2,3]
def fooP4(a,b,c,d); [a,b,c,d]; end
fooP4(1,2,3,4).should == [1,2,3,4]
def fooP5(a,b,c,d,e); [a,b,c,d,e]; end
fooP5(1,2,3,4,5).should == [1,2,3,4,5]
end
it "works with optional arguments" do
def fooP0O1(a=1); [a]; end
fooP0O1().should == [1]
def fooP1O1(a,b=1); [a,b]; end
fooP1O1(1).should == [1,1]
def fooP2O1(a,b,c=1); [a,b,c]; end
fooP2O1(1,2).should == [1,2,1]
def fooP3O1(a,b,c,d=1); [a,b,c,d]; end
fooP3O1(1,2,3).should == [1,2,3,1]
def fooP4O1(a,b,c,d,e=1); [a,b,c,d,e]; end
fooP4O1(1,2,3,4).should == [1,2,3,4,1]
def fooP0O2(a=1,b=2); [a,b]; end
fooP0O2().should == [1,2]
end
it "works with rest arguments" do
def fooP0R(*r); r; end
fooP0R().should == []
fooP0R(1).should == [1]
fooP0R(1,2).should == [1, 2]
def fooP1R(a, *r); [a, r]; end
fooP1R(1).should == [1, []]
fooP1R(1,2).should == [1, [2]]
def fooP0O1R(a=1, *r); [a, r]; end
fooP0O1R().should == [1, []]
fooP0O1R(2).should == [2, []]
fooP0O1R(2,3).should == [2, [3]]
def fooP1O1R(a, b=1, *r); [a, b, r]; end
fooP1O1R(1).should == [1, 1, []]
fooP1O1R(1,2).should == [1, 2, []]
fooP1O1R(1,2,3).should == [1, 2, [3]]
end
it "with an empty expression is like calling with nil argument" do
def foo(a); a end
foo(()).should be_nil
end
it "with block as block argument is ok" do
def foo(a,&b); [a,yield(b)] end
foo(10) do 200 end.should == [10,200]
foo(10) { 200 }.should == [10,200]
end
it "with block argument converts the block to proc" do
def makeproc(&b) b end
makeproc { "hello" }.call.should == "hello"
makeproc { "hello" }.class.should == Proc
# check that converted proc is indeed behaves like proc,
# not like lambda
def proc_caller(&b) b.call end
def enclosing_method
proc_caller { return :break_return_value }
:method_return_value
end
enclosing_method.should == :break_return_value
end
it "with an object that responds to 'to_proc' as a block argument coerces it to a proc" do
x = "my proc"
class << x
def to_proc; Proc.new {|y| self + y}; end
end
def foo(&b); b.call(" called"); end
def foo2; yield(" yielded"); end
foo(&x).should == "my proc called"
foo2(&x).should == "my proc yielded"
end
it "fails with both lambda and block argument" do
def foo(a,&b); [a,yield(b)] end
l = lambda { 300 }
lambda { eval "foo(10, &l){ 42}"}.should raise_error(SyntaxError)
end
it "with same names as existing variables is ok" do
foobar = 100
def foobar; 200; end
foobar.should == 100
foobar().should == 200
end
it "with splat operator * and literal array unpacks params" do
def fooP3(a,b,c); [a,b,c] end
fooP3(*[1,2,3]).should == [1,2,3]
end
it "with splat operator * and referenced array unpacks params" do
def fooP3(a,b,c); [a,b,c] end
a = [1,2,3]
fooP3(*a).should == [1,2,3]
end
it "without parentheses works" do
def fooP3(a,b,c); [a,b,c] end
(fooP3 1,2,3).should == [1,2,3]
end
it "with a space separating method name and parenthesis treats expression in parenthesis as first argument" do
def myfoo(x); x * 2 end
def mybar
# means myfoo((5).to_s)
# NOT (myfoo(5)).to_s
myfoo (5).to_s
end
mybar().should == "55"
end
it "with invalid argument count raises an ArgumentError" do
def fooP3(a,b,c); end
lambda { fooP3 }.should raise_error(ArgumentError)
lambda { fooP3(1,2) }.should raise_error(ArgumentError)
lambda { fooP3(1,2,3,4) }.should raise_error(ArgumentError)
lambda { fooP3((), (), (), ()) }.should raise_error(ArgumentError)
end
# "Allows infinite arguments" is kinda hard to spec
it "allows any number of args beyond required to method with a splat" do
def foo(a, b, *c); [c.size, c.last]; end
a = Array.new(2500) { Object.new }
obj = a[-1]
lambda { foo 1 }.should raise_error(ArgumentError)
res = foo 1, 2
res.first.should == 0
res.last.nil?.should == true
res = foo 1, 2, 3
res.first.should == 1
res.last.should == 3
res = foo 1, 2, 3, *a
res.first.should == 2501
res.last.should equal(obj)
end
it "allows to pass literal hashes without curly braces as the last parameter" do
def foo(a,b,c); [a,b,c] end
foo('abc', 456, 'rbx' => 'cool', 'specs' => 'fail sometimes', 'oh' => 'weh').should ==
['abc', 456, { 'rbx' => 'cool', 'specs' => 'fail sometimes', 'oh' => 'weh'}]
(foo 'abc', 456, 'rbx' => 'cool', 'specs' => 'fail sometimes', 'oh' => 'weh').should ==
['abc', 456, { 'rbx' => 'cool', 'specs' => 'fail sometimes', 'oh' => 'weh'}]
end
it "allows to literal hashes without curly braces as the only parameter" do
def foo(a); a end
foo(:rbx => :cool, :specs => :fail_sometimes).should ==
{ :rbx => :cool, :specs => :fail_sometimes }
(foo :rbx => :cool, :specs => :fail_sometimes).should ==
{ :rbx => :cool, :specs => :fail_sometimes }
end
end
describe "Calling a private setter method" do
describe "permits self as a receiver" do
module MethodSpecs
class PrivateSetter
attr_reader :foo
attr_writer :foo
private :foo=
def call_self_foo_equals(value)
self.foo = value
end
def call_self_foo_equals_masgn(value)
a, self.foo = 1, value
end
end
end
it "for normal assignment" do
receiver = MethodSpecs::PrivateSetter.new
receiver.call_self_foo_equals(42)
receiver.foo.should == 42
end
it "for multiple assignment" do
receiver = MethodSpecs::PrivateSetter.new
receiver.call_self_foo_equals_masgn(42)
receiver.foo.should == 42
end
end
end
describe "Calling a private getter method" do
it "does not permit self as a receiver" do
module MethodSpecs
class PrivateGetter
attr_reader :foo
private :foo
def call_self_foo
self.foo
end
def call_self_foo_or_equals(value)
self.foo ||= 6
end
end
end
receiver = MethodSpecs::PrivateGetter.new
lambda { receiver.call_self_foo }.should raise_error(NoMethodError)
lambda { receiver.call_self_foo_or_equals(6) }.should raise_error(NoMethodError)
end
end
language_version __FILE__, "method"
|
module Seed
class ChuckNorrisJokesService
def self.build
self.new
end
def initialize
end
def call
Rails.logger.info("- Start #{self.class.name}")
jokes = [
{:joke_type => 0, :sequence => 1, :uuid => 1,
:joke => "The First rule of Chuck Norris is: you do not talk about Chuck Norris."},
{:joke_type => 0, :sequence => 2, :uuid => 2,
:joke => "The Second rule of Chuck Norris is: you do not talk about Chuck Norris."},
{:joke_type => 0, :sequence => 3, :uuid => 3,
:joke => "The Last rule of Chuck Norris is: you do not talk about Chuck Norris."},
{:joke_type => 0, :sequence => 4, :uuid => 4,
:joke => "Chuck Norris counted to infinity... Twice."},
{:joke_type => 0, :sequence => 5, :uuid => 5,
:joke => "And that's why Chuck Norris can divide by zero."},
{:joke_type => 0, :sequence => 6, :uuid => 6,
:joke => "However, if you divide Chuck Norris by zero and you will in fact get one........one bad-ass that is."},
{:joke_type => 0, :sequence => 7, :uuid => 7,
:joke => "Chuck Norris has already been to Mars; that's why there are no signs of life there."},
{:joke_type => 0, :sequence => 8, :uuid => 8,
:joke => "Chuck Norris has also been to Pluto, that's why it is not a planet anymore."},
{:joke_type => 0, :sequence => 9, :uuid => 9,
:joke => "Chuck Norris knows the last digit of pi.."},
{:joke_type => 0, :sequence => 10, :uuid => 10,
:joke => "When Chuck Norris wants an egg, he cracks open a chicken."},
{:joke_type => 0, :sequence => 11, :uuid => 11,
:joke => "Chuck Norris once round-house kicked a salesman. Over the phone."},
{:joke_type => 0, :sequence => 12, :uuid => 12,
:joke => "Chuck Norris can remember the future."},
{:joke_type => 0, :sequence => 13, :uuid => 13,
:joke => "Chuck Norris doesn't age, because time cannot keep up with him."},
{:joke_type => 0, :sequence => 14, :uuid => 14,
:joke => "Chuck Norris can make onions cry."},
{:joke_type => 0, :sequence => 15, :uuid => 15,
:joke => "Chuck Norris can watch the radio."},
{:joke_type => 0, :sequence => 16, :uuid => 16,
:joke => "Chuck Norris knows Victoria's secret."},
]
jokes.each do |j|
joke = AllJoke.find_or_initialize_by(:uuid => j[:uuid])
joke.sequence = j[:sequence]
joke.joke = j[:joke]
joke.joke_type = j[:joke_type]
joke.save
end
Rails.logger.info("- Finish #{self.class.name}")
ServiceResult.new(status: true)
end
end
end
|
require "autotest"
class Autotest::Spec < Autotest
def initialize # :nodoc:
super
clear_mappings
self.libs = libs.split ":"
self.libs << "spec"
self.libs = libs.join File::PATH_SEPARATOR
add_mapping %r%^lib/(.*)\.rb$% do |_, m|
files_matching %r%^spec/#{m[1]}.*_spec.rb$%
end
add_mapping %r%^spec/.*_spec\.rb$% do |filename, _|
filename
end
end
end
|
class RemoveOwnedFromBusinesses < ActiveRecord::Migration[5.2]
def change
remove_column :businesses, :womenown, :string, default: "No"
remove_column :businesses, :familyown, :string, default: "No"
end
end
|
require('pg')
require_relative('./sql_runner.rb')
require_relative('./films.rb')
class Customer
attr_reader :id
attr_accessor :name, :funds
def initialize(params)
@id = params['id'].to_i if params['id']
@name = params['name']
@funds = params['funds'].to_i
end
def save()
sql = "INSERT INTO customers (name, funds) VALUES ('#{@name}', #{@funds}) RETURNING id;"
customer = SqlRunner.run(sql)
@id = customer.first['id'].to_i
end
def delete()
sql = "DELETE FROM customers WHERE id = #{@id};"
SqlRunner.run(sql)
end
def self.delete_all()
sql = "DELETE FROM customers;"
SqlRunner.run(sql)
end
def update()
sql = "UPDATE customers SET
(name, funds) =
('#{@name}',#{@funds})
WHERE id = #{@id};"
SqlRunner.run(sql)
end
def self.all()
sql = "SELECT * FROM customers"
customers = SqlRunner.run(sql)
result = customers.map {|customer| Customer.new(customer)}
return result
end
def which_films()
sql = "SELECT films.* FROM films
INNER JOIN tickets ON films.id = tickets.film_id
INNER JOIN customers ON tickets.customer_id = customers.id
WHERE customers.id = #{@id};"
which_films = SqlRunner.run(sql)
result = which_films.map {|film| Film.new(film)}
return result
end
def pay_for_ticket()
films = which_films()
for film in films
p @funds -= film.price.to_i
end
end
def num_tickets
p which_films.count
end
end |
describe New::Validation do
before do
class ValidationSpec
extend New::Validation
end
end
describe '.validate_option' do
before do
@task = New::Task.new :validate_option, Dir.pwd
end
context 'with required options' do
before do
@option = {
:required => true
}
end
it 'should accept any value' do
expect(ValidationSpec.validate_option(:required, @option, 'foo')).to eq 'foo'
end
it 'should reject missing values' do
expect{ValidationSpec.validate_option(:required, @option, nil)}.to raise_error
expect{ValidationSpec.validate_option(:required, @option, '')}.to raise_error
expect{ValidationSpec.validate_option(:required, @option, [])}.to raise_error
expect{ValidationSpec.validate_option(:required, @option, {})}.to raise_error
end
end
context 'with defaulted options' do
before do
@option = {
:default => 'default value'
}
end
it 'should accept missing values' do
expect(ValidationSpec.validate_option(:default, @option, nil)).to eq 'default value'
expect(ValidationSpec.validate_option(:default, @option, '')).to eq 'default value'
expect(ValidationSpec.validate_option(:default, @option, [])).to eq 'default value'
expect(ValidationSpec.validate_option(:default, @option, {})).to eq 'default value'
end
it 'should accept user values' do
expect(ValidationSpec.validate_option(:default, @option, 'foo')).to eq 'foo'
end
end
context 'with strings' do
before do
@option = {
:validation => /foo_.+_bar/
}
end
it 'should accept regex matches' do
expect(ValidationSpec.validate_option(:type_string, @option, 'foo_BAZ_bar')).to eq 'foo_BAZ_bar'
end
it 'should reject regex mismatches' do
expect{ValidationSpec.validate_option(:type_string, @option, 'bar_BAZ_foo')}.to raise_error
end
end
context 'with symbols' do
before do
@option = {
:type => Symbol,
:validation => /foo_.+_bar/
}
end
it 'should accept regex matches' do
expect(ValidationSpec.validate_option(:type_symbol, @option, 'foo_BAZ_bar')).to eq :foo_baz_bar
end
it 'should reject regex mismatches' do
expect{ValidationSpec.validate_option(:type_symbol, @option, 'bar_BAZ_foo')}.to raise_error
end
end
context 'with booleans' do
before do
@option = {
:type => Boolean
}
end
it 'should accept approved boolean keywords' do
expect(ValidationSpec.validate_option(:type_boolean, @option, 'true')).to eq true
expect(ValidationSpec.validate_option(:type_boolean, @option, 'Yes')).to eq true
expect(ValidationSpec.validate_option(:type_boolean, @option, 'false')).to eq false
expect(ValidationSpec.validate_option(:type_boolean, @option, 'No')).to eq false
end
it 'should reject non-approved keywords' do
expect{ValidationSpec.validate_option(:type_boolean, @option, 'foo')}.to raise_error
end
end
context 'with integers' do
before do
@option = {
:type => Integer,
:validation => (1..10)
}
end
it 'should accept numbers' do
expect(ValidationSpec.validate_option(:type_integer, @option, '1')).to eq 1
expect(ValidationSpec.validate_option(:type_integer, @option, '2.9')).to eq 2
end
it 'should reject out-of-range numbers' do
expect{ValidationSpec.validate_option(:type_integer, @option, '11')}.to raise_error
end
it 'should reject non-numbers' do
expect{ValidationSpec.validate_option(:type_integer, @option, 'foo')}.to raise_error
end
end
context 'with floats' do
before do
@option = {
:type => Float,
:validation => (0.5..10.5)
}
end
it 'should accept numbers' do
expect(ValidationSpec.validate_option(:type_float, @option, '1')).to eq 1.0
expect(ValidationSpec.validate_option(:type_float, @option, '2.9')).to eq 2.9
end
it 'should reject out-of-range numbers' do
expect{ValidationSpec.validate_option(:type_float, @option, '11')}.to raise_error
end
it 'should reject non-numbers' do
expect{ValidationSpec.validate_option(:type_float, @option, 'foo')}.to raise_error
end
end
context 'with arrays' do
context 'with type validation' do
before do
@option = {
:type => Array,
:validation => Symbol
}
end
it 'should accept arrays with matchable types' do
expect(ValidationSpec.validate_option(:type_array, @option, ['foo'])).to eq [:foo]
end
it 'should reject arrays with mismatched types' do
expect{ValidationSpec.validate_option(:type_array, @option, [1])}.to raise_error
end
it 'should compact arrays' do
expect(ValidationSpec.validate_option(:type_array, @option, ['', 'bar'])).to eq [:bar]
end
end
context 'with array validation' do
before do
@option = {
:type => Array,
:validation => [:foo]
}
end
it 'should accept arrays with an object of matching keys' do
expect(ValidationSpec.validate_option(:type_array_hash, @option, [{ :foo => 'foo' }])).to eq([{ :foo => 'foo' }])
end
it 'should reject arrays with an object without matching keys' do
expect{ValidationSpec.validate_option(:type_array_hash, @option, [{ :bar => 'foo' }])}.to raise_error
end
end
end
context 'with hashes' do
context 'with array validation' do
before do
@option = {
:type => Hash,
:validation => [:foo]
}
end
it 'should accept hashes with matching keys' do
expect(ValidationSpec.validate_option(:type_hash_array, @option, { :foo => 'foo' })).to eq({ :foo => 'foo' })
end
it 'should reject hashes without matching keys' do
expect{ValidationSpec.validate_option(:type_hash_array, @option, { :bar => 'foo' })}.to raise_error
end
end
context 'with hash validation' do
before do
@option = {
:type => Hash,
:validation => {
:foo => Integer
}
}
end
it 'should accept hashes with matching keys & types' do
expect(ValidationSpec.validate_option(:type_hash_hash, @option, { :foo => '1' })).to eq({ :foo => 1 })
end
it 'should reject hashes without matching keys' do
expect{ValidationSpec.validate_option(:type_hash_hash, @option, { :bar => '1' })}.to raise_error
end
it 'should reject hashes with matching keys but mismatched types' do
expect{ValidationSpec.validate_option(:type_hash_hash, @option, { :foo => 'foo' })}.to raise_error
end
end
end
end
describe '.validate_class' do
it 'should validate String' do
expect(ValidationSpec.validate_class(:foo, String)).to eq 'foo'
end
it 'should validate Symbol' do
expect(ValidationSpec.validate_class('foo', Symbol)).to eq :foo
end
it 'should validate Boolean' do
expect(ValidationSpec.validate_class('true', Boolean)).to eq true
end
it 'should validate Integer' do
expect(ValidationSpec.validate_class('1', Integer)).to eq 1
end
it 'should validate Float' do
expect(ValidationSpec.validate_class('1', Float)).to eq 1.0
end
it 'should validate Array' do
expect(ValidationSpec.validate_class([1, nil, '', 2], Array)).to eq [1,2]
end
it 'should validate Hash' do
expect(ValidationSpec.validate_class({ :one => 1, :two => nil, :three => '', :four => [], :five => 5 }, Hash)).to eq({ :one => 1, :five => 5 })
end
end
end
|
class PersonMailer < ActionMailer::Base
default from: "manager@control.com"
ADMINISTRATOR_MAIL = "alfredo.roca.mas@gmail.com"
def welcome_email(person)
@person = person
@fullname = "#{@person.name} #{@person.lastname}"
@url = "http://localhost:3000"
mail to: "#{@fullname} <#{@person.email}> ",
cc: ADMINISTRATOR_MAIL,
subject: 'Welcome to the Emergency Manager platform!'
end
end
|
class GridWithInFormEditingOnly < Netzke::Basepack::Grid
column :author__name do |c|
c.editor = {min_chars: 1} # this should be passed to the form combo! TODO: test and refactor
end
def configure(c)
super
c.model = 'Book'
c.enable_edit_inline = false
end
end
|
require 'spec_helper'
describe "Locale Switching Requests" do
subject { response }
I18n.available_locales.each do |locale|
I18n.available_locales.each do |target_locale|
next if locale == target_locale
context "after a validation error" do
context "when failing to create a micropost" do
let(:user) { create(:user) }
context "behaviour" do
before do
sign_in_request(locale, user)
post microposts_path(locale) # nil micropost
get locale_root_url(set_locale: target_locale)
end
it { should redirect_to(locale_root_url(target_locale)) }
end
end
context "when failing to sign up" do
context "behaviour" do
before do
post users_path(locale)
get signup_path(set_locale: target_locale)
end
it { should redirect_to(signup_url(target_locale)) }
end
end
context "when failing to update a user" do
let(:user) { create(:user) }
context "behaviour" do
before do
sign_in_request(locale, user)
put user_path(locale, user)
get edit_user_path(user, set_locale: target_locale)
end
it { should redirect_to(edit_user_url(target_locale, user)) }
end
end
context "when failing to sign in" do
context "behaviour" do
before do
post session_path(locale)
get signin_path(set_locale: target_locale)
end
it { should redirect_to(signin_url(target_locale)) }
end
end
end
end
end
end
|
class AddNewFiledsToPpl < ActiveRecord::Migration
def change
add_column :ppls, :code, :integer
add_column :ppls, :salary, :integer
add_column :ppls, :yearly_off, :integer
add_column :ppls, :daily_hours, :float
add_column :ppls, :over_time_price, :integer
end
end
|
require "httplog/extensions/data_filters/empty_filter"
describe Extensions::DataFilters::EmptyFilter do
subject { described_class.new(filtered_keys: filtered_keys,
filtered_value: filtered_value) }
let(:http_data) { "username=testuser&password=mypass&secret=mysecret" }
let(:json_data) { {username: "testuser", password: "mypass", secret: "mysecret"}.to_json }
let(:filtered_keys) { [:password, :secret] }
let(:filtered_value) { "[FV]" }
describe "#suitable?" do
context "http data" do
it "is true" do
subject.suitable?(http_data).should be_true
end
end
context "json data" do
it "is true" do
subject.suitable?(json_data).should be_true
end
end
end
describe "#filter" do
context "http data" do
it "returns unchanged data" do
subject.filter(http_data).should eq(http_data)
end
end
context "json data" do
it "returns unchanged data" do
subject.filter(json_data).should eq(json_data)
end
end
end
end
|
class AddConstraintsToItemNew < ActiveRecord::Migration[5.0]
def change
remove_foreign_key :documents, :items
add_foreign_key :documents, :items, on_delete: :cascade
end
end
|
class ThemeselectionSection < ActiveRecord::Base
belongs_to :tag_selection
belongs_to :section
end |
# frozen_string_literal: true
require 'integration_test'
require 'application_system_test_case'
# This file contains different ways to log in during tests to test wether they interfere with each other.
class LoginControllerTest < IntegrationTest
test 'controller test login' do
login(:uwe)
end
test 'controller action login' do
post login_password_path, params: LoginIntegrationTest::LOGIN_PARAMS
assert_logged_in(:uwe)
end
end
class LoginIntegrationTest < IntegrationTest
LOGIN_PARAMS = { user: { login: 'uwe', password: 'atest' } }.freeze
test 'integration test login' do
login(:uwe)
assert_logged_in
end
test 'integration action login' do
post '/login/password', params: LOGIN_PARAMS
assert_logged_in
end
end
class LoginSystemTest < ApplicationSystemTestCase
include ActionMailer::TestCase::ClearTestDeliveries
setup { screenshot_section :session }
def test_login_with_password
screenshot_group :login_with_password
visit '/'
click_on 'Medlemssider'
assert_current_path '/login?detour%5Baction%5D=index&detour%5Bcontroller%5D=welcome'
visit '/login/password'
assert_current_path '/login/password'
screenshot :empty_form
fill_in 'user_login', with: :uwe
fill_in 'user_password', with: :atest
screenshot :filled_in
click_button 'Logg inn'
assert_current_path root_path
screenshot :welcome
end
def test_send_email_link
screenshot_group :email_link
visit '/'
click_on 'Medlemssider'
assert_current_path '/login?detour%5Baction%5D=index&detour%5Bcontroller%5D=welcome'
screenshot :email_form
fill_in 'user_identity', with: users(:uwe).email
screenshot :email_filled_in, skip_area: [16, 14, 48, 46]
click_on 'Send melding'
assert_current_path login_pin_form_path identity: 'uwe@example.com'
screenshot :email_sent
UserMessageSenderJob.perform_now
assert_equal 1, Mail::TestMailer.deliveries.size,
-> { Mail::TestMailer.deliveries.map(&:subject).to_s }
email = Mail::TestMailer.deliveries[0]
login_link_text = 'Klikk her for å logge på Romerike Jujutsu Klubb!'
assert(m = %r{<h2>(?<pin>\d{4})</h2>.*<a href="https://example.com/login/pin_form\?identity=(?<identity>[^"]+)">#{login_link_text}</a>}.match(email.body.decoded))
pin = m[:pin]
identity = CGI.unescape(m[:identity])
assert_equal identity, users(:uwe).email
fill_in :user_pin, with: pin
click_on 'Logg inn'
open_menu
screenshot :welcome
click_link 'Logg ut'
click_on 'Medlemssider'
assert has_field?('user[identity]', with: users(:uwe).email)
end
end
|
require 'formula'
class Fb303 < Formula
homepage 'http://thrift.apache.org'
# We use a custom verion of fb303, although we may try to submit these changes back.
url 'git://github.com/Asana/thrift.git', :branch => "trunk"
version "2ac809e92e9afaf8b98bc3652a00669d71b137f1"
depends_on 'thrift'
depends_on 'automake'
depends_on 'autoconf'
def install
# fb303 is in a thrift subdirectory.
Dir.chdir "contrib/fb303"
# These were in admin/configure.py. I don't know what they do.
ENV["CPPFLAGS"] = "-DHAVE_NETDB_H=1 -DHAVE_NETINET_IN_H=1 -DHAVE_INTTYPES_H=1 -fpermissive -fPIC"
ENV["PY_PREFIX"] = "#{HOMEBREW_PREFIX}"
ENV["CXX"] = "clang++ -std=c++11 -stdlib=libc++"
system "./bootstrap.sh"
# Language bindings try to install outside of Homebrew's prefix, so
# omit them here. For ruby you can install the gem, and for Python
# you can use pip or easy_install.
system "./configure", "--disable-debug",
"--prefix=#{prefix}",
"--libdir=#{lib}",
"--with-thriftpath=#{HOMEBREW_PREFIX}"
ENV.j1
system "make"
system "make install"
end
end
|
json.notifications do
json.array! @notification_data do |notification_data|
json.call(notification_data, :notification_type, :count, :post_event_id, :user_id)
json.user_email notification_data.post_event.user.email
end
end
|
class Purchase < ActiveRecord::Base
belongs_to :item
after_save :reduce_stock_of_item
def reduce_stock_of_item
self.item.reduce_stock!
end
end
|
# $Id$
# $(c)$
require_relative '../../models/datarepos/repo.rb'
require_relative '../../models/datarepos/seed_url.rb'
module Datarepos
class FindStuff < ActiveJob::Base
attr_reader :agent
class << self
def format_validators
Dir[Rails.root.join('**','validator','*.rb').to_s].each {|f| require f }
base_val = Datarepos::Validator
base_val.constants.select { |c| base_val.const_get(c).is_a?(Class) }
.map{|k| Validator.const_get(k) }
rescue NameError
return []
end
end
delegate :format_validators, to: :class
def perform
SeedUrl.active.each do |seed|
depth = (seed.url_max_depth || 10)
spider(seed.uri, depth)
end
end
def spider(url, depth)
require 'spidr'
Spidr.start_at(url, max_depth: depth) do |spider|
spider.every_url { |url| puts url }
spider.every_page do |page|
format_validators.each do |validator_klass|
break if validate_format(validator_klass, page)
end
end
end
end
private
def validate_format(validator_klass, page)
url = page.uri.to_s
validator = validator_klass.new(page)
validator.execute!
raise RepoError::IncompatibleProcessorError.new unless validator.ok?
# save repo here
Repo.where(initial_uri: url).first_or_create.update!(
name: File.basename(url, Pathname.new(url).extname),
initial_uri: url,
validated_format: validator_klass.name,
last_validated: DateTime.now(),
filesize: page["content-length"].to_i,
columns: validator.validator.instance_variable_get(:@expected_columns),
rows: validator.validator.data.length
) unless validator.try(:saved?)
true
rescue NoMethodError => e
# invalid page
false
rescue RepoError::UnavailableUriError => e
# file was not available
false
rescue RepoError::IncompatibleProcessorError, RuntimeError => e
# file was not compliant w format_validator
false
end
def spider_link(lnk, url, depth)
href = lnk.href
root_href = URI.join(url,href).to_s
spider(root_href, depth - 1)
true
rescue URI::InvalidURIError => e
false
rescue ArgumentError => e
false
end
end
end
|
# frozen_string_literal: true
describe Grape::ExtraValidators::MinimumValue do
module ValidationsSpec
module MinimumValueValidatorSpec
class API < Grape::API
default_format :json
params do
optional :static_number, type: Integer, minimum_value: 10
optional :minimum_value_for_proc_number, type: Integer, allow_blank: false
optional :proc_number, type: Integer, minimum_value: ->(params) { params[:minimum_value_for_proc_number] - 1 }
end
post "/" do
body false
end
end
end
end
def app
ValidationsSpec::MinimumValueValidatorSpec::API
end
let(:params) do
{
static_number: static_number,
minimum_value_for_proc_number: minimum_value_for_proc_number,
proc_number: proc_number,
}.compact
end
let(:static_number) { nil }
let(:minimum_value_for_proc_number) { nil }
let(:proc_number) { nil }
before { post "/", params }
subject { last_response.status }
context "when a configured minimum value is a static value" do
context "when the value is less than the minimum value" do
let(:static_number) { 9 }
it { is_expected.to eq(400) }
end
context "when the value is equal to the minimum value" do
let(:static_number) { 10 }
it { is_expected.to eq(204) }
end
context "when the value is more than the minimum value" do
let(:static_number) { 11 }
it { is_expected.to eq(204) }
end
end
context "when a configured minimum value is a Proc" do
context "the value is less than the minimum value" do
let(:minimum_value_for_proc_number) { 12 }
let(:proc_number) { 10 }
it { is_expected.to eq(400) }
end
context "the value is equal to the minimum value" do
let(:minimum_value_for_proc_number) { 12 }
let(:proc_number) { 11 }
it { is_expected.to eq(204) }
end
context "the value is more than the minimum value" do
let(:minimum_value_for_proc_number) { 12 }
let(:proc_number) { 12 }
it { is_expected.to eq(204) }
end
end
context "when the parameter is nil" do
let(:params) { {} }
it { is_expected.to eq(204) }
end
end
|
# Description
# ---------------
# Twenty-One is a card game consisting of a dealer and a player, where the participants are trying to get as close as possible to 21 without going over.
# Overview:
# - Both participants are initially dealt 2 cards from a 52-card deck.
# - The player takes the first turn, and can "hit" or "stay".
# - If the player busts, he/she loses. If he/she stays, its the dealer's turn.
# - THe dealer must hit until his/her card add up to at least 17.
# - If the dealer busts, the player wins. If both player and dealer stays, then the highest total wins.
# - If both totals are equal, then it's a tie, and nobody wins.
# Nouns --> Dealer, Player, participant, deck, turn, total, card, game
# -----------
# Verbs --> deal, hit, stay, busts, win, tie, add, compare
# -----------
# Participant (Dealer, Player) --> hand
# - hit
# - stay
# - total
# - busted?
# - won?
# - tie?
# Deck
# - deal
# Game
# - start
# - turn
# Dependencies
# ------------
# HAND --> Card
# PARTICIPANT -->
# DEALER --> Participant, Hand
# PLAYER --> Participant, Hand
# DECK --> Card
# CARD -->
# GAME --> Deck, Card, Player, Dealer
class Participant
def intiialize
@hand
@name
end
def hit
end
def stay
end
def total
end
def busted?
end
def won?
end
def tie?
end
end
class Deck
def initialize
# 52-card deck
end
def deal
end
end
class Game
def start
display_welcome_message
loop do
loop do
initial_deal
player_turn
break if player_busted?
dealer_turn
break if dealer_busted?
compare_totals
end
show_result
break unless play_again?
end
display_goodbye_message
end
def take_turn
end
end
Game.new.start |
#!/usr/bin/env ruby
require 'rake'
usage = <<EOS
[usage]
ruby script/02.make_parsed2.rb <idir>
[example]
ruby script/02.make_parsed2.rb Data/2016/20160512/taxdump
[requirement]
1) <idir> should be directory.
2) <idir>/names.dmp should exist.
2) <idir>/nodes.dmp should exist.
EOS
idir = ARGV[0]
(puts usage; exit) if ARGV.size != 1
fin1 = "#{idir}/names.dmp"
fin2 = "#{idir}/nodes.dmp"
(puts usage; exit) unless File.exist?(fin1)
(puts usage; exit) unless File.exist?(fin2)
odir = "#{idir}/MAGRE"; mkdir_p odir unless File.directory?(odir)
fout = open("#{odir}/parsed2.txt", "w")
ranks = {} # ranks["family"]["31"] = 1
id2parent = {}
id2name = {}
id2rank = {}
IO.readlines(fin1).each{ |l|
id, name, type = l.chomp.split(/\t/).values_at(0, 2, 6)
next if type != "scientific name"
#name_ary += [id, name]
id2name[id] = name
}
puts "parsed: name file"
IO.readlines(fin2).each{ |l|
id, parent_id, rank = l.chomp.split(/\t/).values_at(0, 2, 4)
raise if id2parent[id] # overlap check
id2parent[id] = parent_id #if id != "1" # "1" => "1"
id2rank[id] = rank
}
puts "parsed: node file"
id2parent.each_key{ |input|
output = {} # { "kingdom_id" => "2", "kingdom_name" => "Bacteria", ...}
id = input.dup
idx = 0
ids = []
while parent = id2parent[id]
ids << id
break if id == "1" and parent == "1"
id = parent
end
fout.puts [input, ids.map{ |id| [id2name[id], id2rank[id], id]*"|" }*"\t"]*"\t"
}
|
class CreateDispatcherDrivers < ActiveRecord::Migration[6.1]
def change
create_table :join_dispatch_drivers do |t|
t.integer :dispatcher_id
t.integer :driver_id
end
end
end
|
# frozen_string_literal: true
require 'helper'
require 'inci_score/recognizer_rules'
describe InciScore::Recognizer::Rules do
it 'must recognize component by key' do
rule = InciScore::Recognizer::Rules::Key
_(rule.call('ci 61570').to_s).must_equal 'ci 61570 (3)'
end
it 'must return nil for unfound key' do
rule = InciScore::Recognizer::Rules::Key
refute rule.call('watermelon')
end
it 'must recognize component by Levenshtein distance' do
rule = InciScore::Recognizer::Rules::Levenshtein
_(rule.call('agua').to_s).must_equal 'aqua (0)'
end
it 'returns nil if too distant' do
rule = InciScore::Recognizer::Rules::Levenshtein
refute rule.call('watermelon')
end
it 'returns nil for empty ingredient' do
rule = InciScore::Recognizer::Rules::Levenshtein
refute rule.call('')
end
it 'must recognize generic hazard' do
rule = InciScore::Recognizer::Rules::Hazard
_(rule.call('favothicone').to_s).must_equal 'favothicone (4)'
_(rule.call('noent peg-4').to_s).must_equal 'noent peg-4 (3)'
_(rule.call('noent boent glycol').to_s).must_equal 'noent boent glycol (3)'
end
it 'must recognize component by prefix' do
rule = InciScore::Recognizer::Rules::Prefix
_(rule.call('olea europaea oil').to_s).must_equal 'olea europaea (0)'
end
it 'must return nil with no matchings' do
rule = InciScore::Recognizer::Rules::Prefix
refute rule.call('melonwater')
end
it 'must recognize component by tokens' do
rule = InciScore::Recognizer::Rules::Tokens
_(rule.call('f588 capric triglyceride').to_s).must_equal 'c10-18 triglycerides (0)'
_(rule.call('d-limonene').to_s).must_equal 'limonene (2)'
end
it 'must return nil with short matchings' do
rule = InciScore::Recognizer::Rules::Tokens
refute rule.call('imo')
end
it 'must return nil with no matchings' do
rule = InciScore::Recognizer::Rules::Tokens
refute rule.call('watermelon')
end
end
|
require "base64"
require 'jwt'
require 'jwt/json'
require 'httparty'
require 'httmultiparty'
require 'colorize'
module Googlepub
class Auth
def initialize(options = {})
if !options["package"] && !ENV['PACKAGE']
puts "Please provide the package you want to EDIT on (Use option -p or --package for ease): "
package = gets.chomp
package = eval %Q{#{package}}
else
package = options["package"] || ENV['PACKAGE']
end
@package = package
ENV['PACKAGE'] = package
does_accesstoken_exists
if !ENV['ACCESS_TOKEN']
find_key_and_iss
if !options["key"] && !ENV['KEY']
puts "Please provide the key for the Account on Google Developer Console (use option -k or --key for ease): "
@key = gets.chomp
@key = eval %Q{#{@key}}
else
@key = options["key"] || ENV['KEY']
end
ENV['KEY'] = @key
if !options["iss"] && !ENV['ISS']
puts "Please provide the ISS for the account on Google Developer Console (use -i or -iss for ease): "
@iss = gets.chomp
@iss = eval %Q{#{@iss}}
else
@iss = options["iss"] || ENV['ISS']
end
ENV['ISS'] = @iss
if (!@key || !@iss || !@package)
puts "Invalid Arguments!".red
end
self.new_access_token
else
@access_token = ENV['ACCESS_TOKEN']
end
end
def new_access_token
header = {"alg" => "RS256","typ" => "JWT"}
claim_set = {
"iss"=>@iss,
"scope"=> 'https://www.googleapis.com/auth/androidpublisher',
"aud"=>"https://www.googleapis.com/oauth2/v3/token",
"exp" => Time.now.to_i + 3600,
"iat" => Time.now.to_i
}
private_key = @key.to_s
@key = OpenSSL::PKey.read(private_key)
if !@key
puts "Invlaid OPENSLL Key, please check!".red
exit 1
end
jwt = JWT.encode(claim_set, @key, "RS256", header)
if !jwt
puts "Invlaid JWT, please check!".red
exit 1
end
data = {"grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion" => "#{jwt}"}
response = HTTParty.post("https://www.googleapis.com/oauth2/v3/token", :body => data)
if !response.parsed_response["access_token"]
puts "Invlaid or Not generated Access Token, please try again!".red
puts response.parsed_response
exit 1
end
access_token = response.parsed_response["access_token"] #Access Token valid for 60 minutes
ENV['ACCESS_TOKEN'] = access_token
@access_token = access_token
accessfile = File.new("access_token", "w")
accessfile.write(@access_token)
accessfile.close
puts "Access Token: #{@access_token}".green
end
################# A new EDIT ##########################
def edit
puts "Generating Edit for package: #{@package}"
headers = {"Authorization" => "Bearer #{@access_token}"}
edit_response = HTTParty.post("https://www.googleapis.com/androidpublisher/v2/applications/#{@package}/edits", :headers => headers, :body => {}).parsed_response
if !edit_response["id"]
puts "Invlaid Edit, No id returned, please check!".red
p edit_response
exit 1
end
ENV['EDIT_ID'] = edit_response["id"]
@edit_id = edit_response["id"]
puts "Edit ID generated: #{ENV['EDIT_ID']}".green
end
##################### Validate Edit ##########################
def validate_edit
response_validate = HTTParty.post("https://www.googleapis.com/androidpublisher/v2/applications/#{@package}/edits/#{@edit_id}:validate?access_token=#{@access_token}", :body =>{}).parsed_response
if response_validate["id"] == @edit_id
puts "Validated: Good to Go".green
else
puts "Invalid Edit, please check!".red
puts response_validate
exit 1
end
end
###################### Commit the Edit ##########################
def commit_edit
response_commit = HTTParty.post("https://www.googleapis.com/androidpublisher/v2/applications/#{@package}/edits/#{@edit_id}:commit?access_token=#{@access_token}", :body =>{}).parsed_response
if response_commit["id"] == @edit_id
puts "Committed!".green
else
puts "Commit Error! please check!".red
puts response_commit
exit 1
end
end
def find_key_and_iss
keyfile = Dir["keyfile"][0]
if keyfile
file = File.open("#{keyfile}", 'r')
if file.size != 0
@key = eval %Q{"#{file.read}"}
ENV['KEY'] = @key
end
end
issfile = Dir["issfile"][0]
if issfile
file = File.open("#{issfile}", 'r')
if file.size != 0
@iss = eval %Q{"#{file.read}"}
ENV['ISS'] = @iss
end
end
end
def does_accesstoken_exists
accessfile = Dir["access_token"][0]
if accessfile
file = File.open("#{accessfile}", 'r')
if file.size != 0
@access_token = eval %Q{"#{file.read}"}
validate_token_or_generate
end
end
end
def validate_token_or_generate
response_validate = HTTParty.get("https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=#{@access_token}").parsed_response
if response_validate["issued_to"] && response_validate["expires_in"] >=300
ENV['ACCESS_TOKEN'] = @access_token
puts "Using Access Token: #{ENV['ACCESS_TOKEN']}"
else
@access_token = nil
accessfile = Dir["access_token"][0]
if accessfile
File.delete("access_token")
end
end
end
end
end
|
# Encoding: utf-8
# used by ChefSpec for LWRPs
if defined?(ChefSpec)
def create_docker_registry_config(name)
ChefSpec::Matchers::ResourceMatcher.new(:docker_registry_config, :create, name)
end
def remove_docker_registry_config(name)
ChefSpec::Matchers::ResourceMatcher.new(:docker_registry_config, :remove, name)
end
def create_docker_registry_instance(name)
ChefSpec::Matchers::ResourceMatcher.new(:docker_registry_instance, :create, name)
end
def remove_docker_registry_instance(name)
ChefSpec::Matchers::ResourceMatcher.new(:docker_registry_instance, :remove, name)
end
def enable_docker_registry_service(name)
ChefSpec::Matchers::ResourceMatcher.new(:docker_registry_service, :enable, name)
end
def disable_docker_registry_service(name)
ChefSpec::Matchers::ResourceMatcher.new(:docker_registry_service, :disable, name)
end
def start_docker_registry_service(name)
ChefSpec::Matchers::ResourceMatcher.new(:docker_registry_service, :start, name)
end
def stop_docker_registry_service(name)
ChefSpec::Matchers::ResourceMatcher.new(:docker_registry_service, :stop, name)
end
def restart_docker_registry_service(name)
ChefSpec::Matchers::ResourceMatcher.new(:docker_registry_service, :restart, name)
end
end
|
require 'forwardable'
module TextToNoise
module Logging
extend Forwardable
def_delegators :logger, :warn, :debug, :error, :info
def logger() TextToNoise.logger; end
end
end
|
Rails.application.routes.draw do
resources :businesses
resources :expenses
devise_for :users
root 'home#index'
end
|
#!/usr/bin/ruby
# dump mysql data to sqlite file:
# https://raw.github.com/gist/943776/dd87f4088f6d5ec7563478f7a28a37ba02cf26e2/mysql2sqlite.sh
# chmod +x mysql2sqlite
# ./mysql2sqlite --no-data -uscottr -pbtc0mt1e --lock-tables=off scottraymond_mephisto | sqlite3 old-srnet-data.sqlite
require 'rubygems'
require 'mysql'
require 'time'
con = Mysql.new('127.0.0.1', 'root', '', 'old-srnet')
result = con.query("select * from contents where type='Article'")
result.each_hash do |row|
print '.'
created = Time.parse(row['created_at'])
File.open("_posts/#{created.strftime("%Y-%m-%d")}-#{row['permalink']}.textile", 'w') do |f|
f.write("---\n")
f.write("layout: post\n")
f.write("title: #{row['title']}\n")
f.write("created: #{created.iso8601}\n")
f.write("---\n")
f.write("\n")
f.write(row['body'])
end
end
con.close |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.