text stringlengths 10 2.61M |
|---|
require 'rails_helper'
RSpec.describe "OpinionPages", type: :request do
subject { page }
let(:content) { FactoryGirl.create(:content) }
describe "opinion creation" do
before { visit @content }
describe "with invalid information" do
it "should not create a opinion" do
expect { click_button "Отправить"}.not_to change(Opinion, :count)
end
describe "error messages" do
before { click_button "Отправить" }
it { should have_content('error') }
end
end
describe "with valid information" do
before do
fill_in 'comment', with: "Lorem ipsum"
fill_in 'value', with: "4"
end
it "should create a micropost" do
expect { click_button "Отправить"}.to change(Opinon, :count).by(1)
end
end
end
end
|
class LineItemsController < ApplicationController
# Setup @line_item.
before_action :set_line_item, only: [:update, :destroy]
# POST /line_items
def create
if params[:variant_id]
# The request includes the `:variant_id`.
@variant = Variant.find_by(id: params[:variant_id])
if @variant
# The variant exsists.
# Initalize the cart object to perform validations.
cart_product = AddProductToCart.new(@variant, params[:quantity], current_cart)
# Perform validations against the cart product.
if cart_product.out_of_stock?
# Out of stock.
flash.now[:error] = t(".out_of_stock")
elsif cart_product.quantity_over_stock?
# The quantity exceeds the amount in stock.
flash.now[:error] = t(".quantity_over_stock")
elsif cart_product.quantity_over_limit?
# The quantity exceeds the set limit for this variant.
flash.now[:error] = "You can only purchase #{@variant.limit} per order."
elsif cart_product.unavailable?
# The active flag has been set to false on this variant or the stock
# has run out.
flash.now[:error] = t(".unavailable")
else
# Add the variant to cart and return the new line_item.
@line_item = cart_product.add
# Reset previously selected shipping rate.
ResetOrderShipmentRates.call(current_cart)
# Added to cart.
flash.now[:success] = t(".added_to_cart")
end
else
# Variant not found.
flash.now[:error] = t(".not_found")
end
else
# No variant present.
flash.now[:error] = t(".no_option_selected")
end
end
# PATCH /line_items/:id
def update
# Update @line_item quantity.
if @line_item.update_attributes(line_item_params)
flash.now[:success] = t(".quantity_updated")
end
end
# DELETE /line_items/:id
def destroy
# Remove @line_item from cart.
@line_item.destroy
flash.now[:success] = t(".removed_from_cart")
end
private
# Setup @line_item.
def set_line_item
@line_item = current_cart.line_items.find_by(id: params[:id])
end
# Strong params.
def line_item_params
params.require(:line_item).permit(:quantity)
end
end
|
# describe "anagrams" do
# it "should be defined" do
# lambda { combine_anagrams([]) }.should_not raise_error(::NoMethodError)
# end
# it "should return an Array" do
# combine_anagrams([]).class.should == Array
# end
# end
def combine_anagrams(words)
# <YOUR CODE HERE>
hash = Hash.new
words.each do |w|
t = w.chars.sort { |a, b| a.casecmp(b) } .join
if hash.has_key? t
hash[t] << w
else
hash[t] = w
end
end
res = []
hash.keys.each do |l|
res << hash[l]
end
return res
end
w = ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream']
puts combine_anagrams w
|
require 'sinatra'
module Putit
module Integration
class IntegrationBase
class << self
attr_reader :endpoint
end
def self.on_webhook(&handler)
@handler = handler
end
def self.listen_for_webhook_on_url(endpoint)
@endpoint = endpoint
end
def self.handler(data)
@handler.call(data)
end
def self.call(env)
[200, { 'Content-Type' => 'text/plain' }, [@handler.call(env['rack.input'].read)]]
end
end
end
end
|
require 'dm-core'
require 'dm-migrations'
require 'dm-constraints'
require 'dm-validations'
require 'dm-timestamps'
require 'dm-transactions'
require 'dm-types'
require 'dm-serializer/to_json'
require 'dm-zone-types'
module Testor
def self.next_job(previous_jobs, status)
Persistence::Job.available(previous_jobs, status).first
end
def self.register_commit(library_name, revision)
Persistence::Job.register_commit(library_name, revision)
end
def self.accept_job(id, status)
job = Persistence::Job.get(id)
job.accept(status)
end
def self.report_job(user, report)
job = Persistence::Job.get(report[:job_id])
job.create_report(user, report)
end
module Persistence
class IdentityMap
def initialize(app)
@app = app
end
def call(env)
DataMapper.repository { @app.call(env) }
end
end
def self.setup(log_stream, log_level)
setup_logger(log_stream, log_level) if log_stream
convention = DataMapper::NamingConventions::Resource::UnderscoredAndPluralizedWithoutModule
adapter = DataMapper::setup(:default, Config['database'])
adapter.resource_naming_convention = convention
DataMapper.finalize
adapter
end
def self.create(log_stream, log_level)
setup(log_stream, log_level)
DataMapper.auto_migrate!
end
def self.setup_logger(stream, level)
DataMapper::Logger.new(log_stream(stream), level)
end
def self.log_stream(stream)
stream == 'stdout' ? $stdout : stream
end
class User
include DataMapper::Resource
property :login, String, :key => true
property :token, String, :default => lambda { |_, _|
while token = Digest::SHA1.hexdigest(rand(36**8).to_s(36))[4..20]
return token if first(:token => token).nil?
end
}
property :created_at, ZonedTime
has n, :reports
end
class Library
include DataMapper::Resource
property :id, Serial
property :name, String, :required => true
property :url, URI, :required => true
property :revision, String, :required => true
has n, :platforms, :through => Resource
has n, :adapters, :through => Resource
end
class Platform
include DataMapper::Resource
property :id, Serial
property :name, String, :required => true
has n, :libraries, :through => Resource
has n, :adapters, :through => :libraries
end
class Adapter
include DataMapper::Resource
property :id, Serial
property :name, String, :required => true
has n, :platforms, :through => Resource
has n, :libraries, :through => Resource
end
class Job
include DataMapper::Resource
MODIFIED = 'modified'
PROCESSING = 'processing'
FAIL = 'fail'
PASS = 'pass'
SKIPPED = 'skipped'
property :id, Serial
property :status, String, :required => true, :set => [MODIFIED, PROCESSING, FAIL, PASS, SKIPPED]
belongs_to :platform
belongs_to :adapter
belongs_to :library
has n, :reports
def self.available(previous_jobs, status)
matching_status = if status.empty?
all(:status => MODIFIED) | all(:status => SKIPPED)
else
all(:status => status)
end
all(:id.not => previous_jobs) & matching_status
end
def self.register_commit(library_name, revision)
transaction do
library = Library.first(:name => library_name)
library.update(:revision => revision)
all(:library => library).each do |job|
job.update_status(MODIFIED)
end
end
end
def create_report(user, report_attributes)
transaction do
unless skip_report?(report_attributes)
report = reports.create(report_attributes.merge(:user => user))
end
update_status(report_attributes['status'])
end
end
def accept(status)
allowed = status.empty? ? (modified? || skipped?) : true
allowed ? update(:status => PROCESSING) : false
end
def update_status(status)
return false if modified?
update(:status => status)
end
def modified?
self.status == MODIFIED
end
def skipped?
self.status == SKIPPED
end
def skip_report?(attributes)
attributes['status'] == SKIPPED && previous_status == SKIPPED
end
def previous_status
report = reports.last(:order => [:created_at.asc])
report ? report.status : FAIL
end
def library_name
library.name
end
def revision
library.revision
end
def platform_name
platform.name
end
def adapter_name
adapter.name
end
end
class Report
include DataMapper::Resource
property :id, Serial
property :status, String, :required => true, :set => [Job::PASS, Job::FAIL, Job::SKIPPED]
property :revision, String, :required => true
property :output, Text, :required => true, :length => 2**24
property :duration, Integer, :required => true
property :created_at, ZonedTime
belongs_to :user
belongs_to :job
def library_name
job.library_name
end
def platform_name
job.platform_name
end
def adapter_name
job.adapter_name
end
end
end # module Persistence
end # module Testor
|
# frozen_string_literal: true
require "spec_helper"
RSpec.describe BigintCustomIdIntRange do
let(:connection) { described_class.connection }
let(:schema_cache) { connection.schema_cache }
let(:table_name) { described_class.table_name }
describe ".primary_key" do
subject { described_class.primary_key }
it { is_expected.to eq("some_id") }
end
describe ".create" do
let(:some_int) { 1 }
let(:some_other_int) { 9 }
subject do
described_class.create!(
some_int: some_int,
some_other_int: some_other_int,
)
end
context "when partition key in range" do
its(:id) { is_expected.to be_a(Integer) }
its(:some_int) { is_expected.to eq(some_int) }
its(:some_other_int) { is_expected.to eq(some_other_int) }
end
context "when partition key outside range" do
let(:some_int) { 20 }
let(:some_other_int) { 20 }
it "raises error" do
expect { subject }.to raise_error(ActiveRecord::StatementInvalid, /PG::CheckViolation/)
end
end
end
describe ".partitions" do
subject { described_class.partitions }
context "when query successful" do
it { is_expected.to contain_exactly("#{table_name}_a", "#{table_name}_b") }
end
context "when an error occurs" do
before { allow(PgParty.cache).to receive(:fetch_partitions).and_raise("boom") }
it { is_expected.to eq([]) }
end
end
describe ".create_partition" do
let(:start_range) { [20, 20] }
let(:end_range) { [30, 30] }
let(:child_table_name) { "#{table_name}_c" }
subject(:create_partition) do
described_class.create_partition(
start_range: start_range,
end_range: end_range,
name: child_table_name
)
end
subject(:partitions) { described_class.partitions }
subject(:child_table_exists) { schema_cache.data_source_exists?(child_table_name) }
before do
schema_cache.clear!
described_class.partitions
end
after { connection.drop_table(child_table_name) if child_table_exists }
context "when ranges do not overlap" do
it "returns table name and adds it to partition list" do
expect(create_partition).to eq(child_table_name)
expect(partitions).to contain_exactly(
"#{table_name}_a",
"#{table_name}_b",
"#{table_name}_c"
)
end
end
context "when name not provided" do
let(:child_table_name) { create_partition }
subject(:create_partition) do
described_class.create_partition(
start_range: start_range,
end_range: end_range,
)
end
it "returns table name and adds it to partition list" do
expect(create_partition).to match(/^#{table_name}_\w{7}$/)
expect(partitions).to contain_exactly(
"#{table_name}_a",
"#{table_name}_b",
child_table_name,
)
end
end
context "when ranges overlap" do
let(:start_range) { [19, 19] }
it "raises error and cleans up intermediate table" do
expect { create_partition }.to raise_error(ActiveRecord::StatementInvalid, /PG::InvalidObjectDefinition/)
expect(child_table_exists).to eq(false)
end
end
end
describe ".in_partition" do
let(:child_table_name) { "#{table_name}_a" }
subject { described_class.in_partition(child_table_name) }
its(:table_name) { is_expected.to eq(child_table_name) }
its(:name) { is_expected.to eq(described_class.name) }
its(:new) { is_expected.to be_an_instance_of(described_class) }
its(:allocate) { is_expected.to be_an_instance_of(described_class) }
describe "query methods" do
let!(:record_one) { described_class.create!(some_int: 0, some_other_int: 0) }
let!(:record_two) { described_class.create!(some_int: 9, some_other_int: 9) }
let!(:record_three) { described_class.create!(some_int: 19, some_other_int: 19) }
describe ".all" do
subject { described_class.in_partition(child_table_name).all }
it { is_expected.to contain_exactly(record_one, record_two) }
end
describe ".where" do
subject { described_class.in_partition(child_table_name).where(some_id: record_one.some_id) }
it { is_expected.to contain_exactly(record_one) }
end
end
end
describe ".partition_key_in" do
let(:start_range) { [0, 0] }
let(:end_range) { [10, 10] }
let!(:record_one) { described_class.create!(some_int: 0, some_other_int: 0) }
let!(:record_two) { described_class.create!(some_int: 9, some_other_int: 9) }
let!(:record_three) { described_class.create!(some_int: 19, some_other_int: 19) }
subject { described_class.partition_key_in(start_range, end_range) }
context "when spanning a single partition" do
it { is_expected.to contain_exactly(record_one, record_two) }
end
context "when spanning multiple partitions" do
let(:end_range) { [20, 20] }
it { is_expected.to contain_exactly(record_one, record_two, record_three) }
end
context "when chaining methods" do
subject { described_class.partition_key_in(start_range, end_range).where(some_int: 0) }
it { is_expected.to contain_exactly(record_one) }
end
context "when incorrect number of values provided" do
let(:start_range) { 0 }
it "raises error" do
expect { subject }.to raise_error(/does not match the number of partition key columns/)
end
end
end
describe ".partition_key_eq" do
let(:partition_key) { [0, 0] }
let!(:record_one) { described_class.create!(some_int: 0, some_other_int: 0) }
let!(:record_two) { described_class.create!(some_int: 10, some_other_int: 10) }
subject { described_class.partition_key_eq(partition_key) }
context "when partition key in first partition" do
it { is_expected.to contain_exactly(record_one) }
end
context "when partition key in second partition" do
let(:partition_key) { [10, 10] }
it { is_expected.to contain_exactly(record_two) }
end
context "when chaining methods" do
subject do
described_class
.in_partition("#{table_name}_b")
.unscoped
.partition_key_eq(partition_key)
end
it { is_expected.to be_empty }
end
context "when table is aliased" do
subject do
described_class
.select("*")
.from(described_class.arel_table.alias)
.partition_key_eq(partition_key)
end
it { is_expected.to contain_exactly(record_one) }
end
context "when table alias not resolvable" do
subject do
described_class
.select("*")
.from("garbage")
.partition_key_eq(partition_key)
end
it { expect { subject }.to raise_error("could not find arel table in current scope") }
end
end
end
|
require 'hollywood'
class Actor
def in_a_movie?
false
end
def learnt_lines?
@learn_lines || false
end
def learn_lines character
@learn_lines = true
@character = character
end
def deposit fee
@money_in_the_bank = fee
end
attr_reader :character, :money_in_the_bank
end
class Agent
include Hollywood
def take_10_percent
callback :you_got_the_part, :ninty_percent, :deckard
end
end
class Director
def send_contract_to agent
agent.take_10_percent
end
end
RSpec::Matchers.define :have_learnt_its_lines do
match { |actor| actor.learnt_lines? }
end |
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'
require 'capybara/rails'
require 'shoulda/matchers'
require 'helpers/admin_helper'
require 'factories'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
# Use capybara DSL
config.include Capybara::DSL
#include manually made helpers
config.include AdminHelper
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
end
|
module SportsDataApi
module Mlb
class Games
include Enumerable
attr_reader :games, :year
def initialize(xml)
xml = xml.first if xml.is_a? Nokogiri::XML::NodeSet
@year = xml['season_year']
@games = []
if xml.is_a? Nokogiri::XML::Element
xml.xpath('event').each do |event|
@games << Game.new(year: @year, xml: event)
end
end
end
def each &block
@games.each do |game|
if block_given?
block.call game
else
yield game
end
end
end
end
end
end
|
# # Create a program that asks the user for their favorite 5 foods. Then display those foods as an array, using the “p” keyword.
# foods = []
# puts "What is the name of your five favorite foods?"
# 2.times do |i|
# puts "Number #{i + 1} is:"
# answer = gets.chomp
# foods << answer
# i += 1
# end
# #p foods
# #Now, instead of printing out the array, output 5 separate lines of each food, with the prefix, “I love”. For example
# # foods.each do |food|
# # puts "I love #{food}"
# # end
# #Finally, change your program so that when the list is printed in the terminal, each food is prefaced with a number, beginning with 1 and going up to 5, for example:
# counter = 0
# foods.each do |food|
# puts "#{counter + 1}. #{food}"
# counter += 1
# end
#Problem 2: Create and define a variable ‘count = 0’. Using a loop and the ‘+=’ operator, output the following:
# counter = 0
# 11.times do
# puts "#{counter}"
# counter += 1
# end
# results = 5
# unless results == true
# puts "Hi"
# else
# puts "Wrong"
# end
#Question 2, part D: Look at the conditional below. What value(s) can the variable ‘result’ be for it to output “HELLO!” What values will it not output? Experiment in Sublime:
# result = 5
# unless result
# puts "HELLO!"
# end
#Question 2, part E: If Sam can cook more than 10 recipes and Sally speaks more than 5 languages, they should date. If Sam can make crepes or Sally can speak French, they should marry.
# sam_recipes = ["eggs", "waffles", "hashbrowns", "bagels", "fries", "burgers", "pasta", "bread", "breadsticks", "breadcrumbs", "pizza"]
# sally_languages = ["English", "American", "Spanish", "French", "Portugese", "Albanian"]
# if sam_recipes.length > 10 && sally_languages.length > 5
# puts "Sam and Sally should date."
# elsif sam_recipes.include?("crepes") || sally_languages.include?("French")
# puts "Sam and Sally should marry."
# end
#Question 3, HASHES! Create a banking program that asks the user 5 times to enter a first name, last name, and email. This information should be stored as an array of hashes.
# 2.times do |i|
# puts "Number #{i + 1} is:"
# answer = gets.chomp
# foods << answer
# i += 1
# end
# customer_info = []
# 2.times do
# customer = {}
# puts "What is your first name?"
# customer["first_name"] = gets.chomp
# puts "What is your last name?"
# customer["last_name"] = gets.chomp
# puts "What is your email?"
# customer["email"] = gets.chomp
# customer["account_number"] = rand(10 ** 10)
# customer_info << customer
# end
# customer_info.each do |customer|
# puts "FIRST NAME: #{customer["first_name"]}"
# puts "LAST NAME: #{customer["last_name"]}"
# puts "EMAIL: #{customer["email"]}"
# puts "ACCT #: #{customer["account_number"]}"
# end
#Question 4, Final Review. Create a program that puts your class into groups! Have the program request the user to enter each student’s names. Assume the classroom has an even number of students, so there are only groups of two. For example, you can have the program output groups like so:
puts "Please enter the name of every student."
students = []
4.times do |counter|
puts "Student number #{counter + 1}'s name is:"
student = gets.chomp
students << student
end
# p students
2.times do |counter|
puts "Group: #{students.sample(2)}"
end
|
module Offers
module Searchable
extend ActiveSupport::Concern
included do
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
settings index: { number_of_shards: 1 } do
mappings dynamic: false do
indexes :id, type: :long
indexes :title, type: :text
indexes :description, type: :text
indexes :price, type: :long
indexes :user_id, type: :long
end
end
def as_indexed_json(options = {})
self.as_json(only: [:id, :title, :description, :price, :user_id])
end
end
end
end
|
require 'dalli'
module Twigg
module Cache
class Client
def initialize
options = {
compress: true,
expires_in: Config.cache.expiry,
value_max_bytes: Config.cache.value_max_bytes,
namespace: Config.cache.namespace,
}.delete_if { |key, value| value.nil? }
@client = Dalli::Client.new("#{Config.cache.host}:#{Config.cache.port}",
options)
end
def get(key)
@client.get(key)
rescue Dalli::RingError
# degrade gracefully
end
def set(key, value)
@client.set(key, value)
rescue Dalli::RingError
# degrade gracefully
end
end
end
end
|
# == Schema Information
#
# Table name: reports
#
# id :bigint(8) not null, primary key
# business_id :integer
# date :date
# sales :money
# expenses :money
# comments :text
# created_at :datetime not null
# updated_at :datetime not null
#
class Report < ApplicationRecord
belongs_to :business, :optional => true
end
|
module Merb::Cache::ControllerInstanceMethods
# Mixed in Merb::Controller. Provides methods related to fragment caching
# Checks whether a cache entry exists
#
# ==== Parameter
# options<String,Hash>:: The options that will be passed to #key_for
#
# ==== Returns
# true if the cache entry exists, false otherwise
#
# ==== Example
# cached_action?("my_key")
def cached?(options)
key = Merb::Controller._cache.key_for(options, controller_name)
Merb::Controller._cache.store.cached?(key)
end
# ==== Example
# In your view:
# <%- cache("my_key") do -%>
# <%= partial :test, :collection => @test %>
# <%- end -%>
def cache(options, from_now = nil, &block)
key = Merb::Controller._cache.key_for(options, controller_name)
Merb::Controller._cache.store.cache(self, key, from_now, &block)
end
# Fetch data from cache
#
# ==== Parameter
# options<String,Hash>:: The options that will be passed to #key_for
#
# ==== Returns
# data<Object,NilClass>::
# nil is returned if the cache entry is not found
#
# ==== Example
# if cache_data = cache_get("my_key")
# @var1, @var2 = *cache_data
# else
# @var1 = MyModel.big_query1
# @var2 = MyModel.big_query2
# cache_set("my_key", nil, [@var1, @var2])
# end
def cache_get(options)
key = Merb::Controller._cache.key_for(options, controller_name)
Merb::Controller._cache.store.cache_get(key)
end
# Store data to cache
#
# ==== Parameter
# options<String,Hash>:: The options that will be passed to #key_for
# object<Object>:: The object(s) to put in cache
# from_now<~minutes>::
# The number of minutes (from now) the cache should persist
#
# ==== Returns
# data<Object,NilClass>::
# nil is returned if the cache entry is not found
#
# ==== Example
# if cache_data = cache_get("my_key")
# @var1, @var2 = *cache_data
# else
# @var1 = MyModel.big_query1
# @var2 = MyModel.big_query2
# cache_set("my_key", nil, [@var1, @var2])
# end
def cache_set(options, object, from_now = nil)
key = Merb::Controller._cache.key_for(options, controller_name)
Merb::Controller._cache.store.cache_set(key, object, from_now)
end
# Expires the entry identified by the key computed after the parameters
#
# ==== Parameter
# options<String,Hash>:: The options that will be passed to #key_for
#
# ==== Examples
# expire("my_key")
# expire(:key => "my_", :match => true)
# expire(:key => "my_key", :params => [session[:me], params[:ref]])
def expire(options)
Merb::Controller._cache.expire_key_for(options, controller_name) do |key, match|
if match
Merb::Controller._cache.store.expire_match(key)
else
Merb::Controller._cache.store.expire(key)
end
end
true
end
end
|
class RenameColumnImage < ActiveRecord::Migration[5.2]
def change
rename_column :categories, :image, :image_url
end
end
|
class Attribution::Report
attr_accessor :portfolio, :start_date, :end_date, :securities,
:cumulative_security_performances, :cumulative_portfolio_performance, :cumulative_security_contributions,
:companies
def initialize( opts={} )
@portfolio = opts[:portfolio]
@start_date = opts[:start_date]
@end_date = opts[:end_date]
@companies = Hash.new { |h, k| h[k] = {} }
end
def calculate
ensure_inputs_are_set!
ensure_days_are_completely_downloaded
ensure_security_days_are_completely_calculated
calculate_cumulative_security_performances
calculate_cumulative_portfolio_performance
calculate_cumulative_security_contributions
@results = { :security => security_stats }
end
def ensure_inputs_are_set!
[:start_date, :end_date, :portfolio].each do |attrib|
if self.send(attrib).blank?
raise "#{attrib} was not set! Cannot calculate."
end
end
end
def ensure_security_days_are_completely_calculated
days.sort_by(&:date).each do |d|
if d.security_days.empty?
# ActiveRecord::Base.transaction do
calculator = Attribution::SecurityPerformanceCalculator.new :day => d
calculator.calculate
# end
end
end
end
def calculate_cumulative_security_performances
self.securities = Hash.new { |h, k| h[k] = [] }
days.sort_by(&:date).each do |d|
d.security_days.each do |sd|
securities[sd.company_id] << sd
end
end
@cumulative_security_performances = {}
securities.each do |company_id, security_days|
company = Attribution::Company.find( company_id )
puts "#{company.tag.ljust(10)} | #{security_days.inspect}"
cumulative_perf = geo_link security_days.map(&:performance)
@companies[company][:performance] = cumulative_perf
@cumulative_security_performances[company.tag] = cumulative_perf
end
@cumulative_security_performances
end
def calculate_cumulative_security_contributions
@cumulative_security_contributions = {}
security_days_by_company = Hash.new { |h, k| h[k] = [] }
contribution_days_by_company = Hash.new { |h, k| h[k] = [] }
days.sort_by(&:date).each do |d|
d.security_days.each do |sd|
security_days_by_company[sd.company_id] << sd
end
end
security_days_by_company.each do |company_id, security_days|
company = Attribution::Company.find( company_id )
contrib = security_contribution( security_days )
@companies[company][:contribution] = contrib
@cumulative_security_contributions[company.tag] = contrib
end
end
def calculate_cumulative_portfolio_performance
range = (@start_date..@end_date).select(&:trading_day?)
daily_performances = range.to_a.map do |d|
puts "PORT PERF: #{d} | #{@portfolio.day( d ).portfolio_day}"
@portfolio.day( d ).portfolio_day.performance
end
@cumulative_portfolio_performance = geo_link daily_performances
end
def days
@portfolio.days.where( :date => @start_date..@end_date )
end
def ensure_days_are_completely_downloaded
trading_days = (@start_date.prev_trading_day..@end_date).select(&:trading_day?)
trading_days.each do |date|
ensure_day_is_downloaded( date )
end
trading_days[1..-1].each do |date|
ensure_day_is_computed( date )
end
end
def ensure_day_is_downloaded( date )
day = @portfolio.days.where(:date => date).first_or_create
raise "no portfolio day for #{date}" if day.nil?
day.download unless day.downloaded?
end
def ensure_day_is_computed( date )
day = @portfolio.days.where(:date => date).first
raise "no portfolio day for #{date}" if day.nil?
day.compute_portfolio_day unless day.completed?
end
def security_stats
hsh = Hash.new { |h, k| h[k] = {} }
securities.inject(hsh) do |stats, cusip_and_days|
cusip = cusip_and_days.first
sec_days = cusip_and_days.last
stats[cusip][:performance] = security_performance( sec_days )
stats[cusip][:contribution] = security_contribution( sec_days )
stats
end
end
def security_return_stats
hsh = Hash.new { |h, k| h[k] = {} }
securities.inject(hsh) do |stats, cusip_and_days|
cusip = cusip_and_days.first
ticker = Attribution::Holding.where( :cusip => cusip ).first.ticker
sec_days = cusip_and_days.last
stats[ticker][:performance] = security_performance( sec_days )
stats
end
end
def portfolio_days
days.inject({}) do |hsh, day|
hsh[day.date] = day.portfolio_day
hsh
end
end
def days
@portfolio.days.where( :date => [@start_date..@end_date] )
end
def pv_multiplier( security_day )
future_days = (@start_date..@end_date).select(&:trading_day?).to_a.select { |d| d > security_day.date }
future_performance_days = future_days.map{ |d| portfolio_days[d].performance }
geo_link future_performance_days
end
def security_performance( security_days )
geo_link( security_days.map { |sd| sd.performance } )
end
def security_contribution( security_days )
sum( security_days.map { |sd| contribution_addend( sd ) } )
end
def contribution_addend( security_day )
(security_day.contribution || 0) * pv_multiplier( security_day )
end
def security_results
@results[:security]
end
def audit(ticker=nil)
if ticker.nil?
audit_portfolio
else
audit_security( ticker )
end
end
def audit_security( tag )
tag_holdings = days.map do |d|
d.holdings.find { |h| h.company.tag.upcase == tag.upcase }
end.compact
tag_holdings.each do |h|
h.audit
end
end
def audit_portfolio
cumulative_security_performances.each do |company_tag, perf|
puts "#{company_tag.ljust(10)} | #{percentagize( perf ).round(4)}"
end
end
def print_results
tickers = @results[:security].keys.inject( {} ) do |hsh, cusip|
ticker = Attribution::Holding.where( :cusip => cusip ).first.ticker
hsh[cusip] = ticker
hsh
end
puts "ATTRIBUTION REPORT FOR #{portfolio.name}"
puts "Start date: #{start_date}"
puts "End date: #{end_date}"
puts "TOTAL RETURN: #{sprintf('%.5f', percentagize( cumulative_portfolio_return ))}"
puts "======================================"
puts "Ticker | Return | Contribution"
@results[:security].each do |cusip, stats|
ticker = tickers[cusip]
perf = stats[:performance]
contrib = stats[:contribution]
puts "#{(ticker || "(na)").ljust(6)} | #{sprintf( '%.5f', percentagize(perf)).rjust(8)} | #{sprintf( '%.5f', contrib*100).rjust(8)}"
end
puts "value of cumulative_portfolio_return is: #{'%.5f' % percentagize(cumulative_portfolio_return)}"
summed_contribs = @results[:security].values.inject( BigDecimal("0.0") ) { |s, x| s += x[:contribution] }
puts "value of summed_contribs is: #{'%.5f' % summed_contribs}"
end
# def cumulative_portfolio_return
# range = (@start_date..@end_date)
# geo_link range.to_a.map { |d| @portfolio.days.where( :date => d ).first.portfolio_day.performance }
# end
#
# NOTE: this assumes it takes depercentagized numbers!
def geo_link( nums )
nums.compact.inject( BigDecimal("1.0") ) { |product, factor| product *= factor }
end
# "normalize" with respect to what is right mathematically
# eg., depercentagize("5") => 1.05
def depercentagize( num )
BigDecimal(num.to_s) / 100 + 1
end
# 1.05 => 5
def percentagize( num )
(BigDecimal(num.to_s) - 1.0)*100
end
def sum( nums )
nums.inject( BigDecimal("0.0") ) { |sum, addend| sum += addend }
end
def lookup_security_days( tag )
c = Attribution::Company.find_by_tag( tag )
return nil unless c
c.security_days.where( :day_id => days.map(&:id) )
end
end
|
module ApplicationHelper
def bootstrap_class_for flash_type
case flash_type
when :success
"alert-success"
when :error
"alert-error"
when :alert
"alert-block"
when :notice
"alert-info"
else
flash_type.to_s
end
end
def resource_name
devise_mapping.name
end
def resource_class
devise_mapping.to
end
def resource_name
:user
end
def resource
@resource ||= User.new
end
def devise_mapping
@devise_mapping ||= Devise.mappings[:user]
end
def flash_class(level)
case level
when :notice then
"alert alert-info"
when :success then
"alert alert-success"
when :error then
"alert alert-error"
when :alert then
"alert alert-error"
end
end
end
|
class Node < ActiveRecord::Base
# belongs_to :parent, :class_name => Node
belongs_to :left, :class_name => Node, foreign_key: true
belongs_to :right, :class_name => Node, foreign_key: true
def insert(other)
newbie = Node.create(:value => other)
insert_node(newbie)
end
def insert_node(other)
if other.value < self.value
if left
left.insert_node(other)
else
self.left = other
end
else
if right
right.insert_node(node)
else
self.right = other
end
end
end
def count
total = 1
total += left.count if left
total += right.count if right
return total
end
def min
if left
left.min
else
self.value
end
end
def max
if right
right.max
else
self.value
end
end
end
# if you don't like your problem, create another problem
# identifying the problem at hand, is it two, three or even four problems and then addressing them
|
# encoding: UTF-8
class Report < ActiveRecord::Base
# associations
belongs_to :project
belongs_to :service
# validations
# validates :comment, :date, :duration, :project_id, :service_id, :format => {:with => /^[^<>%&$]*$/}
validates :date, :presence => true
validates :duration, :presence => true
validates :project_id, :presence => true
validates :service_id, :presence => true
# CSV-Download
require 'csv'
include ActionView::Helpers::NumberHelper
def self.download_csv(options = {})
headline = [I18n.t("activerecord.attributes.report.date"),
I18n.t("activerecord.models.customer"),
I18n.t("activerecord.models.project"),
I18n.t("activerecord.models.service"),
I18n.t("labels.roles.timetracker"),
I18n.t("activerecord.attributes.report.duration"),
I18n.t("labels.universe.comment")]
CSV.generate(:col_sep => ";") do |csv|
csv << headline
all.each do |report|
user = report.project.customer.user
user = user.firstname + " " + user.lastname
##
data = [
report.date,
report.project.customer.name,
report.project.name,
report.service.name,
user,
report.duration.to_s.gsub(".", ","),
report.comment]
# csv << report.attributes.values_at(*column_names)
csv << data
end
end
end
#TODO in helper
# Returns the wage in currency format.
def get_wage
return number_to_currency(self.wage)
end
#TODO in helper
# Returns the wage in readable format.
def get_duration
return "#{self.duration.to_s.sub!('.', ',')} #{I18n.t("labels.datetime.hour_short")}"
end
# Calculates and returns the income (wage + duration) of the current Report.
# Readable can be set to false if it is necessary to calculate with the result.
# readable false => returns number instead of a string.
def get_income(readable = true)
income = self.wage * self.duration
if readable
return number_to_currency(self.wage * self.duration)
else
return income
end
end
# search
def self.search(search, projects_user, current_user)
if projects_user.present?
result = Report.where(:project_id => projects_user.project.id)
else
services = Service.where("user_id = ?", current_user.id)
result = Report.where(:service_id => services)
end
# raise
if search
if search["date_from"].present?
result = result.where("date >= ?", search["date_from"].to_date)
end
if search["date_to"].present?
result = result.where("date <= ?", search["date_to"].to_date)
end
if search["customer"].present?
# you get the customer of a report only with the project
projects_of_customer = Project.where('customer_id = ?', search["customer"])
result = result.where(:project_id => projects_of_customer)
end
if search["project"].present?
result = result.where('project_id = ?', search["project"])
end
# archived, will return nil if 'all' is selected.
if search["archived"] == 'false'
result = result.where('archived = ?', false)
end
if search["archived"] == 'true'
result = result.where('archived = ?', true)
end
end
result.order("date DESC")
end
# statistic
def self.showstats(month, projects_user, current_user)
if projects_user.present?
result = Report.where(:project_id => projects_user.project.id, :date => month)
else
services = Service.where("user_id = ?", current_user.id)
result = Report.where(:service_id => services, :date => month)
end
end
end
|
require 'rails_helper'
describe Nib do
it { should have_valid(:nib_size).when('medium') }
it { should have_valid(:nib_type).when('oblique') }
it { should_not have_valid(:nib_type).when(nil, '') }
end
|
class TeslaCommand
include ActionView::Helpers::DateHelper
TEMP_MIN = 59
TEMP_MAX = 82
def self.command(cmd, opt=nil, quick=false)
new.command(cmd, opt, quick)
end
def self.quick_command(cmd, opt=nil)
return "Currently forbidden" if DataStorage[:tesla_forbidden]
TeslaCommandWorker.perform_async(cmd.to_s, opt&.to_s)
command(cmd, opt, true)
end
def address_book
@address_book ||= User.admin.first.address_book
end
def command(original_cmd, original_opt=nil, quick=false)
if Rails.env.development?
ActionCable.server.broadcast(:tesla_channel, stubbed_data)
return "Stubbed data"
end
ActionCable.server.broadcast(:tesla_channel, { loading: true })
car = Tesla.new unless quick
cmd = original_cmd.to_s.downcase.squish
opt = original_opt.to_s.downcase.squish
direction = :toggle
if "#{cmd} #{opt}".match?(/\b(unlock|open|lock|close|pop|vent)\b/)
combine = "#{cmd} #{opt}"
direction = :open if combine.match?(/\b(unlock|open|pop)\b/)
direction = :close if combine.match?(/\b(lock|close|shut)\b/)
cmd, opt = combine.gsub(/\b(open|close|pop)\b/, "").squish.split(" ", 2)
elsif cmd.to_i.to_s == cmd
opt = cmd.to_i
cmd = :temp
end
case cmd.to_sym
when :request
ActionCable.server.broadcast(:tesla_channel, format_data(Tesla.new.cached_vehicle_data))
when :update, :reload
ActionCable.server.broadcast(:tesla_channel, format_data(car.vehicle_data)) unless quick
@response = "Updating car cell"
return @response
when :off, :stop
@response = "Stopping car"
car.off_car unless quick
when :on, :start, :climate
@response = "Starting car"
car.start_car unless quick
when :boot, :trunk
dir = "Closing" if direction == :close
@response = "#{dir || "Popping"} the boot"
car.pop_boot(direction) unless quick
when :lock
@response = "Locking car doors"
car.doors(:close) unless quick
when :unlock
@response = "Unlocking car doors"
car.doors(:open) unless quick
when :doors, :door
if direction == :open
@response = "Unlocking car doors"
else
@response = "Locking car doors"
end
car.doors(direction) unless quick
when :windows, :window, :vent
if direction == :open
@response = "Opening car windows"
else
@response = "Closing car windows"
end
car.windows(direction) unless quick
when :frunk
@response = "Opening frunk"
car.pop_frunk unless quick
when :honk, :horn
@response = "Honking the horn"
car.honk unless quick
when :seat
@response = "Turning on driver seat heater"
car.heat_driver unless quick
when :passenger
@response = "Turning on passenger seat heater"
car.heat_passenger unless quick
when :navigate
address = opt[::Jarvis::Regex.address]&.squish.presence if opt.match?(::Jarvis::Regex.address)
# If specify nearest, search based on car location.
# Otherwise use the one in contacts and fallback to nearest to house
address ||= address_book.contact_by_name(original_opt)&.address
address ||= address_book.nearest_address_from_name(original_opt)
if address.present?
duration = address_book.traveltime_seconds(address)
if duration && duration < 100 # seconds
@cancel = true
@response = "You're already at your destination."
elsif duration
@response = "It will take #{distance_of_time_in_words(duration)} to get to #{original_opt.squish}"
else
@response = "Navigating to #{original_opt.squish}"
end
if !@cancel && !quick
car.start_car
car.navigate(address)
end
else
@response = "I can't find #{original_opt.squish}"
end
when :temp
temp = opt.to_s[/\d+/]
temp = TEMP_MAX if opt.to_s.match?(/\b(hot|heat|high)\b/)
temp = TEMP_MIN if opt.to_s.match?(/\b(cold|cool|low)\b/)
@response = "Car temp set to #{temp.to_i}"
car.set_temp(temp.to_i) unless quick
when :cool
@response = "Car temp set to #{TEMP_MIN}"
car.set_temp(TEMP_MIN) unless quick
when :heat, :defrost, :warm
@response = "Defrosting the car"
unless quick
car.set_temp(TEMP_MAX)
car.heat_driver
car.heat_passenger
car.defrost
end
when :find
@response = "Finding car..."
unless quick
data = car.vehicle_data
loc = [data.dig(:drive_state, :latitude), data.dig(:drive_state, :longitude)]
Jarvis.say("http://maps.apple.com/?ll=#{loc.join(',')}&q=#{loc.join(',')}", :sms)
end
else
@response = "Not sure how to tell car: #{[cmd, opt].map(&:presence).compact.join('|')}"
end
Jarvis.ping(@response) unless quick
@response
rescue TeslaError => e
if e.message.match?(/forbidden/i)
ActionCable.server.broadcast(:tesla_channel, format_data(Tesla.new.cached_vehicle_data))
else
ActionCable.server.broadcast(:tesla_channel, { failed: true })
end
"Tesla #{e.message}"
rescue StandardError => e
ActionCable.server.broadcast(:tesla_channel, { failed: true })
backtrace = e.backtrace&.map {|l|l.include?('app') ? l.gsub("`", "'") : nil}.compact.join("\n")
SlackNotifier.notify("Failed to command: #{e.inspect}\n#{backtrace}")
raise e # Re-raise to stop worker from sleeping and attempting to re-get
"Failed to request from Tesla"
end
def cToF(c)
return unless c
(c * (9/5.to_f)).round + 32
end
def format_data(data)
return {} if data.blank?
{
forbidden: DataStorage[:tesla_forbidden],
charge: data.dig(:charge_state, :battery_level),
miles: data.dig(:charge_state, :battery_range)&.floor,
charging: {
state: data.dig(:charge_state, :charging_state),
active: data.dig(:charge_state, :charging_state) != "Complete", # FIXME
speed: data.dig(:charge_state, :charge_rate),
eta: data.dig(:charge_state, :minutes_to_full_charge),
},
climate: {
on: data.dig(:climate_state, :is_climate_on),
set: cToF(data.dig(:climate_state, :driver_temp_setting)),
current: cToF(data.dig(:climate_state, :inside_temp)),
},
open: {
ft: data.dig(:vehicle_state, :ft), # Frunk
df: data.dig(:vehicle_state, :df), # Driver Door
fd_window: data.dig(:vehicle_state, :fd_window), # Driver Window
pf: data.dig(:vehicle_state, :pf), # Passenger Door
fp_window: data.dig(:vehicle_state, :fp_window), # Passenger Window
dr: data.dig(:vehicle_state, :dr), # Rear Driver Door
rd_window: data.dig(:vehicle_state, :rd_window), # Rear Driver Window
pr: data.dig(:vehicle_state, :pr), # Rear Passenger Door
rp_window: data.dig(:vehicle_state, :rp_window), # Rear Passenger Window
rt: data.dig(:vehicle_state, :rt), # Trunk
},
locked: data.dig(:vehicle_state, :locked),
drive: drive_data(data).merge(speed: data.dig(:drive_state, :speed).to_i),
timestamp: data.dig(:vehicle_config, :timestamp).to_i / 1000
}
end
def stubbed_data
{
forbidden: false,
charge: 100,
miles: 194,
charging: {
active: true,
speed: 34.4,
eta: 35,
},
climate: {
on: true,
set: 69,
current: 70,
},
open: {
ft: false, # Frunk
df: false, # Driver Door
fd_window: true, # Driver Window
pf: false, # Passenger Door
fp_window: false, # Passenger Window
dr: false, # Rear Driver Door
rd_window: false, # Rear Driver Window
pr: false, # Rear Passenger Door
rp_window: false, # Rear Passenger Window
rt: true, # Trunk
},
locked: true,
drive: {
action: ["Driving", "Near", "At", "Stopped"].sample,
location: address_book.contacts.pluck(:name).sample,
speed: 0,
},
timestamp: Time.current.to_i
}
end
def drive_data(data)
loc = [data.dig(:drive_state, :latitude), data.dig(:drive_state, :longitude)]
is_driving = data.dig(:drive_state, :speed).to_i > 0
place = address_book.near(loc)
action = is_driving ? :Near : :At
return { action: action, location: place[:name] } if place.present?
action = is_driving ? :Driving : :Stopped
city = address_book.reverse_geocode(loc) if loc.compact.length == 2
return { action: action, location: city } if city.present?
{ action: action, location: "<Unknown>" }
end
end
|
class ChurchesController < ApplicationController
before_filter :authenticate_user!, :only => [:new, :edit, :create, :update, :destroy]
load_and_authorize_resource
respond_to :html, :json, :xml
def index
@churches = Church.page params[:page]
respond_with @churches
end
def geo
@churches = Church.near(params[:l]).page params[:page]
respond_with @churches
end
def search
@query = params[:n]
@churches = Church.search_with_solr @query, params[:page] # this is paginated
respond_with @churches
end
def follow
redirect_to :root
render nil
end
def show
@church = Church.with_relations.find(params[:id])
@sermons = @church.try(:sermons).page params[:page]
respond_with @churches
end
def new
@church = Church.new
respond_with @church
end
def edit
@church = Church.find(params[:id])
end
def create
@church = Church.new(params[:church])
flash[:notice] = 'Church was successfully created.' if @church.save
respond_with @church
end
def update
@church = Church.find(params[:id])
flash[:notice] = 'Church was successfully updated.' if @church.update_attributes(params[:church])
respond_with @church
end
def destroy
@church = Church.find(params[:id])
@church.destroy
respond_with @church
end
end
|
describe "SalariedEmployee" do
describe "#initialize" do
it "should instantiate properly" do
test = SalariedEmployee.new "Clay"
expect(test.name).to eq("Clay")
end
it "should set the default payrate" do
test = SalariedEmployee.new "Clay"
expect(test.payrate).to eq(50000)
end
end
describe "#pay" do
it "should return the pay for a single paycheck" do
test = SalariedEmployee.new "Clay"
two_week_pay = test.pay
expect(two_week_pay).to eq(1923.08)
end
end
end |
class AdvancedApplicationWindowLayout < Netzke::Basepack::BorderLayoutPanel
include AdvancedApplicationWindowLayoutHelper
def configuration
super.merge(
:header => false,
:border => false,
:tbar => [{
:xtype => 'buttongroup',
:title => 'Sample jobs',
:columns => 3,
:layout => 'table',
:height => 80,
:items => [{
:text => 'Job 1',
:iconCls => 'icon-job-1',
:rowspan => '2',
:scale => 'medium',
:arrowAlign => 'bottom',
:iconAlign => 'top',
:width => 50,
:menu => [{
:text => 'Backup emails',
:iconCls => 'icon-execute-job-1',
:handler => :on_long_running_job,
:data => {:sleep_for => 7, :job_label => "Backup emails"}
}]
},{
:text => 'Job 2',
:iconCls => 'icon-job-2',
:rowspan => '2',
:scale => 'medium',
:arrowAlign => 'bottom',
:iconAlign => 'top',
:width => 40,
:menu => [{
:text => 'Backup Google servers',
:iconCls => 'icon-execute-job-2',
:handler => :on_long_running_job,
:data => {:sleep_for => 30, :job_label => "Backup Google servers"}
}]
},{
:iconCls => 'icon-job-3',
:tooltip => 'Job 3 - Execute 30 second job'
},{
:iconCls => 'icon-job-4',
:tooltip => 'Job 4 - Execute 60 second job'
}]
}],
:items => [
{
:name => "details",
:class_name => "Netzke::Basepack::Panel",
:region => :east,
:title => "Details",
:width => 250,
:split => true
},
{
:name => "advanced_window_tree",
:class_name => "AdvancedWindowTree",
:region => :center,
:title => "Job history",
}
]
)
end
endpoint :select_item do |params|
# store selected location id in the session for this component's instance
component_session[:item_type] = params[:item_type]
component_session[:item_id] = params[:item_id]
# selected node
unless params[:item_type].nil?
item = case params[:item_type]
when 'node'
Job.find(params[:item_id])
when 'tree'
Infrastructure.find(params[:item_id])
else
Job.find(params[:item_id])
end
end
{
:details => {:update_body_html => params[:item_type] == 'node' ? job_info_html(item) : infrastructure_info_html(item), :set_title => "#{item.label} details"}
}
end
def infrastructure_details(item)
infrastructure_info_html(item)
end
def node_details(item)
node_info_html(item)
end
# Overriding initComponent
js_method :init_component, <<-JS
function(){
// calling superclass's initComponent
#{js_full_class_name}.superclass.initComponent.call(this);
// setting the 'rowclick' event
this.getChildComponent('advanced_window_tree').on('click', this.onItemSelectionChanged, this);
}
JS
# Event handler
js_method :on_item_selection_changed, <<-JS
function(self, rowIndex){
var tree_object = self.id.split("-");
var item_type = tree_object[0];
var item_id = tree_object[1];
this.selectItem({item_id: item_id, item_type: item_type});
}
JS
js_method :on_long_running_job, <<-JS
function(self){
var sleep_for = self.data.sleepFor;
var job_label = self.data.jobLabel;
this.getEl().mask('Processing...','loadingMask');
this.longRunningJob({el_id: this.id, sleep_for: sleep_for, job_label: job_label}, function(result) {}, this);
}
JS
endpoint :long_running_job do |params|
# pass a code representing the origin of the message,
# so when the job is completed, and the message returned
# with the same code via websockets, we know which
# window to update etc
el_id = params[:el_id]
sleep_for = params[:sleep_for]
job_label = params[:job_label]
Delayed::Job.enqueue LongRunningJob.new(:return_code => :success_reload,
:element_id => el_id,
:sleep_for => sleep_for,
:job_label => job_label)
end
end
|
class Sub < ActiveRecord::Base
validates :title, :user_id, presence: true
belongs_to :moderator,
foreign_key: :user_id,
class_name: :User
has_many :original_posts,
class_name: :Posts
has_many :posts,
through: :post_subs,
source: :post
has_many :post_subs
end
|
# frozen_string_literal: true
if ENV['PARALLEL_WORKERS'].to_i != 1
ENV['PARALLEL_WORKERS'] = '1'
warn '**** PARALLEL_WORKERS has been disabled ****'
warn 'SimpleCov does not support Rails Parallelization yet'
end
return if ENV['RUBYMINE_SIMPLECOV_COVERAGE_PATH']
if defined?(Spring) && ENV['DISABLE_SPRING'].nil?
puts '**** NO COVERAGE FOR YOU! ****'
puts 'Please disable Spring to get COVERAGE by `DISABLE_SPRING=1 COVERAGE=1 bin/rspec`'
else
SimpleCov.start 'rails' do
add_filter %w[
app/views lib/rails lib/templates
bin coverage log test vendor node_modules db doc public storage tmp
]
add_group('Carriers', 'app/carriers')
add_group('Scripts', 'app/scripts')
# add_group("Views", "app/views")
enable_coverage(:branch)
enable_coverage_for_eval
end
parallel_number = [
ENV['CIRCLE_NODE_INDEX'] || ENV['CI_INDEX'],
ENV['TEST_ENV_NUMBER'] || ENV['JOB_NUMBER']
].compact.join('_')
if parallel_number.present?
SimpleCov.command_name "Job #{parallel_number}"
end
if ENV['COBERTURA_ENABLED']
require 'simplecov-cobertura'
SimpleCov.formatter = SimpleCov::Formatter::CoberturaFormatter
end
end
|
class GuestsController < ApplicationController
def new
@guest = Guest.new
end
# if user is logged in, return current_user, else return guest_user
def current_or_guest_user
if current_user
if session[:guest_user_id] && session[:guest_user_id] != current_user.id
logging_in
# reload guest_user to prevent caching problems before destruction
guest_user(with_retry = false).reload.try(:destroy)
session[:guest_user_id] = nil
end
current_user
else
guest_user
end
end
def guest_user(with_retry = true)
# Cache the value the first time it's gotten.
@guest_user ||= User.find(session[:guest_user_id] ||= create_guest_user.id)
rescue ActiveRecord::RecordNotFound # if session[:guest_user_id] invalid
session[:guest_user_id] = nil
create if with_retry
binding.pry
end
private
def input_params
params.require(:guest).permit(:username, :dialect_id)
end
def create_guest_user
u = Guest.create(:username => input_params[:username], :dialect_id => input_params[:dialect_id])
u.save!(:validate => false)
session[:guest_user_id] = u.id
u
end
end
|
class IncidentsController < InheritedResources::Base
private
def incident_params
params.require(:incident).permit(:name, :duration)
end
end
|
class Statosaurus
def initialize(fields, logger)
@fields = fields.sort
values = {}
@logger = logger
@logger.info("# Fields: " + fields.join(" "))
end
def values
Thread.current[:values] ||= {}
end
def transaction_id
Thread.current[:transaction_id]
end
def measure(field, &block)
result = nil
measurement = Benchmark.measure do
result = yield
end
values["#{field}_real"] = min(measurement.real)
values["#{field}_sys"] = min(measurement.stime)
values["#{field}_user"] = min(measurement.utime)
result
end
def set(key, value)
values[key] = value
end
def transaction
Thread.current[:transaction_id] = "#{Process.pid}-#{Time.now.to_i}-#{rand(9999)}"
result = yield
print
values.clear
Thread.current[:transaction_id]= nil
result
end
private
def print
prefix = [Time.now.iso8601, transaction_id].join(" ")
info = @fields.collect { |field| format(values[field]) }.join(" ")
@logger.info(prefix + " " + info)
end
def min(n)
[n, 10e-5].max
end
def format(value)
case value
when NilClass
"-"
when Float
"%f" % value
when TrueClass, FalseClass
value ? '1' : 0
else
value.to_s
end
end
end |
class Collection < ApplicationRecord
belongs_to :user
has_many :items, dependent: :destroy
mount_uploader :image, ImageUploader
# validates :name, presence: true, unless: :image?
validate :image_present?
validate :name_present?
validate :explanation_present?
validates :name, :explanation, :image, :user, presence: true
# 名前、説明、画像選択がない場合エラーとする
def image_present?
if image.blank?
errors.add(:error, "画像のアップロードを選択してください。")
end
end
def name_present?
if name.blank?
errors.add(:error, "名前を入力してください。")
end
end
def explanation_present?
if explanation.blank?
errors.add(:error, "説明を入力してください。")
end
end
end
|
require 'spec_helper_acceptance'
describe 'singularity class:' do
context 'default parameters' do
it 'runs successfully' do
pp = <<-EOS
class { 'singularity':
# Avoid /etc/localtime which may not exist in minimal Docker environments
bind_paths => ['/etc/hosts'],
}
EOS
apply_manifest(pp, catch_failures: true)
apply_manifest(pp, catch_changes: true)
end
describe file('/etc/singularity/singularity.conf') do
it { is_expected.to be_file }
it { is_expected.to be_mode 644 }
it { is_expected.to be_owned_by 'root' }
it { is_expected.to be_grouped_into 'root' }
end
describe command('singularity exec library://alpine cat /etc/alpine-release') do
its(:exit_status) { is_expected.to eq(0) }
its(:stdout) { is_expected.to match %r{[0-9]+.[0-9]+.[0-9]+} }
end
end
context 'source install' do
let(:version) { '3.7.4' }
it 'runs successfully' do
pp = <<-EOS
class { 'singularity':
version => '#{version}',
install_method => 'source',
# Avoid /etc/localtime which may not exist in minimal Docker environments
bind_paths => ['/etc/hosts'],
}
EOS
if fact('os.family') == 'RedHat'
on hosts, 'puppet resource package singularity ensure=absent'
end
apply_manifest(pp, catch_failures: true)
apply_manifest(pp, catch_changes: true)
end
describe file('/etc/singularity/singularity.conf') do
it { is_expected.to be_file }
it { is_expected.to be_mode 644 }
it { is_expected.to be_owned_by 'root' }
it { is_expected.to be_grouped_into 'root' }
end
describe command('singularity version') do
its(:stdout) { is_expected.to include(version) }
end
describe command('singularity exec library://alpine cat /etc/alpine-release') do
its(:exit_status) { is_expected.to eq(0) }
its(:stdout) { is_expected.to match %r{[0-9]+.[0-9]+.[0-9]+} }
end
end
context 'upgrade' do
let(:version) { '3.8.0' }
it 'runs successfully' do
pp = <<-EOS
class { 'singularity':
version => '#{version}',
install_method => 'source',
# Avoid /etc/localtime which may not exist in minimal Docker environments
bind_paths => ['/etc/hosts'],
}
EOS
apply_manifest(pp, catch_failures: true)
apply_manifest(pp, catch_changes: true)
end
describe file('/etc/singularity/singularity.conf') do
it { is_expected.to be_file }
it { is_expected.to be_mode 644 }
it { is_expected.to be_owned_by 'root' }
it { is_expected.to be_grouped_into 'root' }
end
describe command('singularity version') do
its(:stdout) { is_expected.to include(version) }
end
describe command('singularity exec library://alpine cat /etc/alpine-release') do
its(:exit_status) { is_expected.to eq(0) }
its(:stdout) { is_expected.to match %r{[0-9]+.[0-9]+.[0-9]+} }
end
end
context 'downgrade' do
let(:version) { '3.7.4' }
it 'runs successfully' do
pp = <<-EOS
class { 'singularity':
version => '#{version}',
install_method => 'source',
# Avoid /etc/localtime which may not exist in minimal Docker environments
bind_paths => ['/etc/hosts'],
}
EOS
apply_manifest(pp, catch_failures: true)
apply_manifest(pp, catch_changes: true)
end
describe file('/etc/singularity/singularity.conf') do
it { is_expected.to be_file }
it { is_expected.to be_mode 644 }
it { is_expected.to be_owned_by 'root' }
it { is_expected.to be_grouped_into 'root' }
end
describe command('singularity version') do
its(:stdout) { is_expected.to include(version) }
end
end
end
|
module FakerioApi
class Internet
def self.emails(options = {})
request_parameters = {count: 1}.merge(options)
request_parameters.merge!({uuid: FakerioApi::Base.uuid, auth_token: FakerioApi::Base.token})
FakerioApi::Base.get("/api/v1/internet/emails.json", body: request_parameters).parsed_response
end
def self.ip_v4_addresses(opitons = {})
request_parameters = {count: 1}.merge(options)
request_parameters.merge!({uuid: FakerioApi::Base.uuid, auth_token: FakerioApi::Base.token})
FakerioApi::Base.get("/api/v1/internet/ip_addresses.json", body: request_parameters).parsed_responpse
end
end
end
|
=begin
output: all even numbers 1- 99 inclusive
steps:
1: puts all numbers 1-99
=end
(1..99).each do |number|
puts number if number.even?
end
number_range = (1..99).to_a
arr = number_range.select { |num| num % 2 == 0 }
arr.each { |num| p num } |
require File.dirname(__FILE__) + '/test_helper.rb'
class TestGoogleChart < Test::Unit::TestCase
context '#Line' do
context 'with hash parameters' do
setup do
@url = GoogleChart.Line(:size => '1000x300', :data => [[35, 41], [50, 33]], :scale => 0..61)
end
should 'return Google Chart URL' do
assert_match(%r{\Ahttp://chart\.apis\.google\.com/chart\?}, @url)
end
should 'include chart type parameter' do
assert_match(/\bcht=lc\b/, @url)
end
should 'include chart size parameter' do
assert_match(/\bchs=1000x300\b/, @url)
end
should 'include chart data parameter' do
assert_match(/\bchd=s:jp,yh\b/, @url)
end
end
context 'with block parameters' do
setup do
@url = GoogleChart.Line do |c|
c.size = '800x375'
c.data = [[35, 41], [50, 33]]
c.scale = 0..61
end
end
should 'return Google Chart URL' do
assert_match(%r{\Ahttp://chart\.apis\.google\.com/chart\?}, @url)
end
should 'include chart type parameter' do
assert_match(/\bcht=lc\b/, @url)
end
should 'include chart size parameter' do
assert_match(/\bchs=800x375\b/, @url)
end
should 'include chart data parameter' do
assert_match(/\bchd=s:jp,yh\b/, @url)
end
end
end
context '#Bar' do
context 'with hash parameters' do
setup do
@url = GoogleChart.Bar(:size => '1000x300', :data => [[35, 41], [50, 33]], :scale => 0..61)
end
should 'return Google Chart URL' do
assert_match(%r{\Ahttp://chart\.apis\.google\.com/chart\?}, @url)
end
should 'include chart type parameter' do
assert_match(/\bcht=bvg\b/, @url)
end
should 'include chart size parameter' do
assert_match(/\bchs=1000x300\b/, @url)
end
should 'include chart data parameter' do
assert_match(/\bchd=s:jp,yh\b/, @url)
end
end
context 'with block parameters' do
setup do
@url = GoogleChart.Bar do |c|
c.size = '800x375'
c.data = [[35, 41], [50, 33]]
c.scale = 0..61
end
end
should 'return Google Chart URL' do
assert_match(%r{\Ahttp://chart\.apis\.google\.com/chart\?}, @url)
end
should 'include chart type parameter' do
assert_match(/\bcht=bvg\b/, @url)
end
should 'include chart size parameter' do
assert_match(/\bchs=800x375\b/, @url)
end
should 'include chart data parameter' do
assert_match(/\bchd=s:jp,yh\b/, @url)
end
end
end
end
|
class NousarmicropostsController < ApplicationController
# GET /Nousarmicroposts
# GET /Nousarmicroposts.json
def index
@nousarmicroposts = Nousarmicropost.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @nousarmicroposts }
end
end
# GET /Nousarmicroposts/1
# GET /Nousarmicroposts/1.json
def show
@nousarmicropost = Nousarmicropost.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @nousarmicropost }
end
end
# GET /Nousarmicroposts/new
# GET /Nousarmicroposts/new.json
def new
@nousarmicropost = Nousarmicropost.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @nousarmicropost }
end
end
# GET /Nousarmicroposts/1/edit
def edit
@nousarmicropost = Nousarmicropost.find(params[:id])
end
# POST /Nousarmicroposts
# POST /Nousarmicroposts.json
def create
@nousarmicropost = Nousarmicropost.new(params[:nousarmicropost])
respond_to do |format|
if @nousarmicropost.save
format.html { redirect_to @nousarmicropost, notice: 'Nousarmicropost was successfully created.' }
format.json { render json: @nousarmicropost, status: :created, location: @nousarmicropost }
else
format.html { render action: "new" }
format.json { render json: @nousarmicropost.errors, status: :unprocessable_entity }
end
end
end
# PUT /Nousarmicroposts/1
# PUT /Nousarmicroposts/1.json
def update
@nousarmicropost = Nousarmicropost.find(params[:id])
respond_to do |format|
if @nousarmicropost.update_attributes(params[:nousarmicropost])
format.html { redirect_to @nousarmicropost, notice: 'Nousarmicropost was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @nousarmicropost.errors, status: :unprocessable_entity }
end
end
end
# DELETE /Nousarmicroposts/1
# DELETE /Nousarmicroposts/1.json
def destroy
@nousarmicropost = Nousarmicropost.find(params[:id])
@nousarmicropost.destroy
respond_to do |format|
format.html { redirect_to microposts_url }
format.json { head :no_content }
end
end
end
|
require 'zxcvbn'
require 'sqlite3'
require 'bcrypt'
password_file = 'password_dictionaries/10_million_password_list_top_10000.txt'
database_file = 'db/entropy.sqlite3'
tester = Zxcvbn::Tester.new
puts "Reading common passwords"
start_time = Time.now
entropies = File.readlines(password_file).map(&:chomp).each_with_object({}) do |password, obj|
entropy = tester.test(password).entropy
(obj[entropy] ||= []) << password
end
puts "Finished entropy collection in #{Time.now - start_time}s"
# Open a SQLite 3 database file
SQLite3::Database.new(database_file) do |db|
sql = <<-SQL
SELECT email, password_hash, entropy
FROM users
ORDER BY entropy
SQL
db.execute(sql) do |email, password_hash, entropy|
puts "User: #{email}, entropy: #{entropy}, password_hash: #{password_hash}"
next unless candidate_passwords = entropies[entropy]
match = candidate_passwords.find do |candidate|
BCrypt::Password.new(password_hash) == candidate
end
if match
puts "Password is: #{match}"
else
puts "No Matching Candidates"
end
end
end
|
class OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy, :review]
def show
authorize @order
end
def new
@order = Order.new
authorize @order
end
def create
@order = Order.new(order_params)
@order.user = current_user
@pastel = @order.pastel
authorize @order
if @order.quantity > @pastel.stock
redirect_to pastel_path(@pastel)
flash[:alert] = "Not enough stock"
elsif @order.save
@pastel.stock -= @order.quantity
@pastel.save!
redirect_to user_path(current_user)
else
render :new
# needs to be changed when we have a pastel show page
end
end
def edit
authorize @order
end
def update
@pastel = @order.pastel
authorize @order
if @order.quantity > @pastel.stock
flash[:alert] = "Not enough stock, please try again"
elsif @order.update(order_params)
redirect_to user_path(current_user)
else
render :edit # print edit.html.erb
end
end
def destroy
authorize @order
@order.destroy
redirect_to user_path(current_user)
end
def review
authorize @order
end
private
def set_order
@order = Order.find(params[:id])
end
def order_params
params.require(:order).permit(:pastel_id, :user_id, :quantity, :order_date, :review)
end
end
|
module ReportsKit
module Reports
module Data
class ChartOptions
DEFAULT_COLORS = %w(
#1f77b4
#aec7e8
#ff7f0e
#ffbb78
#2ca02c
#98df8a
#d62728
#ff9896
#9467bd
#c5b0d5
#8c564b
#c49c94
#e377c2
#f7b6d2
#7f7f7f
#c7c7c7
#bcbd22
#dbdb8d
#17becf
#9edae5
).freeze
DEFAULT_OPTIONS = {
scales: {
xAxes: [{
gridLines: {
display: false
},
barPercentage: 0.9,
categoryPercentage: 0.9
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
legend: {
labels: {
usePointStyle: true
}
},
maintainAspectRatio: false,
tooltips: {
xPadding: 8,
yPadding: 7
}
}.freeze
attr_accessor :data, :options, :chart_options, :inferred_options, :dataset_options, :type
def initialize(data, options:, inferred_options: {})
self.data = data
self.options = options.try(:except, :options) || {}
self.chart_options = options.try(:[], :options) || {}
self.dataset_options = options.try(:[], :datasets)
self.type = options.try(:[], :type) || 'bar'
self.options = inferred_options.deep_merge(self.options) if inferred_options.present?
end
def perform
set_colors
set_chart_options
set_dataset_options
set_type
data
end
private
def set_colors
if donut_or_pie_chart?
set_record_scoped_colors
else
set_dataset_scoped_colors
end
end
def set_record_scoped_colors
data[:chart_data][:datasets] = data[:chart_data][:datasets].map do |dataset|
length = dataset[:data].length
dataset[:backgroundColor] = DEFAULT_COLORS * (length.to_f / DEFAULT_COLORS.length).ceil
dataset
end
end
def set_dataset_scoped_colors
data[:chart_data][:datasets] = data[:chart_data][:datasets].map.with_index do |dataset, index|
color = DEFAULT_COLORS[index % DEFAULT_COLORS.length]
dataset[:backgroundColor] = color
dataset[:borderColor] = color
dataset
end
end
def default_options
@default_options ||= begin
return {} if donut_or_pie_chart?
default_options = DEFAULT_OPTIONS.deep_dup
x_axis_label = options[:x_axis_label]
if x_axis_label
default_options[:scales] ||= {}
default_options[:scales][:xAxes] ||= []
default_options[:scales][:xAxes][0] ||= {}
default_options[:scales][:xAxes][0][:scaleLabel] ||= {}
default_options[:scales][:xAxes][0][:scaleLabel][:display] ||= true
default_options[:scales][:xAxes][0][:scaleLabel][:labelString] ||= x_axis_label
end
y_axis_label = options[:y_axis_label]
if y_axis_label
default_options[:scales] ||= {}
default_options[:scales][:yAxes] ||= []
default_options[:scales][:yAxes][0] ||= {}
default_options[:scales][:yAxes][0][:scaleLabel] ||= {}
default_options[:scales][:yAxes][0][:scaleLabel][:display] ||= true
default_options[:scales][:yAxes][0][:scaleLabel][:labelString] ||= y_axis_label
end
default_options
end
end
def set_chart_options
merged_options = default_options
merged_options = merged_options.deep_merge(chart_options) if chart_options
data[:chart_data][:options] = merged_options
end
def set_dataset_options
return if data[:chart_data][:datasets].blank? || dataset_options.blank?
data[:chart_data][:datasets] = data[:chart_data][:datasets].map do |dataset|
dataset.merge(dataset_options)
end
end
def set_type
return if type.blank?
data[:type] = type
end
def donut_or_pie_chart?
type.in?(%w(donut pie))
end
end
end
end
end
|
class Remision < ActiveRecord::Base
attr_accessible :numero_remision, :centro_costo_id, :fecha_remision, :concepto_servicio_id, :estado_remision_id, :referencia
scope :ordenado_01, -> {order("fecha_remision desc")}
scope :ordenado_id_desc, -> {order("id desc")}
scope :con_salidas, -> { where("exists (select * from remisiones_detalles rd join productos_movimientos pm on rd.id = pm.remision_detalle_id where remisiones.id = rd.remision_id) and remisiones.estado_remision_id = 4")}
validates :numero_remision, :centro_costo_id, :fecha_remision, :concepto_servicio_id, :estado_remision_id, presence: true
validates :numero_remision, uniqueness: true
belongs_to :centro_costo
belongs_to :concepto_servicio
belongs_to :estado_remision
has_many :remisiones_detalles, class_name: 'RemisionDetalle', :dependent => :restrict_with_error
end
|
Rails.application.routes.draw do
get 'trainings/show'
get 'trainings/new'
get 'trainings/index'
root 'sessions#index'
#custom routes for login
#creating a new session
get '/login' => 'sessions#new'
post '/login' => 'sessions#create'
delete '/logout' => 'sessions#destroy' #this needs to be a delete action because you dont want '/logout' to be an option that can be typed in the url, but rather a button to click on a page
#can't log in without a user
#custom routes for signup
#creating a new model object
get '/signup' => 'users#new'
post '/signup' => 'users#create'
resources :workouts do
resources :trainings, only: [:index, :new, :create] #2021-01-15
end
resources :trainings
resources :races do # 2021-01-16 01
resources :trainings # 2021-01-16 01
end# 2021-01-16 01
resources :users
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
|
class UsersController < ApplicationController
skip_before_action :authenticate_user!, only: :show
def show
@user = User.find(params[:id])
@bookings = current_user.bookings
end
def edit
@user = User.find(params[:id])
end
def update
current_user.update(user_params)
current_user.save
redirect_to user_path(current_user)
end
private
def user_params
params.require(:user).permit(:email, :password, :photo, :first_name, :last_name)
end
end
|
#! /usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'optparse'
$LOAD_PATH.unshift( File.join( File.dirname( __FILE__ ), '..', 'lib' ))
require 'sip_notify'
opts_defaults = {
:port => 5060,
:user => nil,
:verbosity => 0,
:event => 'check-sync;reboot=false',
:spoof_src_addr => nil,
}
opts = {}
opts_parser = ::OptionParser.new { |op|
op.banner = "Usage: #{ ::File.basename(__FILE__) } HOST [options]"
op.on( "-p", "--port=PORT", Integer,
"Port. (Default: #{opts_defaults[:port].inspect})"
) { |v|
opts[:port] = v.to_i
if ! v.between?( 1, 65535 )
$stderr.puts "Invalid port."
$stderr.puts op
exit 1
end
}
op.on( "-u", "--user=USER", String,
"User/extension. (Default: #{opts_defaults[:user].inspect})"
) { |v|
opts[:user] = v
}
op.on( "-e", "--event=EVENT", String,
"Event. (Default: #{opts_defaults[:event].inspect})"
) { |v|
opts[:event] = v
}
op.on( "-t", "--type=EVENT_TYPE", String,
"Pre-defined event type."
) { |v|
opts[:event_type] = v
}
op.on( "--types", String,
"List pre-defined event types."
) { |v|
puts "Pre-defined event types:"
puts " #{'Name'.to_s.ljust(32)} #{'Event header'.to_s.ljust(30)} #{'Content-Type header'.to_s.ljust(35)} +"
puts " #{'-' * 32} #{'-' * 30} #{'-' * 35} #{'-' * 1}"
::SipNotify.event_templates.each { |name, info|
puts " #{name.to_s.ljust(32)} #{info[:event].to_s.ljust(30)} #{info[:content_type].to_s.ljust(35)} #{info[:content] ? '+' : ' '}"
}
exit 0
}
op.on( "--spoof-src-addr=SOURCE_ADDRESS", String,
"Spoof source IP address. (Must be run as root.)"
) { |v|
opts[:spoof_src_addr] = v
}
op.on_tail( "-v", "--verbose", "Increase verbosity level. Can be repeated." ) { |v|
opts[:verbosity] ||= 0
opts[:verbosity] += 1
}
op.on_tail("-?", "-h", "--help", "Show this help message." ) {
puts op
exit 0
}
}
begin
opts_parser.parse!
rescue ::OptionParser::ParseError => e
$stderr.puts e.message
$stderr.puts opts_parser
exit 1
end
opts[:host] = ::ARGV[0]
if ! opts[:host]
$stderr.puts "Missing host argument."
$stderr.puts opts_parser
exit 1
end
if opts[:event] && opts[:event_type]
$stderr.puts "Event and event type arguments don't make sense together."
$stderr.puts opts_parser
exit 1
end
opts = opts_defaults.merge( opts )
opts[:domain] = opts[:host]
if opts[:event_type]
et = ::SipNotify.event_templates[ opts[:event_type].to_sym ]
if ! et
$stderr.puts "Event type not found: #{opts[:event_type].inspect}"
exit 1
end
opts[:event] = et[:event]
opts[:content_type] = et[:content_type]
opts[:content] = et[:content]
end
begin
::SipNotify.send_variations( opts[:host], {
:port => opts[:port],
:user => opts[:user],
:domain => opts[:domain],
:verbosity => opts[:verbosity],
:via_rport => true,
:event => opts[:event],
:content_type => opts[:content_type],
:content => opts[:content],
:spoof_src_addr => opts[:spoof_src_addr],
})
rescue ::SipNotifyError => e
$stderr.puts "Error: #{e.message}"
exit 1
end
# Local Variables:
# mode: ruby
# End:
|
class ExternalActivity < ActiveRecord::Base
belongs_to :user
has_many :offerings, :dependent => :destroy, :as => :runnable, :class_name => "Portal::Offering"
has_many :teacher_notes, :as => :authored_entity
has_many :author_notes, :as => :authored_entity
acts_as_replicatable
include Changeable
include Publishable
self.extend SearchableModel
@@searchable_attributes = %w{name description}
named_scope :like, lambda { |name|
name = "%#{name}%"
{
:conditions => ["#{self.table_name}.name LIKE ? OR #{self.table_name}.description LIKE ?", name,name]
}
}
named_scope :published,
{
:conditions =>{:publication_status => "published"}
}
class <<self
def searchable_attributes
@@searchable_attributes
end
def display_name
"External Activity"
end
def search_list(options)
name = options[:name]
if (options[:include_drafts])
external_activities = ExternalActivity.like(name)
else
# external_activities = ExternalActivity.published.like(name)
external_activities = ExternalActivity.like(name)
end
portal_clazz = options[:portal_clazz] || (options[:portal_clazz_id] && options[:portal_clazz_id].to_i > 0) ? Portal::Clazz.find(options[:portal_clazz_id].to_i) : nil
if portal_clazz
external_activities = external_activities - portal_clazz.offerings.map { |o| o.runnable }
end
if options[:paginate]
external_activities = external_activities.paginate(:page => options[:page] || 1, :per_page => options[:per_page] || 20)
else
external_activities
end
end
end
##
## Hackish stub: Noah Paessel
##
def offerings
[]
end
#def self.display_name
#'Activity'
#end
def left_nav_panel_width
300
end
def print_listing
listing = []
end
def run_format
:run_external_html
end
end
|
# coding: utf-8
# frozen_string_literal: true
require 'pp'
require './uri.rb'
# require 'uri'
# modify uri module to permit '|'
require 'eventmachine'
require 'em-http'
require 'nokogiri'
require 'open-uri'
require 'httpclient'
require 'mechanize'
require 'net/http'
require 'logger'
require 'sqlite3'
require 'capybara/webkit'
require 'headless'
require 'parallel'
# crawler
class Crawler
DOWNLOADDIR = '/var/smb/sdc1/video'
CrawlerLOGGER = Logger.new(
DOWNLOADDIR +
"/0log/download_#{Time.now.strftime('%Y%m%d')}.log"
)
M3UPath = DOWNLOADDIR + "/0m3u/#{Time.now.strftime('%Y%m%d')}.m3u"
START_URL = 'http://youtubeanisoku1.blog106.fc2.com/'
AGENT = Mechanize.new
CONCURRENCY = 256 # 32
WATCH_INTERVAL = 1
MEGA = (1024 * 1024).to_f
JOB_ANISOKUTOP = 'アニ速TOP'
JOB_KOUSINPAGE = '更新ページ'
JOB_KOBETUPAGE = '個別ページ'
JOB_ANITANSEARCH = 'アニタン検索ページ'
JOB_NOSUBSEARCH = 'nosub検索ページ'
JOB_NOSUBVIDEO = 'nosubビデオページ'
JOB_ANITANVIDEO = 'アニタンビデオページ'
JOB_CONVERT = 'flv2mp4'
JOB_DOWNLOADVIDEO = 'download'
DBFILE = 'crawler.db'
# constructor
# hash[:ffmpeg] convert or not
# hash[:debug] debug or not
# hash[:usecurl] download by curl
def initialize(arghash)
@queue = []
@queue.push(kind: JOB_ANISOKUTOP, value: START_URL)
@fetching = 0
@downloads = {}
@ffmpeg = arghash[:ffmpeg] || false
# @debug = arghash[:debug] || false
@usecurl = arghash[:usecurl] || false
@_gaman = 240
@gaman = @_gaman
@candidate = {}
@title = {}
@titles = {}
@downloads = {}
@urls = {}
sql = <<~SQL
CREATE TABLE IF NOT EXISTS crawler(
id integer primary key,
name text,
path text,
created_at TIMESTAMP DEFAULT (DATETIME('now','localtime')),
url text
);
SQL
open_db do |db|
db.execute sql
end
@sql = <<~SQL
insert into crawler(name, path, url) values(:name, :path, :url)
SQL
sql_select = <<~SQL
select * from crawler
SQL
@himado = {}
open_db do |db|
db.execute(sql_select) do |row|
@himado[row[4]] = true
end
end
Capybara::Webkit.configure do |config|
config.debug = false
config.allow_url('*')
end
Capybara.default_driver = :webkit
Capybara.javascript_driver = :webkit
Headless.new.start
@session = Capybara::Session.new(:webkit)
@session.driver.header(
'user-agent',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
)
end
def open_db
db = SQLite3::Database.new(DBFILE)
yield(db)
db.close
end
def run
EM.run do
EM.add_periodic_timer(WATCH_INTERVAL) do
diff = CONCURRENCY - @fetching
diff.times do
# print "queue - #{@queue.size}\t"
job = @queue.pop
process job if job
end
if @queue.size.zero?
@gaman -= 1
print "fetching:#{@fetching} gaman:#{@gaman}\t"
if @gaman.zero?
puts :finish
pp @downloads
EM.stop_event_loop
end
else
@gaman = @_gaman
pp @downloads
end
end
end
end
def process(job)
case job[:kind]
when JOB_ANISOKUTOP
anisokutop job[:value]
when JOB_KOUSINPAGE
anisokukousin job[:value]
when JOB_KOBETUPAGE
anisokukobetu job[:value]
when JOB_NOSUBSEARCH
# sleep 0.5
nosubsearch job[:value]
when JOB_ANITANSEARCH
# sleep 0.5
anitansearch job[:value]
when JOB_NOSUBVIDEO
# sleep 0.6
nosubvideo job[:value]
when JOB_ANITANVIDEO
# sleep 0.6
anitanvideo job[:value]
when JOB_CONVERT
convert job[:value]
when JOB_DOWNLOADVIDEO
downloadvideo job[:value]
end
end
# anisoku top
def anisokutop(url)
req = EM::HttpRequest.new(
url,
connect_timeout: 5000, inactivity_timeout: 5000
).get
req.errback { @fetching -= 1 }
req.callback do
page = Nokogiri::HTML(req.response)
page.css('.Top_info div ul li a').each do |a|
next unless a.attributes['title'] &&
a.attributes['title'].value =~ /更新状況/
@queue.push(kind: JOB_KOUSINPAGE, value: a.attributes['href'].value)
end
@fetching -= 1
end
end
# anisoku kousin
def anisokukousin(url)
# puts 'anisokukousin : ' + url
req = EM::HttpRequest.new(
url,
connect_timeout: 5000, inactivity_timeout: 5000
).get
req.errback { @fetching -= 1 }
req.callback do
page = Nokogiri::HTML(req.response)
page.css('ul').each do |ul|
next unless ul.attributes['type'] &&
ul.attributes['type'].value == 'square'
ul.css('li a').each { |a| a2job a }
@fetching -= 1
end
end
end
# a to job
def a2job(a)
href = ''
href = a.attributes['href'].value unless a.attributes['href'].nil?
return unless href =~ %r{^http\:\/\/youtubeanisoku1\.blog106\.fc2\.com\/blog-entry-.+?\.html$}
title = a.attributes['title'].value if a.attributes['title']
title = a.text unless title
return if title =~ /更新状況/
return unless title =~ /^.+$/
title = title.delete(':').delete('.').delete(' ').delete('/')
title = title.delete('#').delete('(').delete(')')
return if @title[title]
return unless proseed(title)
@title[title] = true
puts 'do:' + title
return if @urls[href]
@urls[href] = :doing
@queue.push(kind: JOB_KOBETUPAGE, value: { title: title, href: href })
end
# anisoku kobetu
def anisokukobetu(value)
puts 'anisokukobetu : ' + value.to_s
req = EM::HttpRequest.new(
value[:href],
connect_timeout: 5000, inactivity_timeout: 5000
).get
req.errback { @fetching -= 1 }
req.callback do
page = Nokogiri::HTML(req.response)
unless page.title.nil?
t = page.title.delete(' ★ You Tube アニ速 ★').strip
t = t.delete('.').delete(' ').delete('/').delete('#')
t = t.delete('(').delete(')')
value[:title] = t if t
page.css('a').each do |a|
href = ''
href = a.attributes['href'].value unless a.attributes['href'].nil?
next unless href =~ %r{himado\.in\/\?s}
next unless a.children[0].text =~ /ひまわり/
next if @titles[value[:title]]
@titles[value[:title]] = :pedinding
@queue.push(
kind: JOB_ANITANSEARCH,
value: { title: value[:title], href: href }
)
end
end
@fetching -= 1
end
end
def anitansearch(value)
puts 'himadosearch : ' + value.to_s # if @debug
values = []
value[:href] = value[:href].gsub('%WWW', 'WWW')
begin
req = EM::HttpRequest.new(
value[:href],
connect_timeout: 5000, inactivity_timeout: 5000
).get
rescue => ex
p ex
end
req.errback do |client|
@fetching -= 1
pp "get error event machine : #{client.inspect}"
puts "err #{value[:href]}"
end
req.callback do
page = Nokogiri::HTML(req.response)
count = 5
#page.css(".thumbtitle a[rel='nofollow']").each do |a|
page.css(".thumbtitle a").each do |a|
href = 'http://himado.in'
href += a.attributes['href'].value unless a.attributes['href'].nil?
if @himado[href]
puts '*' * 80
puts "already fetched #{href} skip"
next
end
break if count.negative?
count -= 1
episode = a.attributes['title'].value.delete('.').delete(' ')
episode = episode.delete(' ').delete('#').delete(':').delete('第')
episode = episode.delete('話').delete('/')
unless episode =~ /アニメPV集/ || episode =~ /エヴァンゲリオン新劇場版:序/
hash = { title: value[:title], episode: episode, href: href }
values << hash
end
end
@queue.push(kind: JOB_ANITANVIDEO, value: values)
@fetching -= 1
end
end
def anitanvideo(value)
puts 'hiamdovideo : ' + value.to_s # if @debug
value.each do |val|
fetched = false
path = mkfilepath val[:title], val[:episode]
path = path.delete('<u>').delete('\'')
pathmp4 = path.gsub(/flv$/, 'mp4')
targetpath = if File.exist?(path)
path
else
pathmp4
end
if File.exist?(targetpath) && File.size(targetpath) > 1024 * 1024 * 2
fetched = true
end
fetched = true if @candidate[path]
@candidate[path] = :pending
if fetched
@fetching -= 1
next
end
@fetching += 1
url = get_url(val)
puts "enqueue #{path}"
if url
@queue.push(kind: JOB_DOWNLOADVIDEO,
value: { url: url, path: path, low: 10_000, orig_url: val[:href] })
end
end
@fetching -= 1
end
def get_url(val)
url = false
@session.visit val[:href]
begin
a = @session.find('video')['src']
url = URI.unescape(a)
rescue => e1
p e1
end
begin
if url == false
flashvars = @session.find('#playerswf')['flashvars']
flashvars =~ /'url='(.*?)' sou/
url_bare = Regexp.last_match[1]
url = URI.unescape(url_bare)
end
rescue => e2
p e2
end
begin
if url == false
@session.execute_script '$(\'#movie_title\').attr(\'src\',ary_spare_sources.spare[1].src);'
src = @session.find('#movie_title')['src']
url = URI.unescape(src)
end
rescue => e3
p e3
end
return url
rescue => ex
pp ex
return false
end
def downloadvideo(val)
url = val[:url]
path = val[:path]
_size = val[:low]
orig_url = val[:orig_url]
puts 'downloadvideo : ' + path
return if @downloads[path]
@downloads[path] = :go
path = path.delete('<u>')
pathmp4 = path.gsub(/flv$/, 'mp4')
if File.exist?(path) || File.exist?(path + '.mp4') || File.exist?(pathmp4)
return
end
puts "download start: #{url} - #{path}"
@downloads[path] = 'start'
if @usecurl
@fetching += 1
if @ffmpeg
path2 = path.gsub(/flv$/, 'mp4')
command = "curl -# -L '#{url}' "
command += '| ffmpeg -threads 4 -y -i - -vcodec copy -acodec copy '
command += "'#{path2}' &"
puts command
system command
@fetching -= 1
puts '#' * 80
puts "orig_url: #{orig_url}"
open_db do |db|
db.execute(@sql, name: (File.basename path2), path: path2, url: orig_url)
end
else
command = "curl -# -L -R -o '#{path}' '#{url}' &"
open_db do |db|
db.execute(@sql, name: (File.basename path2), path: path2, url: orig_url)
end
puts command
system command
@fetching -= 1
end
@downloads[path] = 'complete'
end
rescue => ex
p ex
end
def mkfilepath(title, episode)
t = title.tr('(', '(').tr(')', ')').tr('.', '').tr(' ', '').tr('/', '')
t = t.tr(' ', '').delete('#').delete(':').delete(':')
t = t.tr('!', '!').tr('+', '+')
mkdirectory t
episode = episode.gsub(/\[720p\]/, '').tr('?', '?')
episode = episode.gsub(/高画質/, '').gsub(/QQ/, '').delete('[').delete(']')
episode = episode.delete('」').delete('「').delete('+').tr('(', '(')
episode = episode.tr(')', ')').tr('!', '!')
episode = episode.tr('!', '!').slice(0, 60)
DOWNLOADDIR + '/' + t + '/' + episode + '.flv'
end
def mkdirectory(title)
Dir.mkdir DOWNLOADDIR + '/' + title
rescue => ex
p ex
end
def mkgifpath(path)
filename = File.basename(path).gsub(/flv$/, 'gif').gsub(/mp4$/, 'gif')
'/var/smb/sdc1/video/tmp/' + filename
end
def proseed(title)
return true if title =~ /./
# return true
# return true if title =~ /CREAT/ || title =~ /kurasika/
end
end
# same content ffmpeg convert
# Crawler.new(ffmpeg: false,debug: false,usecurl: true).run
Crawler.new(ffmpeg: true, debug: true, usecurl: true).run
|
class Api::V1::TagsController < ApplicationController
before_action :authenticate_with_token!, only: [:create, :update, :destroy]
respond_to :json
def index
unless params[:project].nil?
tags = Project.find(params[:project]).tags
end
render json: tags
end
def create
tag = Tag.new(create_params)
if tag.save
render json: tag, status: 201
else
render json: { errors: tag.errors }, status: 422
end
end
def update
tag = Tag.find(params[:id])
if tag.update(update_params)
render json: tag, status: 200
else
render json: { errors: tag.errors }, status: 422
end
end
def destroy
tag = Tag.find(params[:id])
tag.destroy
head 204
end
private
def create_params
params.require(:tag).permit(:name, :color, :project_id)
end
def update_params
params.require(:tag).permit(:name, :color)
end
end
|
class IndexJob < ActiveJob::Base
queue_as :lagottino
def perform(obj)
logger = Logger.new(STDOUT)
obj.__elasticsearch__.index_document
logger.info "Indexing event #{obj.uuid}."
end
end |
class RenamePhotoUrlToImage < ActiveRecord::Migration[5.0]
def change
rename_column :users, :photourl, :image
end
end
|
class SpeaksController < ApplicationController
def new
@speak = Speak.new
end
def create
@speak = Speak.create(create_params)
unless @speak.save
render action: :new
end
end
def show
@speak = Speak.find(params[:id])
@comments = @speak.comments.order('created_at DESC')
end
def edit
@speak = Speak.find(params[:id])
end
def update
# if st_user_signed_in?
speak = Speak.find(params[:id])
if current_st_user.id == speak.st_user_id
speak.update(update_params)
end
# end
end
def destroy
@speak = Speak.find(params[:id])
if st_user_signed_in?
@speak.destroy if current_st_user.id == @speak.st_user_id
end
end
private
def create_params
params.require(:speak).permit(:text,:field,:subject).merge(st_user_id: current_st_user.id)
end
def update_params
params.require(:speak).permit(:text,:field,:subject)
end
end
|
require 'test_helper'
class CallRoutesControllerTest < ActionController::TestCase
setup do
@call_route = call_routes(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:call_routes)
end
test "should get new" do
get :new
assert_response :success
end
test "should create call_route" do
assert_difference('CallRoute.count') do
post :create, call_route: @call_route.attributes
end
assert_redirected_to call_route_path(assigns(:call_route))
end
test "should show call_route" do
get :show, id: @call_route.to_param
assert_response :success
end
test "should get edit" do
get :edit, id: @call_route.to_param
assert_response :success
end
test "should update call_route" do
put :update, id: @call_route.to_param, call_route: @call_route.attributes
assert_redirected_to call_route_path(assigns(:call_route))
end
test "should destroy call_route" do
assert_difference('CallRoute.count', -1) do
delete :destroy, id: @call_route.to_param
end
assert_redirected_to call_routes_path
end
end
|
require 'rubygems'
require 'highline/import'
class PersFizPage
def initialize(session)
@session = session
end
def fill_login_field
puts 'Enter your login: '
login = gets.chomp
@session.find(:xpath, "//input[@id='UserId']").set "#{login}"
end
def fill_password_field
password = ask("Enter your password: ") { |q| q.echo = "*" }
@session.find(:xpath, "//input[@id='Password']").set "#{password}"
end
def enter_system_click
@session.find(:xpath, "//input[@name='loginbutton']").click
end
end |
class CreateBookings < ActiveRecord::Migration[5.1]
def change
create_table :bookings do |t|
t.date :checked_in
t.date :checked_out
t.references :client, foreign_key: true
t.integer :guest
t.float :total_amount
t.references :booking_status, foreign_key: true
t.timestamps
end
end
end
|
require 'spec_helper'
describe Address do
it { should have_many(:users) }
it { should have_many(:snippets) }
it { should have_many(:languages) }
it { should validate_uniqueness_of(:ip) }
end
|
class TracksController < ApplicationController
resources_controller_for :track
before_filter :show_tracks
def edit
@track = find_resource
# if a current language version doesn't exist, clone, save and redirect...
if @track.language_id != @language_id.to_i
track = @current_conference.tracks.find_by_language_id(@language_id)
unless track
track = @track.clone
track.language_id = @language_id
track.save
end
redirect_to edit_track_path(track)
return
end
end
def index
@tracks = @current_conference.get_tracks(logged_in_and_admin)
@presentations = show_presentations? ? @current_conference.get_last_presentations(logged_in_and_admin) : []
@presenters = show_presenters? ? @current_conference.get_last_presenters(logged_in_and_admin) : []
end
def show
@track = find_resource
# if a current language version doesn't exist, clone, save and redirect...
if @track.language_id != @language_id.to_i
track = @track.find_translation(@language_id)
if track
redirect_to track_path(track), :status => :moved_permanently
return
end
end
@presentations = show_presentations? ? @track.get_presentations(@current_conference.language_id,logged_in_and_admin) : []
@presenters = show_presenters? ? @track.get_presenters(@current_conference.language_id,logged_in_and_admin) : []
end
protected
def show_tracks
unless show_tracks?
head :bad_request
return
end
end
end
|
# -*- coding: utf-8 -*-
require_relative 'utils'
require 'delayer'
require 'delayer/deferred'
require 'set'
require 'thread'
require 'timeout'
# 渡されたブロックを順番に実行するクラス
class SerialThreadGroup
QueueExpire = Class.new(Timeout::Error)
# ブロックを同時に処理する個数。最大でこの数だけThreadが作られる
attr_accessor :max_threads
@@force_exit = false
def initialize(max_threads: 1, deferred: nil)
@lock = Monitor.new
@queue = Queue.new
@max_threads = max_threads
@deferred_class = deferred
@thread_pool = Set.new
end
# 実行するブロックを新しく登録する
# ==== Args
# [proc] 実行するブロック
def push(proc=nil, &block)
proc ||= block
promise = @deferred_class && @deferred_class.new(true)
return promise if @@force_exit
@lock.synchronize{
@queue.push(proc: proc, promise: promise)
new_thread if 0 == @queue.num_waiting and @thread_pool.size < max_threads }
promise
end
alias new push
# 処理中なら真
def busy?
@thread_pool.any?{ |t| :run == t.status.to_sym } end
# 全てのserial threadの実行をキャンセルする。終了時の処理用
def self.force_exit!
notice "all Serial Thread Group jobs canceled."
@@force_exit = true end
private
# Threadが必要なら一つ立ち上げる。
# これ以上Threadが必要ない場合はtrueを返す。
def flush
return true if @@force_exit
@lock.synchronize{
@thread_pool.delete_if{ |t| not t.alive? }
if @thread_pool.size > max_threads
return true
elsif 0 == @queue.num_waiting and @thread_pool.size < max_threads
new_thread end }
false end
def new_thread
return if @@force_exit
@thread_pool << Thread.new do
while node = Timeout.timeout(1, QueueExpire){ @queue.pop }
break if @@force_exit
result = node[:proc].call
node[:promise].call(result) if node[:promise]
break if flush
debugging_wait
Thread.pass
end
rescue QueueExpire, ThreadError
rescue Object => e
if node[:promise]
node[:promise].fail(e)
else
error e
abort
end
ensure
@lock.synchronize do
@thread_pool.delete(Thread.current)
end
end
end
end
# SerialThreadGroup のインスタンス。
# 同時実行数は1固定
SerialThread = SerialThreadGroup.new
|
require 'test_helper'
class FriendsControllerTest < ActionDispatch::IntegrationTest
setup do
@friend = friends(:one)
end
test "should get index" do
get friends_url, as: :json
assert_response :success
end
test "should create friend" do
assert_difference('Friend.count') do
post friends_url, params: { friend: { birthday: @friend.birthday, name: @friend.name, visit_interval: @friend.visit_interval } }, as: :json
end
assert_response 201
end
test "should show friend" do
get friend_url(@friend), as: :json
assert_response :success
end
test "should update friend" do
patch friend_url(@friend), params: { friend: { birthday: @friend.birthday, name: @friend.name, visit_interval: @friend.visit_interval } }, as: :json
assert_response 200
end
test "should destroy friend" do
assert_difference('Friend.count', -1) do
delete friend_url(@friend), as: :json
end
assert_response 204
end
end
|
class AttachmentUploader < CarrierWave::Uploader::Base
include ActiveModel::Validations
storage :file
validates :name, presence: true
validates :attachment, presence: true
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(pdf doc htm html docx txt rar zip)
end
end
|
class RenameDnsHostAaaaRecordToDnsHostIpAaaaRecord < ActiveRecord::Migration
def up
rename_table :dns_host_aaaa_records, :dns_host_ip_aaaa_records
end
def down
rename_table :dns_host_ip_aaaa_records, :dns_host_aaaa_records
end
end
|
class ChangeUserIdInMembershipsToInteger < ActiveRecord::Migration[6.0]
def change
remove_column :memberships, :user_id, :string
add_column :memberships, :user_id, :integer
end
end
|
class Location < ActiveRecord::Base
scope :first, -> { order('created_at').first }
scope :last, -> { order('created_at DESC').first }
belongs_to :category, foreign_key: 'category_uuid'
validates :category_uuid, presence: true
validates :name, presence: true
# validates_associated :category
def self.permitted_attributes
new.attributes.keys.reject{|k| k =~ /^(uu)?id$/ || k =~ /^(cre|upd)ated_at$/}.map(&:to_sym)
end
def to_search
CGI.escape("#{name},#{street},#{house_no},#{zip},#{city}")
end
def maps_url mode = 'place'
"https://www.google.com/maps/embed/v1/#{mode}?key=#{ENV['MAPS_KEY']}&q=#{to_search}"
end
end
|
require_relative '../errors'
module Tokenizer
module Reader
class BaseReader
def initialize
@chunk = ''
@line_num = 0
@output_buffer = []
@is_input_closed = false
end
def next_chunk(options = { consume?: true })
read until finished? || !@output_buffer.empty?
options[:consume?] ? @output_buffer.shift : @output_buffer.first
end
# Return the chunk if `skip_whitespace?` is false or the chunk is not
# whitespace. Otherwise, read until the first non-whitespace is found
# (The buffer is searched on each iteration, but the actual number of
# elements will be at most <= 2)
def peek_next_chunk(options = { skip_whitespace?: true })
chunk = next_chunk consume?: false
return chunk.to_s unless options[:skip_whitespace?] && chunk =~ /\A[#{WHITESPACE}]+\z/
read until !(chunk = non_whitespace_chunk_from_buffer).nil? || @is_input_closed
chunk.to_s
end
def finished?
@is_input_closed && @output_buffer.empty?
end
def line_num
@line_num - @output_buffer.count { |chunk| chunk == "\n" }
end
private
def read
char = next_char
if char.nil?
close_input
else
# rubocop:disable Style/CaseEquality
reader_method = {
'「' => :read_string_begin,
'」' => :read_string_close,
"\n" => :read_single_separator,
/[#{COMMA}#{QUESTION}#{BANG}]/ => :read_single_separator,
'※' => :read_inline_comment,
/[#{COMMENT_BEGIN}]/ => :read_comment_begin,
/[#{WHITESPACE}]/ => :read_whitespace,
'\\' => :read_line_break,
} .find { |match, method| break method if match === char } || :read_other
# rubocop:enable Style/CaseEquality
should_continue_reading = send reader_method, char
return if should_continue_reading
end
store_chunk
end
# Continue reading in case the string is followed by a particle.
def read_string_begin(char)
store_chunk
@chunk = char + read_until('」')
true
end
def read_string_close(char)
raise Errors::MalformedString, @chunk + char
end
def read_single_separator(char)
store_chunk
@chunk = char
false
end
# Discard until EOL.
def read_inline_comment(_char)
read_until "\n", inclusive?: false
false
end
# Discard until end of block.
# Continue reading in case the block comment was in the middle of a chunk.
def read_comment_begin(_char)
read_until(/[#{COMMENT_CLOSE}]/)
true
end
def read_whitespace(char)
store_chunk
@chunk = char + read_until(/[^#{WHITESPACE}]/, inclusive?: false)
false
end
# Discard following whitespace, consume newline if found.
def read_line_break(_char)
store_chunk
read_until(/[^#{WHITESPACE}]/, inclusive?: false)
char = next_char
raise Errors::UnexpectedLineBreak unless char == "\n"
false
end
def read_other(char)
@chunk += char
true
end
def read_until(match, options = { inclusive?: true })
char = nil
chunk = ''
loop do
char = next_char_in_range match, chunk, options
chunk += char
# if reading a string and this is an unescaped start of interpolation:
# read the entire substitution range
chunk += read_until('】') if interpolation_open? match, chunk
break if char.empty? || char_matches?(char, match, chunk)
end
return chunk if options[:inclusive?]
restore_char char
chunk.chomp char
end
def store_chunk
return if @chunk.empty?
@output_buffer << @chunk.clone
@chunk.clear
end
def close_input
@is_input_closed = true
end
def next_char
char = read_char
@line_num += 1 if char == "\n"
char
end
def read_char
raise
end
def restore_char(char)
unread_char char
@line_num -= 1 if char == "\n"
end
def unread_char
raise
end
def next_char_in_range(match, chunk, options)
char = next_char.to_s
# raise an error if match was never found before EOF
raise_unfinished_range_error match, chunk if char.empty? && options[:inclusive?]
char
end
def interpolation_open?(match, chunk)
match == '」' && chunk.match(/(\\*【)\z/)&.captures&.first&.length.to_i.odd?
end
def char_matches?(char, match, chunk)
return char =~ match if match.is_a? Regexp
char == match && (match != '」' || unescaped_closing_quote?(chunk))
end
def unescaped_closing_quote?(chunk)
(chunk.match(/(\\*)」\z/)&.captures&.first&.length || 0).even?
end
def non_whitespace_chunk_from_buffer
@output_buffer.find { |chunk| chunk !~ /\A[#{WHITESPACE}]+\z/ }
end
def raise_unfinished_range_error(match, chunk)
raise Errors::UnclosedString, chunk if match == '」'
raise Errors::UnclosedBlockComment if match == /[#{COMMENT_CLOSE}]/
raise Errors::UnexpectedEof
end
end
end
end
|
class ZoneController < ApplicationController
skip_before_action :verify_authenticity_token
attr_reader :zones
include ShippingZoneConcern
BODY = {name: "FBA Shipping by ByteStand",
type: "carrier_3",
settings: {carrier_options: {delivery_services: [], packaging: []}},
enabled: true,
handling_fees:{"fixed_surcharge"=>0}}.to_json
def return_zone_info
get_shipping_zones(current_store)
zones = current_store.zones
render json: zones
end
def receive_zone_info
@zones = return_zones_from_params
get_shipping_methods_for_zones(@zones)
add_rate_to_shipping_zone
update_selected_zones
update_not_selected_zones
head :ok
end
private
def return_zones_from_params
just_zones = []
unless params["zone_info"][0].is_a?(Fixnum)
params["zone_info"].each do |zone_id|
just_zones << zone_id["value"]
end
return just_zones
else
return params["zone_info"]
end
end
def get_shipping_methods_for_zones(zones)
zones.each do |zone|
shipping_methods = HTTParty.get(
"https://api.bigcommerce.com/stores/#{current_store.bc_hash}/v2/shipping/zones/#{zone}/methods",
:headers => create_request_headers(current_store))
does_fba_shipping_exist_in_zone(shipping_methods, zone)
end
end
def does_fba_shipping_exist_in_zone(shipping_methods, zone)
shipping_methods.each do |method|
if method["type"] == "carrier_3"
remove_fba_ship(method["id"], zone)
end
end
end
def remove_fba_ship(shipping_method_id, zone)
HTTParty.delete(
"https://api.bigcommerce.com/stores/#{current_store.bc_hash}/v2/shipping/zones/#{zone}/methods/#{shipping_method_id}",
:headers => create_request_headers(current_store))
end
def add_rate_to_shipping_zone
zones.each do |zone|
HTTParty.post(
"https://api.bigcommerce.com/stores/#{current_store.bc_hash}/v2/shipping/zones/#{zone}/methods",
:body => BODY,
:headers => create_request_headers(current_store))
end
end
def update_selected_zones
zones.each do |selected_zone_id|
current_zone = current_store.zones.find_by(bc_zone_id: selected_zone_id)
current_zone.update(selected: true)
end
end
def update_not_selected_zones
all_zone_ids = current_store.zones.pluck(:bc_zone_id)
zones_to_de_select = all_zone_ids - zones
get_shipping_methods_for_zones(zones_to_de_select)
zones_to_de_select.each do |set_zone_to_false|
false_zone = current_store.zones.find_by(bc_zone_id: set_zone_to_false)
false_zone.update(selected: false)
end
end
end |
# == Schema Information
# Schema version: 58
#
# Table name: sds_sail_users
#
# id :integer(11) not null, primary key
# portal_id :integer(11)
# first_name :string(60) default(""), not null
# last_name :string(60) default(""), not null
# uuid :string(36) default(""), not null
# created_at :datetime
# updated_at :datetime
#
class SailUser < ActiveRecord::Base
validates_presence_of :first_name, :last_name
belongs_to :portal
has_many :workgroup_memberships
has_many :notification_scopes, :as => :notifier
has_many :notification_listeners, :as => :notifier, :through => :notification_scopes
# this creates the following possible search
# workgroups = user.workgroups?
has_many :workgroups, :through => :workgroup_memberships, :select => 'DISTINCT workgroups.*'
# see: http://github.com/mislav/will_paginate/wikis/simple-search
def self.search(search, page, portal)
paginate(:per_page => 20, :page => page, :conditions => ['(first_name like ? or last_name like ?) and portal_id = ?', "%#{search}%","%#{search}%", portal.id], :order => 'created_at DESC')
end
def workgroup?
self.workgroups.count != 0
end
def workgroup
self.workgroups.sort {|a,b| a.id <=> b.id}[0]
end
before_create :generate_uuid
def generate_uuid
self.uuid = UUID.timestamp_create().to_s
end
def name
"#{first_name} #{last_name}"
end
def identifier
"#{name}"
end
end
|
Rails.application.routes.draw do
resources :subjects do |s|
member do
get :activate
get :deactivate
end
resources :groups do |g|
resources :instructor_answers
resources :posts do |p|
resources :discussions
end
end
resources :topics
end
root to: 'subjects#index'
devise_for :users
resources :users
end
|
class AddValidtimeToEeKonto < ActiveRecord::Migration
def change
add_column :EEKonto, :GueltigVon, :datetime
add_column :EEKonto, :GueltigBis, :datetime
end
end
|
class Payment < ApplicationRecord
validates_numericality_of :payment_amount, :greater_than => 0
end
|
require 'spec_helper'
Run.all :read_only do
describe Pacer::Wrappers::EdgeWrapper do
use_pacer_graphml_data :read_only
let(:e_exts) { [Tackle::SimpleMixin, TP::Wrote] }
let(:e_wrapper_class) { Pacer::Wrappers::EdgeWrapper.wrapper_for e_exts }
subject { e_wrapper_class }
it { should_not be_nil }
it { subject.route_conditions(graph).should == { label: 'wrote' } }
its(:extensions) { should == e_exts }
describe 'instance' do
subject do
e_wrapper_class.new graph, pangloss_wrote_pacer.element
end
it { should_not be_nil }
its(:element) { should_not be_nil }
it { should == pangloss_wrote_pacer }
it { should_not equal pangloss_wrote_pacer }
its(:element_id) { should == pangloss_wrote_pacer.element_id }
its(:extensions) { should == e_exts }
describe 'with more extensions added' do
subject { e_wrapper_class.new(graph, pacer.element).add_extensions([Pacer::Utils::TSort]) }
its(:class) { should_not == e_wrapper_class }
its(:extensions) { should == e_exts + [Pacer::Utils::TSort] }
end
end
end
describe Pacer::Wrappers::EdgeWrapper do
use_simple_graph_data
describe '#e' do
subject { e0.e }
it { should be_an_edges_route }
its(:element_type) { should == :edge }
end
describe '#add_extensions' do
context 'no extensions' do
subject { e0.add_extensions([]) }
its('extensions.to_a') { should == [] }
its(:class) { should == graph.base_edge_wrapper }
end
context 'with extensions' do
subject { e0.add_extensions([Tackle::SimpleMixin]) }
its('extensions.to_a') { should == [Tackle::SimpleMixin] }
it { should be_a(Pacer::Wrappers::ElementWrapper) }
it { should be_a(Pacer::Wrappers::EdgeWrapper) }
it { should_not be_a(Pacer::Wrappers::VertexWrapper) }
describe '#e' do
subject { e0.add_extensions([Tackle::SimpleMixin]).e }
its('extensions.to_a') { should == [Tackle::SimpleMixin] }
it { should be_an_edges_route }
it { should be_a(Tackle::SimpleMixin::Route) }
end
end
end
subject { e0 }
its(:graph) { should equal(graph) }
its(:display_name) { should == "#{ v0.element_id }-links-#{ v1.element_id }" }
its(:inspect) { should == "#<E[#{ e0.element_id }]:#{ v0.element_id }-links-#{ v1.element_id }>" }
context 'with label proc' do
before do
graph.edge_name = proc { |e| "some name" }
end
its(:display_name) { should == "some name" }
its(:inspect) { should == "#<E[#{ e0.element_id }]:some name>" }
end
context '', :transactions => true do
it { should_not == e1 }
it { should == e0 }
it { should_not == v0 }
end
end
end
Run.all :read_write do
use_simple_graph_data
describe Pacer::Wrappers::EdgeWrapper do
describe '#delete!' do
before do
@edge_id = e0.element_id
e0.delete!
c = example.metadata[:graph_commit]
c.call if c
end
it 'should be removed' do
graph.edge(@edge_id).should be_nil
end
end
describe '#reverse!' do
it 'should remove the old element' do
id = e0.element_id
e0.reverse!
c = example.metadata[:graph_commit]
c.call if c
graph.edge(id).should be_nil
end
it 'should create a new element with the same label' do
label = e0.label
new_e = e0.reverse!
new_e.label.should == label
end
it 'should not have the same element_id' do
id = e0.element_id
new_e = e0.reverse!
new_e.element_id.should_not == id
end
it 'should reverse the direction' do
iv = e0.in_vertex
ov = e0.out_vertex
new_e = e0.reverse!
new_e.in_vertex.should == ov
new_e.out_vertex.should == iv
end
it 'should change the label' do
new_e = e0.reverse! label: 'hello_there'
new_e.label.should == 'hello_there'
end
it 'should reuse the element id' do
return if graph_name == 'mcfly'
unless graph.features.ignoresSuppliedIds
e0
c = example.metadata[:graph_commit]
c.call if c
id = e0.element_id
new_e = e0.reverse! reuse_id: true
new_e.element_id.should == id.to_s
end
end
end
contexts(
'into new tg' => proc {
let(:dest) { Pacer.tg }
},
'into graph2' => proc {
let(:dest) {
c = example.metadata[:graph2_commit]
c.call() if c
graph2.v.delete!
c.call() if c
graph2
}
}) do
describe '#clone_into' do
context 'including vertices' do
subject do
e0
c = example.metadata[:graph_commit]
c.call if c
e0.clone_into(dest, :create_vertices => true)
end
its('element_id.to_s') { should == e0.element_id.to_s unless graph.features.ignoresSuppliedIds }
its(:label) { should == 'links' }
its(:graph) { should equal(dest) }
its('in_vertex.properties') { should == e0.in_vertex.properties }
its('out_vertex.properties') { should == e0.out_vertex.properties }
end
context 'without vertices' do
context 'not existing' do
subject { e0.clone_into(dest) rescue nil }
it { should be_nil }
end
context 'existing' do
before do
v0; v1; e0
c = example.metadata[:graph_commit]
c.call if c
v0.clone_into(dest)
v1.clone_into(dest)
end
subject { e0.clone_into(dest) }
its('element_id.to_s') { should == e0.element_id.to_s unless graph.features.ignoresSuppliedIds }
its(:label) { should == 'links' }
its(:graph) { should equal(dest) }
its('in_vertex.properties') { should == e0.in_vertex.properties }
its('out_vertex.properties') { should == e0.out_vertex.properties }
end
end
end
describe '#copy_into' do
before do
v0; v1; e0
c = example.metadata[:graph_commit]
c.call if c
end
subject do
v0.clone_into(dest)
v1.clone_into(dest)
e0.copy_into(dest)
end
its(:label) { should == 'links' }
its(:graph) { should equal(dest) }
its('in_vertex.properties') { should == e0.in_vertex.properties }
its('out_vertex.properties') { should == e0.out_vertex.properties }
end
end
end
end
|
class CreateTempusers < ActiveRecord::Migration
def change
create_table :tempusers do |t|
t.string :pku_id
t.timestamps
end
end
end
|
module Fog
module Compute
class ProfitBricks
class Real
# Retrieves the attributes of a given Firewall Rule
#
# ==== Parameters
# * datacenter_id<~String> - UUID of the datacenter
# * server_id<~String> - UUID of the server
# * nic_id<~String> - UUID of the NIC
# * firewall_rule_id<~String> - UUID of the firewall rule
#
# ==== Returns
# * response<~Excon::Response>:
# * body<~Hash>:
# * id<~String> - The resource's unique identifier
# * type<~String> - The type of the created resource
# * href<~String> - URL to the object’s representation (absolute path)
# * metadata<~Hash> - Hash containing the Firewall Rule metadata
# * createdDate<~String> - The date the resource was created
# * createdBy<~String> - The user who created the resource
# * etag<~String> - The etag for the resource
# * lastModifiedDate<~String> - The last time the resource has been modified
# * lastModifiedBy<~String> - The user who last modified the resource
# * state<~String> - Firewall Rule state
# * properties<~Hash> - Hash containing the Firewall Rule properties
# * name<~String> - The name of the Firewall Rule
# * protocol<~String> - The protocol for the rule: TCP, UDP, ICMP, ANY
# * sourceMac<~String> - Only traffic originating from the respective MAC address is allowed.
# Valid format: aa:bb:cc:dd:ee:ff. Value null allows all source MAC address
# * sourceIp<~String> - Only traffic originating from the respective IPv4 address is allowed. Value null allows all source IPs
# * targetIp<~String> - In case the target NIC has multiple IP addresses, only traffic directed
# to the respective IP address of the NIC is allowed. Value null allows all target IPs
# * icmpCode<~String> - Defines the allowed code (from 0 to 254) if protocol ICMP is chosen. Value null allows all codes
# * icmpType<~String> - Defines the allowed type (from 0 to 254) if the protocol ICMP is chosen. Value null allows all types
# * portRangeStart<~String> - Defines the start range of the allowed port (from 1 to 65534) if protocol TCP or UDP is chosen.
# Leave portRangeStart and portRangeEnd value null to allow all ports
# * portRangeEnd<~String> - Defines the end range of the allowed port (from 1 to 65534) if the protocol TCP or UDP is chosen.
# Leave portRangeStart and portRangeEnd null to allow all ports
#
# {ProfitBricks API Documentation}[https://devops.profitbricks.com/api/cloud/v2/#get-firewall-rule]
def get_firewall_rule(datacenter_id, server_id, nic_id, firewall_rule_id)
request(
:expects => [200],
:method => "GET",
:path => "/datacenters/#{datacenter_id}/servers/#{server_id}/nics/#{nic_id}/firewallrules/#{firewall_rule_id}?depth=5"
)
end
end
class Mock
def get_firewall_rule(datacenter_id, server_id, nic_id, firewall_rule_id)
if firewall_rule = data[:firewall_rules]['items'].find do |fwr|
fwr["datacenter_id"] == datacenter_id && fwr["server_id"] == server_id && fwr["nic_id"] == nic_id && fwr["id"] == firewall_rule_id
end
else
raise Fog::Errors::NotFound, "The requested resource could not be found"
end
response = Excon::Response.new
response.status = 200
response.body = firewall_rule
response
end
end
end
end
end
|
class OrderItem < ApplicationRecord
belongs_to :product
belongs_to :order
enum making_status: {
制作不可: 0,
制作待ち: 1,
制作中: 2,
制作完了: 3
}
end
|
require 'rails_helper'
feature 'Delete question', %Q{
As a user
I want to delete a question
So that I can delete duplicate questions
} do
# Acceptance Criteria
# - I must be able delete a question from the question edit page
# - I must be able delete a question from the question details page
# - All answers associated with the question must also be deleted scenario
scenario 'user deletes question from show view' do
question = FactoryGirl.create(:question)
visit '/'
click_link(question.title)
click_link('Delete')
expect(page).to_not have_content(question.title)
end
scenario 'user deletes question from edit view' do
question = FactoryGirl.create(:question)
visit '/'
click_link(question.title)
click_link('Edit Question')
click_link('Delete')
expect(page).to_not have_content(question.title)
end
end
|
require 'json'
require 'webrick'
class Flash
def initialize(req)
@req = req
found_cookie = find_cookie
@cookie = found_cookie ? JSON.parse(found_cookie.value) : {}
process_cookie
end
def process_cookie
@cookie = {} if @cookie["_flag"]
end
def find_cookie
@req.cookies.find { |cookie| cookie.name == "_rails_lite_flash" }
end
def [](key)
@cookie[key]
end
def []=(key, val)
@cookie[key] = val
@cookie["_flag"] = true
end
def store_flash(res)
res.cookies << WEBrick::Cookie.new("_rails_lite_flash", @cookie.to_json)
end
end
|
# tell rails to use rspec format whenever it generates test code
Rails.application.config.generators do |g|
g.test_framework :rspec, :view_specs => false,
:controller_specs => false,
:request_specs => false,
:routing_specs => false
end
|
class UnitTestSetup
Version = '1.3.7'
def initialize
@name = "Gems"
super
end
def require_files
#HACK: this is loading up our defaults file which causes tests to fail.
#the global is to stop that loading
$utr_runner=true
require 'rubygems'
end
def gather_files
test_dir = File.expand_path("Languages/Ruby/Tests/Libraries/RubyGems-#{Version}", ENV["DLR_ROOT"])
$LOAD_PATH << test_dir
# Note that the copy of minitest\unit.rb has a workaround at line 15 for http://redmine.ruby-lang.org/issues/show/1266
ENV["GEM_PATH"] = File.expand_path("External.LCA_RESTRICTED/Languages/Ruby/ruby19/lib/ruby/gems/1.9.1", ENV["DLR_ROOT"])
@all_test_files = Dir.glob("#{test_dir}/test_*.rb")
end
def sanity
# Do some sanity checks
sanity_size(50)
abort("Did not find some expected files...") unless @all_test_files.select { |f| f =~ /test_gem_config/ }.size > 0
sanity_version(Version, Gem::RubyGemsVersion)
warn("Some tests are expected to fail with 'ir.exe -D'. Do not use -D...") if $DEBUG
end
# test_gem_stream_ui.rb uses Timeout.timeout which can cause hangs as described in
# http://ironruby.codeplex.com/WorkItem/View.aspx?WorkItemId=4023
# Increase the timeout to reduce the chance of this occuring when other processes are
# also running (like with "irtests -p")
# require 'timeout'
# Timeout.instance_eval do
# alias :original_timeout :timeout
# def timeout(sec, klass=nil, &b) original_timeout(((sec == nil) ? sec : sec * 50), klass, &b) end
# end
def disable_tests
#
# TODO: is this still applicable?
#
#RubyGems-1_3_1-test\gemutilities.rb has a workaround
#for http://rubyforge.org/tracker/?func=detail&group_id=126&aid=24169&atid=575. However, the following
#test fails inspite of the workaround. So we check if %TMP% is something like
#C:\DOCUME~1\JANEDO~1\LOCALS~1\Temp
#if ENV['TMP'].include?('~')
# disable TestGemDependencyInstaller, :test_find_gems_with_sources_local
#end
disable_by_name %w{
test_self_prefix(TestGem)
test_invoke_with_help(TestGemCommand):
test_defaults(TestGemCommand):
test_invoke_with_options(TestGemCommand):
test_process_args_install(TestGemCommandManager)
test_process_args_update(TestGemCommandManager)
test_execute_build(TestGemCommandsCertCommand):
test_execute_certificate(TestGemCommandsCertCommand)
test_execute_private_key(TestGemCommandsCertCommand)
test_execute_sign(TestGemCommandsCertCommand)
test_execute_add(TestGemCommandsCertCommand)
test_execute(TestGemCommandsEnvironmentCommand)
test_no_user_install(TestGemCommandsInstallCommand)
test_install_security_policy(TestGemDependencyInstaller)
test_uninstall_doc_unwritable(TestGemDocManager)
test_self_build_fail(TestGemExtConfigureBuilder)
test_self_build(TestGemExtConfigureBuilder)
test_class_build(TestGemExtExtConfBuilder)
test_class_build_extconf_fail(TestGemExtExtConfBuilder)
test_sign_in_skips_with_existing_credentials(TestGemGemcutterUtilities)
test_sign_in_with_bad_credentials(TestGemGemcutterUtilities)
test_sign_in(TestGemGemcutterUtilities)
test_sign_in_with_host(TestGemGemcutterUtilities)
test_sign_in_with_other_credentials_doesnt_overwrite_other_keys(TestGemGemcutterUtilities)
test_generate_index(TestGemIndexer)
test_update_index(TestGemIndexer)
test_user_install_disabled_read_only(TestGemInstallUpdateOptions)
test_generate_bin_script_no_perms(TestGemInstaller)
test_generate_bin_symlink_no_perms(TestGemInstaller)
test_build_extensions_extconf_bad(TestGemInstaller)
test_self_open_signed(TestGemPackageTarOutput)
test_self_open(TestGemPackageTarOutput)
test_getc(TestGemPackageTarReaderEntry)
test_explicit_proxy(TestGemRemoteFetcher)
test_no_proxy(TestGemRemoteFetcher)
test_self_load_specification_utf_8(TestGemSourceIndex)
test_validate_empty_require_paths(TestGemSpecification)
test_validate_files(TestGemSpecification)
test_ask_for_password(TestGemStreamUI)
}
end
def disable_mri_only_failures
disable_by_name %w{
test_self_prefix(TestGem)
test_process_args_update(TestGemCommandManager)
test_process_args_install(TestGemCommandManager)
test_execute(TestGemCommandsEnvironmentCommand)
test_no_user_install(TestGemCommandsInstallCommand)
test_uninstall_doc_unwritable(TestGemDocManager)
test_self_build_has_makefile(TestGemExtConfigureBuilder)
test_self_build_fail(TestGemExtConfigureBuilder)
test_self_build(TestGemExtConfigureBuilder)
test_class_build(TestGemExtExtConfBuilder)
test_class_make(TestGemExtExtConfBuilder)
test_sign_in_with_host(TestGemGemcutterUtilities)
test_sign_in_skips_with_existing_credentials(TestGemGemcutterUtilities)
test_sign_in_with_other_credentials_doesnt_overwrite_other_keys(TestGemGemcutterUtilities)
test_sign_in_with_bad_credentials(TestGemGemcutterUtilities)
test_sign_in(TestGemGemcutterUtilities)
test_generate_index_modern(TestGemIndexer)
test_user_install_disabled_read_only(TestGemInstallUpdateOptions)
test_generate_bin_symlink_no_perms(TestGemInstaller)
test_generate_bin_script_no_perms(TestGemInstaller)
test_validate_files(TestGemSpecification)
test_validate_empty_require_paths(TestGemSpecification)
test_ask_for_password(TestGemStreamUI)
test_update_index(TestGemIndexer)
test_self_prefix(TestGem)
}
end
end
|
module TextToNoise
class Player
include Logging
SOUND_DIR = File.expand_path File.join( APP_ROOT, 'sounds' )
class SoundNotFound < StandardError
def initialize( sound_name )
super "Could not locate '#{sound_name}' in #{Rubygame::Sound.autoload_dirs}"
end
end
def initialize()
self.class.load_rubygame
Rubygame::Sound.autoload_dirs << SOUND_DIR
themes = Dir.new(SOUND_DIR).entries.reject { |e| e =~ /^[.]/ }
Rubygame::Sound.autoload_dirs.concat themes.map { |t| File.join SOUND_DIR, t }
@sounds = []
end
def play( sound_name )
sound = Rubygame::Sound[sound_name]
raise SoundNotFound, sound_name if sound.nil?
debug "Playing #{sound_name}"
sound.play :fade_out => 2
@sounds << sound
debug "#{@sounds.size} sounds in queue" if playing?
end
def playing?
@sounds = @sounds.select &:playing?
not @sounds.empty?
end
def sound_dirs()
Rubygame::Sound.autoload_dirs
end
def available_sounds()
Rubygame::Sound.autoload_dirs.map do |dir|
Dir[ "#{dir}/*.wav" ].map { |f| File.basename f }
end.flatten
end
def self.load_rubygame()
old_verbose, $VERBOSE = $VERBOSE, nil
old_stream, stream = $stdout.dup, $stdout
return if defined? Rubygame::Sound
stream.reopen '/dev/null'
stream.sync = true
begin
require 'rubygame'
rescue LoadError
require 'rubygems'
require 'rubygame'
end
raise "No Mixer found! Make sure sdl_mixer is installed." unless defined? Rubygame::Sound
ensure
$VERBOSE = old_verbose
stream.reopen(old_stream)
end
end
end
|
class UsersController < ApplicationController
def show
@user=User.find(params[:id])
end
def new
@user=User.new
end
def Post
@user=User.new(user_params)
if @user.save
redirect_to users_new_path
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:first_name,:country,:last_name,:user_name,:mobile_no,:Email_id,:password)
end
end
|
require 'rubygems'
require 'httpclient'
require 'yaml'
require 'CGI'
require 'json'
require 'parallel'
require File.dirname(__FILE__) + '/string_utils'
require File.dirname(__FILE__) + '/link_builder'
require File.dirname(__FILE__) + '/confluence_page'
require File.dirname(__FILE__) + '/feature_file'
require File.dirname(__FILE__) + '/test_bits'
class Cuki
CONFIG_PATH = 'config/cuki.yaml'
DEFAULT_CONTAINER = /h1\. Acceptance Criteria/
PRIMARY_HEADER = "h1\."
FEATURE_HEADER = "h2\."
SCENARIO_HEADER = "h6\."
FLAGS = {:skip_autoformat => '--skip-autoformat'}
def self.invoke(args)
new(args)
end
def initialize(args)
@args = args
validate_args
read_config
configure_http_client
@link_builder = LinkBuilder.new(@config['host'])
action = args.first
if args.include?(FLAGS[:skip_autoformat])
args.delete_if { |arg| FLAGS[:skip_autoformat] == arg }
@skip_autoformat = true
end
configure_pull_stubs
verify_project
file = args[1]
if file
id = mappings.invert[file]
terminate "could not get id for #{file}" unless id
pull_feature id, file
else
Parallel.map(mappings, :in_processes => 4) do |id, filepath|
pull_feature id, filepath
end
end
autoformat!
end
private
def verify_project
terminate "features folder not found" unless File.exists?('features')
puts "Verifying existing features"
`cucumber --dry-run -P`
terminate "Validation of existing features failed" unless 0 == $?
end
def read_config
terminate "No config file found at #{CONFIG_PATH}" unless File.exist?(CONFIG_PATH)
@config = YAML::load( File.open( CONFIG_PATH ) )
terminate "Host not found in #{CONFIG_PATH}" unless @config["host"]
terminate "Mappings not found in #{CONFIG_PATH}" unless @config["mappings"]
end
def configure_http_client
@client = HTTPClient.new
@client.ssl_config.set_trust_ca(ENV['CER']) if ENV['CER']
@client.ssl_config.set_client_cert_file(ENV['PEM'], ENV['PEM']) if ENV['PEM']
end
def pull_feature(id, filepath)
wiki_edit_link = @link_builder.edit(id)
puts "Downloading #{wiki_edit_link}"
response = @client.get wiki_edit_link
handle_multi response.body, id
end
def container
@config['container'] ||= DEFAULT_CONTAINER
end
def autoformat!
unless @skip_autoformat
`cucumber -a . --dry-run -P`
puts "Running autoformat"
end
end
def handle_multi response_body, id
confluence_page = ConfluencePage.new(response_body)
full_content = confluence_page.content
terminate "Could not find acceptance criteria container" unless full_content.match(container)
acceptance_criteria = full_content.split(container).last
if acceptance_criteria.include?(PRIMARY_HEADER)
acceptance_criteria = acceptance_criteria.split(/#{PRIMARY_HEADER}/).first
end
terminate "Could not match #{container} in #{id}" unless acceptance_criteria
scenario_titles = acceptance_criteria.scan(/#{FEATURE_HEADER} (.*)/).flatten
scenario_blocks = acceptance_criteria.split(/#{FEATURE_HEADER} .*/)
scenario_blocks.shift
puts "Warning: No scenarios found in doc #{id}" if scenario_titles.empty?
pretext = acceptance_criteria.split(/#{FEATURE_HEADER}/).first
combined = {}
scenario_titles.each_with_index do |title, index|
combined[title] = scenario_blocks[index].gsub(/h\d. ([Scenario|Scenario Outline].*)/, '\1')
end
combined.each do |title, content|
feature_filename = title.parameterize
dirpath = mappings[id]
FileUtils.mkdir_p(dirpath)
fname = "#{dirpath}/#{feature_filename.gsub("\r", '').parameterize}.feature"
puts "Writing #{fname}"
File.open(fname, 'w') do |f|
if @config['tags']
@config['tags'].each do |tag, token|
f.write "@#{tag}\n" if pretext.include?(token)
end
end
if @config['tags']
@config['tags'].each do |tag, token|
content.gsub!(token, "@#{tag}\n")
end
end
f.write "Feature: #{title}\n\n"
f.write @link_builder.view(id, confluence_page.title, title)
f.write content
end
end
end
def validate_args
terminate "No action given" if @args.empty?
command = @args.first
terminate "Unknown action '#{@args.first}'" unless 'pull' == command
end
def mappings
@config['mappings']
end
def terminate(message)
puts message
exit(1)
end
end
|
class ModifyStats < ActiveRecord::Migration[5.2]
def change
rename_column(:batting_stats, :player_id, :roster_id)
rename_column(:game_batting_stats, :player_id, :roster_id)
rename_column(:game_pitching_stats, :player_id, :roster_id)
remove_column(:batting_stats, :age)
execute 'ALTER TABLE "batting_stats" ALTER COLUMN "roster_id" SET NOT NULL;'
remove_index "batting_stats", name: "batstat_ndx"
add_index "batting_stats", ["roster_id", "name","season","team_id"], name: "batstat_ndx", unique: true
end
end
|
class DeckCard < ApplicationRecord
belongs_to :deck
belongs_to :card
def as_json
{
# id: self.id,
# deck_id: self.deck_id,
card: self.card.as_json,
quantity: self.quantity
}
end
end
|
class Comic < ActiveRecord::Base
validates :title, presence: true
validates :price, presence: true
validates :image_id, presence: true
validates :comic_series_id, presence: true
validates :publisher_id, presence: true
validates :release_date, presence: true
belongs_to :comic_series
has_and_belongs_to_many :creators
def archive
self.archived = true
self.save
end
def self.reprint
self.where(reprint: true)
end
def self.variant
self.where(variant: true)
end
end
|
class AddingFacilitySysidField < ActiveRecord::Migration
def change
add_column :lsspdfassets, :u_facility_sys_id, :string
end
end
|
require_relative "numerical"
class StochasticVariables
# x - list of values
# p - array of probabilities for each value
def initialize x, p=nil
@x = x
@p = p
end
def d
return Math.sqrt(v)
end
def v
return @x.map { |i| (i.to_f - e)**2 }.reduce(:+) / @x.length
end
def e
return @x.reduce(:+).to_f / @x.length if @p.nil?
return @x.zip(@p).map { |pair| pair[0].to_f * pair[1].to_f }.reduce(:+)
end
end
class Sample
def self.add s1, s2, same_variation=false
if same_variation
return Sample.new(nil, s1.e + s2.e, Math.sqrt(((s1.n - 1)*s1.v + (s2.n - 1)*s2.v) / (s1.n + s2.n - 2)))
else
return Sample.new(nil, s1.e + s2.e, Math.sqrt(s1.v/s1.n + s2.v/s2.n))
end
end
# x - list of values
# sd - standard deviation
def initialize x=nil, mean=nil, sd=nil, n=nil
@x = x
@mean = mean
@sd = sd
@n = n
end
def n
return @n unless @n.nil?
return @x.length unless @x.nil?
return Float::NAN
end
def d
return @sd unless @sd.nil?
return Math.sqrt(v)
end
def v
return @sd**2 unless @sd.nil?
return @x.map { |i| (i.to_f - e)**2 }.reduce(:+) / (@x.length - 1) unless @x.nil?
return Float::NAN
end
def e
return @mean unless @mean.nil?
return @x.reduce(:+).to_f / @x.length unless @x.nil?
return Float::NAN
end
end
class NormalDistribution
# Adds two normal distributions
def self.add nd1, nd2
return NormalDistribution.new(nd1.e + nd2.e, Math.sqrt(nd1.v + nd2.v))
end
def initialize mean=0, sd=1
@mean = mean
@sd = sd
end
def e
return @mean
end
def v
return @sd**2
end
# General normal cumulative distribution function
def cdf x
return integral(lambda { |xpos| pdf(xpos) }, -8 * @sd, x)
end
# General normal probability distribution function
# x - Point in the normal distribution (measured in standard deviations)
# mean - The mean of the normal distribution
# sd - The standard deviation of the normal distribution
def pdf x
return (1 / Math.sqrt(2 * Math::PI * @sd**2)) * Math::E**(-((x - @mean)**2) / (2 * @sd**2))
end
# Find the x that gives some percentage of the distribution
# p - The percentage sought
def r_cdf p
return secant_method(lambda { |x| cdf(x) }, @mean + 1, @mean - 1, p)
end
end
class TDistribution
# k - Degrees of freedom
def initialize k=1
@k = k.to_f
end
def v
return @k.to_f / (@k - 2) if @k > 2
return Float::INFINITY
end
def cdf x
return 1 - cdf(-x) if x < 0
return 1 - 0.5*regularized_incomplete_beta_function(@k/(x**2 + @k), @k / 2, 0.5)
end
def pdf x
return (gamma((@k + 1) / 2) / (Math.sqrt(@k * Math::PI) * gamma(@k / 2))) * (1 + (x.to_f**2)/@k)**(-(@k+1)/2)
end
def r_cdf p
return secant_method(lambda { |x| cdf(x) }, 1, -1, p)
end
end
class ChiSquare
# Calculates Q
# Two parameters:
# a - matrix of actual values
# (e - matrix of expected values, otherwise assumes even spread)
def self.q_matrix a, e=nil
if e.nil?
row_size = a.size
col_size = a.transpose.size
row_sum = a.clone.map { |y| y.reduce(:+) }
col_sum = a.transpose.clone.map { |x| x.reduce(:+) }
tot_sum = row_sum.clone.reduce(:+).to_f
res = 0.0
row_size.times do |y|
col_size.times do |x|
m = row_sum[y]*col_sum[x]/tot_sum # Expected value at (x,y)
res += (a[y][x].to_f - m)**2 / m
end
end
return res
end
return q_list(a.flatten, e.flatten)
end
# Calculates Q
# Two parameters:
# a - list of actual values
# e - list of expected values
def self.q_list a, e
return a.zip(e).map { |pair| (pair[0].to_f - pair[1].to_f)**2 / pair[1].to_f }.reduce(:+)
end
# k - degrees of freedom
def initialize k
@k = k.to_f
end
def pdf x
return (x**(@k/2 - 1) * Math::E**(-x.to_f/2))/(2**(@k/2) * gamma(@k/2))
end
def cdf x
return lower_incomplete_gamma(@k/2, x.to_f/2)/gamma(@k/2)
end
# Returns the maximum point on the probability density function
def pdf_max
return @k - 2 if @k >= 2
return 0
end
# Find the x that gives some percentage of the distribution
# p - The percentage sought
def r_cdf p
return secant_method(lambda { |x| cdf(x) }, pdf_max, pdf_max + 1, p)
end
end
class ExponentialDistribution
# λ = rate
def initialize rate
@rate = rate
end
def e
return 1/@rate
end
def v
return 1/(@rate**2)
end
def d
return Math.sqrt(v)
end
def pdf x
return @rate*(Math::E**(-1*@rate*x))
end
def cdf x
return integral(lambda { |xpos| pdf(xpos) }, 0, x)
end
end
class PoissonDistribution
# Adds two poisson distributions
def self.add pd1, pd2
return PoissonDistribution.new(pd1.e + pd2.e)
end
def initialize mean
@mean = mean.to_f
end
def e
return @mean
end
def v
return e
end
def d
return Math.sqrt(v)
end
def pdf k
return (@mean**k)/factorial(k) * Math::E**(-1*@mean)
end
# Probability that a value is less or equals to k
def cdf k
return Math::E**(-1*@mean) * (0..k).to_a.map { |i| (@mean**i)/factorial(i) }.reduce(:+)
end
end
class BinomialDistribution
def initialize n, p
@n = n
@p = p
end
def e
return @n * @p
end
def v
return @n * @p * (1 - @p)
end
def pdf k
return combination(@n, k) * @p**k * (1 - @p)**(@n - k)
end
# Probability that a value is less or equals to k
def cdf k
return (0..k).to_a.map { |i| pdf(i) }.reduce(:+)
end
end
# Calculates the gamma function
def gamma z
return integral(lambda { |x| x**(z-1) * Math::E**(-x)}, 0, 50)
end
# Calculates the lower incomplete gamma function
def lower_incomplete_gamma s, x
return integral(lambda { |t| t**(s-1) * Math::E**(-t)}, 0, x)
end
# Calculates the regularized incomplete beta function
def regularized_incomplete_beta_function x, a, b
return incomplete_beta_function(x, a, b)/beta_function(a, b)
end
# Calculates the incomplete beta function
def incomplete_beta_function x, a, b
return integral(lambda { |t| t**(a-1) * (1-t)**(b-1) }, 0, x, 0.00001)
end
# Calculates the beta function
def beta_function a, b
return incomplete_beta_function(1, a, b)
end
# Calculates the factorial of an integer
def factorial k
return (1..k).to_a.reduce(:*) if k >= 1
return 1
end
# Calculates n choose k
def combination n, k
return factorial(n)/(factorial(k)*factorial(n-k))
end
|
class CreateProperties < ActiveRecord::Migration
def change
create_table :properties do |t|
t.integer :number_of_bedrooms
t.integer :number_of_bathrooms
t.integer :rent_a_week
t.string :address
t.string :streetName
t.string :agentName
t.string :agentPhoneNo
t.string :imageUrl
t.string :thumbnailUrl
t.text :shortDescription
t.string :detailsUrl
t.timestamps
end
end
end
|
$:.unshift File.dirname(__FILE__)
require 'pusher'
require 'grape'
require 'grape-entity'
require 'grape-swagger'
require 'models/metrics'
require 'models/metadata'
require 'models/dashboard'
require 'bothan/extensions/date_wrangler'
require 'bothan/helpers/metrics_helpers'
require 'bothan/helpers/auth_helpers'
require 'entities' # needed
module Bothan
class MetricEndpointError < StandardError
end
class TimeSpanQueries
attr_reader :value
def initialize(aliased)
@value = aliased
end
def self.parse(value)
if !['all','latest', 'today', 'since-midnight','since-beginning-of-month','since-beginning-of-week', 'since-beginning-of-year'].include?(value) && !value.to_datetime.instance_of?(DateTime)
fail 'Invalid alias'
end
new(value)
end
end
# class EndpointAliases < Grape::Validations::Base
# # TODO - use this block if/when this Ruby bug is fixed https://bugs.ruby-lang.org/issues/13661
# def validate_param!(attr_name, params)
# unless ['all','latest', 'today', 'since-midnight','since-beginning-of-month','since-beginning-of-week', 'since-beginning-of-year'].include?(params[attr_name])
# fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: 'must be a recognised endpoint alias'
# end
# end
# end
class Api < Grape::API
content_type :json, 'application/json; charset=UTF-8'
helpers Bothan::Helpers::Metrics
helpers Bothan::Helpers::Auth
rescue_from MetricEndpointError do |e|
error!({status: e}, 400)
end
rescue_from ArgumentError do |e|
if e.message == "invalid date"
error!({status: "passed parameters are not a valid ISO8601 date/time."}, 400)
else
error!({status: e.message}, 400)
end
end
rescue_from Grape::Exceptions::ValidationErrors do |e|
# byebug
if e.message == "timespan is invalid"
error!({status: "time is not a valid ISO8601 date/time."}, 400)
else
error!({status: e.message}, 400)
end
end
rescue_from ISO8601::Errors::UnknownPattern do |e|
error!({status: "passed parameters are not a valid ISO8601 date/time."}, 400)
end
namespace :metrics do
desc 'list all available metrics'
get do
metrics = list_metrics
present metrics, with: Bothan::Entities::MetricList
end
params do
requires :metric, type: String, desc: 'The name identifier where your metrics are stored'
end
route_param :metric do
# params do, followed by route_param used to namespace enables the documentation desc for :metric to persist in all subsequent blocks
# however using this method means that the documentation from Bothan::Entities does not surface
# namespace 'metrics/:metric' do # can also be '/:metrics', but never :metric
desc 'show latest value for given metric'
get do
metric = metric(params[:metric])
present metric, with: Bothan::Entities::Metric
end
desc 'create a single metric',
detail: 'create an endpoint by posting form data',
params: Bothan::Entities::Metric.documentation # this is preferred as it lists the parameters as form data
params do
requires :time, type: DateTime, desc: 'the timestamp associated with a stored value'
requires :value, desc: 'the value to store alongside a timestamp'
end
post do
endpoint_protected!
update_metric(params[:metric], params[:time], params[:value])
if @metric.save
present @metric, with: Bothan::Entities::Metric
end
end
desc 'delete an entire metric endpoint'
delete do
endpoint_protected!
params do
requires :metric, type: String, desc: 'The name identifier where your metrics are stored'
end
Metric.where(name: params[:metric]).destroy_all
end
desc 'time based queries, return a timestamped value or values for an alias of time'
params do
optional :timespan, type: TimeSpanQueries, desc: 'Either an alias for common timespans or a Time value. Supported aliases include: "all","latest", "today", "since-midnight","since-beginning-of-month","since-beginning-of-week", "since-beginning-of-year"'
end
get ':timespan' do
if %w(all latest today since-midnight since-beginning-of-month since-beginning-of-week since-beginning-of-year).include?(params[:timespan].value)
range_alias(params[:timespan].value)
else
metric = metric(params[:metric], params[:timespan].value.to_datetime)
present metric, with: Bothan::Entities::Metric
end
end
# desc 'time queries'
# # TODO - use this block instead of above block of same desc if/when this Ruby bug is fixed https://bugs.ruby-lang.org/issues/13661
# # TODO - currently the below logic, and associated Grape::Validations::Base class EndpointAliases do not work because of 'since-beginning-month'
# params do
# requires :timespan, types: [DateTime, EndpointAliases], desc: 'duration to parse'
# # disappointingly the above does not surface well within Grape Swagger
# end
# get '/:timespan' do
# if params[:timespan].to_datetime.instance_of?(DateTime)
# metric = single_metric(params[:metric], params[:timespan].to_datetime)
# metric
# else
# range_alias(params[:timespan])
# end
# end
desc 'list a time-series range of measurements for a given metric'
params do
requires :from, type: String, desc: 'the commencement date/time for your time-series range'
optional :to, type: String, desc: 'the conclusion date/time for your time-series range'
end
get ':from/:to' do
metrics = get_timeseries(params)
present metrics, with: Bothan::Entities::MetricCollection
end
namespace '/increment' do
desc 'auto-increment a metric'
post do
endpoint_protected!
increment_metric(1)
status 201
present @metric, with: Bothan::Entities::Metric
end
desc 'increment a metric by stipulated amount' # home/metrics/:metric/increment"
params do
requires :amount, type: {value: Integer}, desc: 'amount to increase by'
end
post '/:amount' do
endpoint_protected!
increment = (params[:amount] || 1).to_i
increment_metric(increment)
if @metric.save
status 201
present @metric, with: Bothan::Entities::Metric
end
end
end
namespace '/metadata' do
desc 'update a metrics metadata',
detail: 'update below parameters by posting form data',
params: Bothan::Entities::MetricMetadata.documentation
post do
endpoint_protected!
# format :json #TODO - when refactoring into classes make this explicit at top of class
meta = MetricMetadata.find_or_create_by(name: params[:metric].parameterize)
meta.type = params[:type].presence
meta.datatype = params[:datatype].presence
meta.title.merge!(params[:title] || {}) # TODO these are breaking when used with grape, because they are set as hash in mongo document, N2K if they are to be kept as such
meta.description.merge!(params[:description] || {}) # TODO these are breaking when used with grape, because they are set as hash in mongo document, N2K if they are to be kept as such
if meta.save
status 201
present meta, with: Bothan::Entities::MetricMetadata
else
status 400
end
end
end
# end # END /<metric> namespace
end # end route param
end # end metrics namespace
add_swagger_documentation \
mount_path: '/api_documentation'
end
end
|
# Gym Membership class that has AnnualMembership & MonthlyMembership
class Members
def AnnualMembership
raise NotImplementedError, 'AnnualMembership() must be defined in subclass'
end
def MonthlyMembership
raise NotImplementedError, 'MonthlyMembership() must be defined in subclass'
end
end
# Membership class that inherits Members and implements AnnualMembership & MonthlyMembership
class Membership < Members
def AnnualMembership
puts "Inside Members:AnnualMembership()"
end
def MonthlyMembership
puts "Inside Members:MonthlyMembership()"
end
end
# CreateMembers class has the functions for MemberRegistration & MemberOperation
class CreateMembers
def MemberRegistration
raise NotImplementedError, 'MemberRegistration() must be defined in subclass'
end
def MemberOperation
@members = MemberRegistration()
return @members
end
end
# ConcreteCreateMembers inherits from CreateMembers
class ConcreteCreateMembers < CreateMembers
def MemberRegistration
return ConcreteMembership.new
end
end
# Create objects for each member creation
membersCreator = ConcreteCreateMembers.new
members = membersCreator.MemberOperation
# Calling the functions
members.AnnualMembership
members.MonthlyMembership |
class SubjectsController < ApplicationController
layout 'application'
#layout 'admin'
def index
list
render('subjects/list')
#render('demo/hello') # Most common way to do it
# render('list')
end
def list
# @subjects = Subject.order("Subject.position ASC")
@subjects = Subject.all
end
def show
@subject = Subject.find(params[:id])
end
def create
#Instantiate a new object using form parameters
temp_par = params.require(:subject).permit(:name, :position, :visible)
@subject = Subject.new(temp_par)
# Save the object
if @subject.save
#If save succeeds, redirect to the list action
set_flash_notice("Subject created.")
redirect_to(action: 'subjects/list')
else
#If save fails, redisplay the form so user can fix problem
render('subjects/new')
end
end
def edit
@subject = Subject.find(params[:id])
end
def update
#Find object object using form parameters
@subject = Subject.find(params[:id])
# Update the object
temp_par = params.require(:subject).permit(:name, :position, :visible)
if @subject.update_attributes(temp_par)
#If updatesucceeds, redirect to the list action
set_flash_notice("Subject updated.")
redirect_to(action: 'subjects/show', id: @subject.id)
else
#If save fails, redisplay the form so user can fix problem
render('edit')
end
end
def delete
@subject = Subject.find(params[:id])
end
def destroy
subject = find_subject
subject.destroy
set_flash_notice("subject destroyed.")
redirect_to(action: 'list')
end
def find_subject
Subject.find(params[:id])
end
end
|
# encoding: UTF-8
require_relative "../test_helper"
class CommentControllerTest < FunctionalTestCase
def setup
login
@post = Factory(:post)
end
def test_show_comments
make_comment
get "/post/#{@post.token}"
assert_equal 200, status
text = css(".post-comments .comment-block").children.first.text
assert_equal "hello world", text
end
def delete_comment
comment = make_comment
delete "/comment/#{comment._id}"
assert_equal 0, Post.first.comments.size
end
def build_comment
comment = Comment.new(content: "hello world")
comment.post = @post
comment.user = @user
comment
end
def make_comment
build_comment.save!
end
end
|
# frozen_string_literal: true
module Domain
class Board
def initialize(state = [[:X, nil, nil],
[nil, nil, nil],
[nil, nil, nil]],
last_piece = :O)
@state = state
@last_piece = last_piece
end
def piece_at(x, y)
@state[y][x]
end
attr_reader :last_piece
attr_reader :state
end
end
|
Rails.application.routes.draw do
get '/' => redirect('/api-docs')
get '/api-docs' => "docs#index"
namespace :api do
resources :currencies, only: [:show]
end
match "*path" => "application#routing_error", via: :all
end
|
require 'formula'
class Subpro < Formula
homepage 'https://github.com/satoshun/subpro'
version 'v2.0.2'
url 'https://raw.githubusercontent.com/satoshun/subpro/v2.0.2/pkg/darwin/subpro'
sha256 '992a990ab150c29177627f93cae5414ca8055b32cf8cfb7ef1f4d7a9401655db'
def install
bin.install 'subpro'
system 'mkdir -p ~/.subpro/base'
system 'curl -o ~/.subpro/base/base.sublime-project https://raw.githubusercontent.com/satoshun/subpro/master/base.sublime-project'
end
end
|
class Armor
include Mongoid::Document
field :name
field :key
field :type
field :icon
field :strength1
field :strength2
field :weakness1
field :weakness2
field :description
has_many :units, class_name: 'Unit::Base'
end |
class GameTeam
attr_reader :game_id,
:team_id,
:home_or_away,
:won,
:head_coach,
:goals,
:shots,
:hits,
:power_play_chances,
:power_play_goals
def initialize(info)
@game_id = info[:game_id]
@team_id = info[:team_id]
@home_or_away = info[:hoa]
@won = info[:won]
@head_coach = info[:head_coach]
@goals = info[:goals].to_i
@shots = info[:shots].to_i
@hits = info[:hits].to_i
@power_play_chances = info[:powerplayopportunities].to_i
@power_play_goals = info[:powerplaygoals].to_i
end
def won?
if @won == "TRUE"
return true
else
return false
end
end
end
|
Pod::Spec.new do |s|
s.name = 'LRMocky'
s.version = '1.0'
s.license = 'MIT'
s.summary = 'A mock object library for Objective C, inspired by JMock 2.0'
s.homepage = 'http://github.com/lukeredpath/LRMocky'
s.authors = { 'Luke Redpath' => 'luke@lukeredpath.co.uk' }
s.source = { :git => 'https://github.com/lukeredpath/LRMocky.git' }
s.requires_arc = true
# exclude files that are not ARC compatible
source_files = FileList['Classes/**/*.{h,m}'].exclude(/LRMockyAutomation/)
source_files.exclude(/NSInvocation\+(BlockArguments|OCMAdditions).m/)
s.source_files = source_files
s.public_header_files = FileList['Classes/**/*.h'].exclude(/LRMockyAutomation/)
# create a sub-spec just for the non-ARC files
s.subspec 'no-arc' do |sp|
sp.source_files = FileList['Classes/LRMocky/Categories/NSInvocation+{BlockArguments,OCMAdditions}.m']
sp.requires_arc = false
end
# platform targets
s.ios.deployment_target = '5.0'
s.osx.deployment_target = '10.7'
# dependencies
s.dependency 'OCHamcrest', '1.9'
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Product.create(name: "canvases", price: 20, image_url: "https://images.ctfassets.net/f1fikihmjtrp/3CDdug9IYkzm0AMUACUmAW/e8ddf90393326c1b00602b611953865e/07008-group1-4ww.jpg?q=80&w=250&fm=webp", description: "A multi-pack of decent canvas panels")
Product.create(name: "paints", price: 10, image_url: "fakeurl.jpg", description: "Oil paints in all colors of the rainbow")
|
require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper')
module Recliner
describe View do
context "with map option" do
subject { View.new(:map => 'my map function') }
it "should wrap map function in a ViewFunction::Map" do
subject.map.should be_an_instance_of(ViewFunction::Map)
end
it "should serialize to couch" do
subject.to_couch.should == {
'map' => 'function(doc) { my map function }'
}
end
it "should load from couch" do
view = View.from_couch({
'map' => 'function(doc) { my map function }'
})
view.map.to_s.should == 'function(doc) { my map function }'
view.reduce.should be_nil
end
it "should be equal to another view with the same map function and no view" do
subject.should == View.new(:map => 'my map function')
end
it "should not be equal to another view with the same map function but with a view" do
subject.should_not == View.new(:map => 'my map function', :reduce => 'some reduce function')
end
it "should not be equal to another view with a different map function" do
subject.should_not == View.new(:map => 'some other map function')
end
end
context "with map and reduce options" do
subject { View.new(:map => 'my map function', :reduce => 'my reduce function') }
it "should wrap reduce function in a ViewFunction::Reduce" do
subject.reduce.should be_an_instance_of(ViewFunction::Reduce)
end
it "should serialize to couch" do
subject.to_couch.should == {
'map' => 'function(doc) { my map function }',
'reduce' => 'function(keys, values, rereduce) { my reduce function }'
}
end
it "should load from couch" do
view = View.from_couch({
'map' => 'function(doc) { my map function }',
'reduce' => 'function(keys, values, rereduce) { my reduce function }'
})
view.map.to_s.should == 'function(doc) { my map function }'
view.reduce.to_s.should == 'function(keys, values, rereduce) { my reduce function }'
end
it "should be equal to another view with the same map and reduce functions" do
subject.should == View.new(:map => 'my map function', :reduce => 'my reduce function')
end
it "should not be equal to another view with a different map function" do
subject.should_not == View.new(:map => 'some other map function', :reduce => 'my reduce function')
end
it "should not be equal to another view with a different reduce function" do
subject.should_not == View.new(:map => 'my map function', :reduce => 'some other reduce function')
end
end
context "without map option" do
before(:each) do
@generator = mock('ViewGenerator instance')
@generator.stub(:generate).and_return([ 'map function', 'reduce function' ])
ViewGenerator.stub!(:new).and_return(@generator)
end
def create_view
View.new(:order => 'name', :conditions => { :class => 'TestDocument' })
end
it "should generate a view function" do
ViewGenerator.should_receive(:new).with(:order => 'name', :conditions => { :class => 'TestDocument' }).and_return(@generator)
create_view
end
it "should assign map and reduce functions from the generator" do
view = create_view
view.map.should == 'map function'
view.reduce.should == 'reduce function'
end
end
describe "#invoke" do
define_recliner_document :TestDocument
subject { View.new(:map => 'map function') }
before(:each) do
@database = mock('database')
@path = "_design/TestDocument/_view/test"
end
describe "options and keys" do
context "with no keys" do
before(:each) do
@database.stub!(:get).and_return({ 'rows' => [] })
end
context "without options" do
def invoke
subject.invoke(@database, @path)
end
it "should GET the view with empty options" do
@database.should_receive(:get).with(@path, {}).and_return({ 'rows' => [] })
invoke
end
end
context "with options" do
def invoke
subject.invoke(@database, @path, :limit => 1, :raw => true)
end
it "should GET the view with the given options (and without meta options)" do
@database.should_receive(:get).with(@path, { :limit => 1 }).and_return({ 'rows' => [] })
invoke
end
end
end
context "with a single key" do
before(:each) do
@database.stub!(:get).and_return({ 'rows' => [] })
end
context "without options" do
def invoke
subject.invoke(@database, @path, 'key')
end
it "should GET the view with the given key" do
@database.should_receive(:get).with(@path, { :key => 'key' }).and_return({ 'rows' => [] })
invoke
end
end
context "with options" do
def invoke
subject.invoke(@database, @path, 'key', :limit => 1, :raw => true)
end
it "should GET the view with the given key and options (and without meta options)" do
@database.should_receive(:get).with(@path, { :key => 'key', :limit => 1 }).and_return({ 'rows' => [] })
invoke
end
end
end
context "with multiple keys" do
before(:each) do
@database.stub!(:post).and_return({ 'rows' => [] })
end
context "without options" do
def invoke
subject.invoke(@database, @path, 'key1', 'key2')
end
it "should POST to the view with the given keys and empty params" do
@database.should_receive(:post).with(@path, { :keys => [ 'key1', 'key2' ] }, {}).and_return({ 'rows' => [] })
invoke
end
end
context "with options" do
def invoke
subject.invoke(@database, @path, 'key1', 'key2', :descending => true, :raw => true)
end
it "should POST to the view with the given keys and options (and without meta options)" do
@database.should_receive(:post).with(@path, { :keys => [ 'key1', 'key2' ] }, { :descending => true }).and_return({ 'rows' => [] })
invoke
end
end
context "with keys option" do
def invoke
subject.invoke(@database, @path, :keys => [ 'key1', 'key2' ], :descending => true, :raw => true)
end
it "should POST to the view with the given keys and options (and without meta options)" do
@database.should_receive(:post).with(@path, { :keys => [ 'key1', 'key2' ] }, { :descending => true }).and_return({ 'rows' => [] })
invoke
end
end
end
end
describe "results" do
context "all results are instantiable" do
before(:each) do
@raw = {
'rows' => [
{ 'id' => '123', 'value' => { 'class' => 'TestDocument', '_id' => '123', '_rev' => '1-12345' }, 'key' => 'TestDocument' },
{ 'id' => 'abc', 'value' => { 'class' => 'TestDocument', '_id' => 'abc', '_rev' => '1-12345' }, 'key' => 'TestDocument' },
]
}
@database.stub!(:get).and_return(@raw)
end
context "raw option not provided" do
it "should instantiate results" do
result = subject.invoke(@database, @path)
result.all? { |i| i.should be_an_instance_of(TestDocument) }
result[0].id.should == '123'
result[1].id.should == 'abc'
end
end
context "raw option provided" do
it "should not instantiate results" do
subject.invoke(@database, @path, :raw => true).should == @raw
end
end
end
context "results are not instantiable" do
before(:each) do
@raw = {
'rows' => [
{ 'id' => '123', 'value' => 1, 'key' => 'TestDocument' },
{ 'id' => 'abc', 'value' => 2, 'key' => 'TestDocument' },
]
}
@database.stub!(:get).and_return(@raw)
end
it "should return raw values" do
subject.invoke(@database, @path).should == [ 1, 2 ]
end
end
end
end
end
end
|
class Indocker::EnvFileHelper
ENV_FILES_FOLDER = 'env_files'.freeze
class << self
def path(env_file)
File.expand_path(File.join(folder, File.basename(env_file.path)))
end
def folder
File.join(Indocker.deploy_dir, ENV_FILES_FOLDER)
end
end
end |
class QuizScoreSummary
def initialize(module_provider, quiz_score_provider)
@module_provider = module_provider
@quiz_score_provider = quiz_score_provider
end
def get_score_summary(user)
topics = []
@module_provider.get_all_topics.each do |topic|
next unless topic['questions']
top_score = @quiz_score_provider.get_highest_score(user, topic['slug'])
topic['score'] = top_score
topics.push(topic)
end
return topics
end
end
|
module Api
module V1
class EntitiesController < ApplicationController
skip_before_action :verify_authenticity_token
# action to create given entity and all its associated tags
def create
if not params.key? "ids" or params["ids"].nil?
render :json => {:status => 201, :msg => "entity should have atleast 1 tag"} and return
end
# TODO: use Rails Associations between Entity and Tag models
# delete entity and all its associated tags existing with the same identifier
entity_obj = Entity.where(:identifier => params["identifier"]).first
if not entity_obj.nil?
Tagging.where(:entity => entity_obj.id).delete_all
entity_obj.delete
end
begin
entity_obj = Entity.new(:identifier => params["identifier"],
:name => params["name"],
:entity_type_id => params["type"],
:description => params["description"])
entity_obj.save
params["ids"].each do |tag_id|
entity_tag_obj = Tagging.new(:entity_id => entity_obj.id, :tag_id => tag_id)
entity_tag_obj.save
end
rescue Exception => e
puts e.message
render :json => {:status => 201, :msg => "unable to save the entity : #{params["name"]}"} and return
end
render :json => {:status => 200, :msg => "entity : #{params["name"]} saved successfully"}
end
end
end
end
|
# encoding: utf-8
control "V-52155" do
title "The DBMS must include organization-defined additional, more detailed information in the audit records for audit events identified by type, location, or subject."
desc "Information system auditing capability is critical for accurate forensic analysis. Audit record content that may be necessary to satisfy the requirement of this control includes: timestamps, source and destination addresses, user/process identifiers, event descriptions, success/fail indications, file names involved, and access control or flow control rules invoked.
In addition, the application must have the capability to include organization-defined additional, more detailed information in the audit records for audit events. These events may be identified by type, location, or subject.
An example of detailed information the organization may require in audit records is full-text recording of privileged commands or the individual identities of group account users.
Some organizations may determine that more detailed information is required for specific database event types. If this information is not available, it could negatively impact forensic investigations into user actions or other malicious events.true"
impact 0.5
tag "check": "
Verify, using vendor and system documentation if necessary, that the DBMS is configured to use Oracle's auditing features, or that a third-party product or custom code is deployed and configured to satisfy this requirement.
If a third-party product or custom code is used, compare its current configuration with the audit requirements. If any of the requirements is not covered by the configuration, this is a finding.
The remainder of this Check is applicable specifically where Oracle auditing is in use.
To see if Oracle is configured to capture audit data, enter the following SQLPlus command:
SHOW PARAMETER AUDIT_TRAIL
or the following SQL query:
SELECT * FROM SYS.V$PARAMETER WHERE NAME = 'audit_trail';
If Oracle returns the value "NONE", this is a finding.
Compare the organization-defined auditable events with the Oracle documentation to determine whether standard auditing covers all the requirements. If it does, this is not a finding.
Compare those organization-defined auditable events that are not covered by the standard auditing, with the existing Fine-Grained Auditing (FGA) specifications returned by the following query:
SELECT * FROM SYS.DBA_FGA_AUDIT_TRAIL;
If any such auditable event is not covered by the existing FGA specifications, this is a finding."
tag "fix": "
Either configure the DBMS's auditing to audit organization-defined auditable events; or if preferred, use a third-party or custom tool. The tool must provide the minimum capability to audit the required events.
If using a third-party product, proceed in accordance with the product documentation. If using Oracle's capabilities, proceed as follows.
Use this query to ensure auditable events are captured:
ALTER SYSTEM SET AUDIT_TRAIL=<audit trail type> SCOPE=SPFILE;
Audit trail type can be "OS", "DB", "DB,EXTENDED", "XML" or "XML,EXTENDED".
After executing this statement, it may be necessary to shut down and restart the Oracle database.
If the organization-defined additional audit requirements are not covered by the default audit options, deploy and configure Fine-Grained Auditing. For details, refer to Oracle documentation, at the location above.
For more information on the configuration of auditing, please refer to "Auditing Database Activity" in the Oracle Database 2 Day + Security Guide:
http://docs.oracle.com/cd/E11882_01/server.112/e10575/tdpsg_auditing.htm
and "Verifying Security Access with Auditing" in the Oracle Database Security Guide: http://docs.oracle.com/cd/E11882_01/network.112/e36292/auditing.htm#DBSEG006
and "27 DBMS_AUDIT_MGMT" in the Oracle Database PL/SQL Packages and Types Reference:
http://docs.oracle.com/cd/E11882_01/appdev.112/e40758/d_audit_mgmt.htm"
# Write Check Logic Here
end |
class AddTosSettingToSmoochBot < ActiveRecord::Migration[4.2]
def change
tb = BotUser.smooch_user
unless tb.nil?
settings = tb.get_settings.clone || []
settings.insert(-2, { name: 'smooch_message_smooch_bot_ask_for_tos', label: 'Message sent to user to ask them to agree to the Terms of Service (placeholders: %{tos} (TOS URL))', type: 'string', default: '' })
tb.set_settings(settings)
tb.save!
end
end
end
|
class EasyGanttThemesController < ApplicationController
layout 'admin'
before_filter :require_admin
def index
@gantt_themes = EasyGanttTheme.all
end
def new
@gantt_theme = EasyGanttTheme.new
end
def create
@gantt_theme = EasyGanttTheme.new
@gantt_theme.safe_attributes = params[:easy_gantt_theme]
@gantt_theme.save_attachments({'first' => {'file' => params[:easy_gantt_theme][:logo]}})
if @gantt_theme.save
redirect_to :action => 'index'
else
render :action => 'new'
end
end
def edit
@gantt_theme = EasyGanttTheme.find(params[:id])
end
def update
@gantt_theme = EasyGanttTheme.find(params[:id])
@gantt_theme.safe_attributes = params[:easy_gantt_theme]
@gantt_theme.save_attachments({'first' => {'file' => params[:easy_gantt_theme][:logo]}})
if @gantt_theme.save
flash[:notice] = l(:notice_successful_update)
redirect_to :action => 'index'
else
render :action => 'edit'
end
end
def destroy
@gantt_theme = EasyGanttTheme.find(params[:id])
@gantt_theme.destroy
redirect_to :action => 'index'
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.