text stringlengths 10 2.61M |
|---|
module Linux
module Lxc
class Lines
def initialize
@lines = []
end
def add(line)
@lines << line
@lines
end
def each(&block)
@lines.each { |line| block.call(line) }
end
def select(&block)
@lines.select { |line| block.call(line) }
end
def find(&block)
@lines.find(&block)
end
def values
@lines.map(&:value)
end
def remove(line)
@lines = @lines.select { |i| i != line }
end
def [](idx)
@lines[idx]
end
def comment!
@lines.each(&:comment!)
end
def length
@lines.length
end
def empty?
@lines.empty?
end
def first
@lines.first
end
end
end
end
|
require_relative './test_helper'
require './lib/sales_analyst'
require './lib/standard_deviation'
require 'bigdecimal/util'
require 'time'
require 'mocha/minitest'
class SalesAnalystTest < Minitest::Test
include StandardDeviation
def setup
@se = SalesEngine.from_csv({
:items => "./fixture_data/items_sample.csv",
:merchants => "./fixture_data/merchants_sample.csv",
:invoices => "./fixture_data/invoices_sample.csv",
:invoice_items => "./fixture_data/invoice_items_sample.csv",
:transactions => "./fixture_data/transactions_sample.csv",
:customers => "./fixture_data/customers_sample.csv",
})
end
def test_it_exists_and_has_attributes
assert_instance_of SalesAnalyst, @se.analyst
end
def test_average_items_per_merchant
assert_equal 2.42, @se.analyst.average_items_per_merchant
end
def test_reduce_shop_items
assert_equal 29, @se.analyst.reduce_shop_items.values.flatten.count
end
def test_average_items_per_merchant_standard_deviation
assert_equal 2.84, @se.analyst.average_items_per_merchant_standard_deviation
end
def test_merchants_with_high_item_count
assert_equal 1, @se.analyst.merchant_names_with_high_item_count.count
assert_equal Merchant, @se.analyst.merchants_with_high_item_count[0].class
end
def test_average_item_price_for_merchant
assert_equal 29.99, @se.analyst.average_item_price_for_merchant(12334105)
end
def test_second_deviation_above_unit_price
assert_equal 0.54076e3, @se.analyst.second_deviation_above_unit_price
end
def test_average_average_price_per_merchant
expected = 0.674e2
assert_equal expected.to_d, @se.analyst.average_average_price_per_merchant
end
def test_golden_items
assert_equal Array, @se.analyst.golden_items.class
assert_equal Item, @se.analyst.golden_items[1].class
assert_equal 5, @se.analyst.golden_items.count
end
def test_average_invoices_per_merchant
assert_equal 11.42, @se.analyst.average_invoices_per_merchant
assert_equal Float, @se.analyst.average_invoices_per_merchant.class
end
def test_reduce_merchants_and_invoices
assert_equal 12, @se.analyst.reduce_merchants_and_invoices.keys.count
assert_equal 12, @se.analyst.reduce_merchants_and_invoices.values.count
assert_equal Hash, @se.analyst.reduce_merchants_and_invoices.class
end
def test_number_of_invoices
assert_equal Array, @se.analyst.number_of_invoices.class
assert_equal 12, @se.analyst.number_of_invoices.count
end
def test_average_invoices_per_merchant_standard_deviation
assert_equal 4.19, @se.analyst.average_invoices_per_merchant_standard_deviation
assert_equal Float, @se.analyst.average_invoices_per_merchant_standard_deviation.class
end
def test_second_deviation_above_invoice_count
assert_equal 19.8, @se.analyst.second_deviation_above_average_invoice_count
assert_equal Float, @se.analyst.second_deviation_above_average_invoice_count.class
end
def test_top_merchants_by_invoice_count
assert_equal Array, @se.analyst.top_merchants_by_invoice_count.class
end
def test_second_deviation_below_average_invoice_count
assert_equal 3.04, @se.analyst.second_deviation_below_average_invoice_count
assert_equal Float, @se.analyst.second_deviation_below_average_invoice_count.class
end
def test_bottom_merchants_by_invoice_count
assert_equal Array, @se.analyst.bottom_merchants_by_invoice_count.class
end
def test_reduce_invoices_and_days
assert_equal Hash, @se.analyst.reduce_invoices_and_days.class
assert_equal 7, @se.analyst.reduce_invoices_and_days.keys.count
end
def test_invoices_by_day_count
assert_equal Array, @se.analyst.invoices_by_day_count.class
assert_equal 7, @se.analyst.invoices_by_day_count.count
end
def test_average_invoices_per_day_standard_deviation
assert_equal Float, @se.analyst.average_invoices_per_day_standard_deviation.class
assert_equal 3.26, @se.analyst.average_invoices_per_day_standard_deviation
end
def test_average_invoices_per_day
assert_equal Float, @se.analyst.average_invoices_per_day.class
assert_equal 19.57, @se.analyst.average_invoices_per_day
end
def test_one_deviation_above_invoices_per_day
assert_equal Float, @se.analyst.one_deviation_above_invoices_per_day.class
assert_equal 22.83, @se.analyst.one_deviation_above_invoices_per_day
end
def test_top_days_by_invoice_count
assert_equal Array, @se.analyst.top_days_by_invoice_count.class
assert_equal String, @se.analyst.top_days_by_invoice_count[0].class
end
def test_invoice_status
assert_equal Float, @se.analyst.invoice_status(:pending).class
assert_equal Float, @se.analyst.invoice_status(:shipped).class
assert_equal Float, @se.analyst.invoice_status(:returned).class
expected = @se.analyst.invoice_status(:pending)
expected += @se.analyst.invoice_status(:shipped)
expected += @se.analyst.invoice_status(:returned)
assert_equal expected, 100
end
def test_merchants_with_pending_invoices
assert_equal Array, @se.analyst.merchants_with_pending_invoices.class
assert_equal 12, @se.analyst.merchants_with_pending_invoices.count
assert_equal Merchant, @se.analyst.merchants_with_pending_invoices[0].class
end
def test_merchants_with_only_one_item
assert_equal Array, @se.analyst.merchants_with_only_one_item.class
assert_equal 7, @se.analyst.merchants_with_only_one_item.count
assert_equal Merchant, @se.analyst.merchants_with_only_one_item[0].class
end
def test_merchants_with_only_one_item_registered_in_month
assert_equal Array, @se.analyst.merchants_with_only_one_item_registered_in_month("January").class
assert_equal 1, @se.analyst.merchants_with_only_one_item_registered_in_month("March").count
assert_equal Merchant, @se.analyst.merchants_with_only_one_item_registered_in_month("March")[0].class
end
def test_validate_merchants
assert_equal Array, @se.analyst.validate_merchants(12334105).class
end
def test_find_the_total_revenue_for_a_single_merchant
repo = mock
transaction = Transaction.new({
:id => 6,
:invoice_id => 55,
:credit_card_number => "4242424242424242",
:credit_card_expiration_date => "0220",
:result => "success",
:created_at => Time.now
}, repo)
assert_equal Invoice, @se.analyst.transaction_to_invoice(transaction).class
assert_equal BigDecimal, @se.analyst.transaction_dollar_value(transaction).class
assert_equal 0.7377717e5, @se.analyst.revenue_by_merchant(12334105)
assert_equal BigDecimal, @se.analyst.revenue_by_merchant(12334105).class
end
def test_invoice_paid_in_full
assert_equal true, @se.analyst.invoice_paid_in_full?(4966)
assert_equal true, @se.analyst.invoice_paid_in_full?(3445)
assert_equal false, @se.analyst.invoice_paid_in_full?(144)
assert_equal false, @se.analyst.invoice_paid_in_full?(204)
end
def test_invoice_total
assert_equal 22338.81, @se.analyst.invoice_total(55)
end
def test_total_revenue_by_date
date = Time.parse("2004-01-25")
assert_equal 0.2233881e5, @se.analyst.total_revenue_by_date(date)
end
def test_top_revenue_earners
assert_equal 12, @se.analyst.top_revenue_earners.count
assert_equal 10, @se.analyst.top_revenue_earners(10).count
end
def test_most_sold_item_for_merchant
se = SalesEngine.from_csv({
:items => "./data/items.csv",
:merchants => "./fixture_data/merchants_sample.csv",
:invoices => "./data/invoices.csv",
:invoice_items => "./data/invoice_items.csv",
:transactions => "./data/transactions.csv",
:customers => "./fixture_data/customers_sample.csv",
})
assert_equal 5, se.analyst.most_sold_item_for_merchant(12334105).count
assert_instance_of Item, se.analyst.most_sold_item_for_merchant(12334105)[0]
assert_instance_of Array, se.analyst.most_sold_item_for_merchant(12334105)
end
end
|
class Order < ApplicationRecord
belongs_to :user
belongs_to :store
has_many :burritos
def total_price
total = 0
self.burritos.each do | burrito |
total += burrito.price
end
return total
end
end |
# See authlogic/lib/authlogic/test_case.rb
#----------------------------------------------------------------------------
def activate_authlogic
require 'authlogic/test_case/rails_request_adapter'
require 'authlogic/test_case/mock_cookie_jar'
require 'authlogic/test_case/mock_request'
Authlogic::Session::Base.controller = (@request && Authlogic::TestCase::RailsRequestAdapter.new(@request)) || controller
end
# Note: Authentication is NOT ActiveRecord model, so we mock and stub it using RSpec.
#----------------------------------------------------------------------------
def login(user_stubs = {}, session_stubs = {})
activate_authlogic
User.current_user = @current_user = FactoryGirl.create(:user, user_stubs)
@current_user_session = double(Authentication, {:record => current_user}.merge(session_stubs))
Authentication.stub(:find).and_return(@current_user_session)
end
alias :require_user :login
#----------------------------------------------------------------------------
def login_and_assign(user_stubs = {}, session_stubs = {})
login(user_stubs, session_stubs)
assigns[:current_user] = current_user
end
#----------------------------------------------------------------------------
def logout
@current_user = nil
@current_user_session = nil
Authentication.stub(:find).and_return(nil)
end
alias :require_no_user :logout
#----------------------------------------------------------------------------
def current_user
@current_user
end
#----------------------------------------------------------------------------
def current_user_session
@current_user_session
end
|
#
# GTDLint
#
module GTDLint
VERSION = '0.5'
end
|
class AddDistrictToOrigins < ActiveRecord::Migration[5.2]
def change
add_column :origins, :district, :string
end
end
|
::Refinery::Page.class_eval do
def self.fast_footer_menu(columns = [])
# First, apply a filter to determine which pages to show.
# We need to join to the page's slug to avoid multiple queries.
return nil if (footer_page_id = ::Refinery::Page.select(:id).find_by_link_url('/footer')).nil?
pages = order('lft ASC').where(:parent_id => footer_page_id)
# Now we only want to select particular columns to avoid any further queries.
# Title and menu_title are retrieved in the next block below so they are not here.
(menu_columns | columns).each do |column|
pages = pages.select(arel_table[column.to_sym])
end
# We have to get title and menu_title from the translations table.
# To avoid calling globalize3 an extra time, we get title as page_title
# and we get menu_title as page_menu_title.
# These is used in 'to_refinery_menu_item' in the Page model.
%w(title menu_title).each do |column|
pages = pages.joins(:translations).select(
"#{translation_class.table_name}.#{column} as page_#{column}"
)
end
pages
end
end |
name "getmail"
maintainer "Bob Greenshields"
maintainer_email ""
license "Apache 2.0"
description "Installs/Configures getmail"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))
version "0.1"
|
class AddConfirmedToReservations < ActiveRecord::Migration
def self.up
add_column :reservations, :confirmed, :bool
end
def self.down
remove_column :reservations, :confirmed
end
end
|
class AddAdditionalFieldsToProducts < ActiveRecord::Migration[4.2]
def change
add_column :products, :is_on_sale, :boolean
add_column :products, :is_on_frontpage, :boolean
add_column :products, :is_featured, :boolean
end
end
|
# Copyright (c) 2015 Vault12, Inc.
# MIT License https://opensource.org/licenses/MIT
require 'test_helper'
require 'prove_test_helper'
class MailboxUploadTest < ProveTestHelper
test 'upload messages to mailbox' do
@config = getConfig
setHpks
for i in 0..@config[:number_of_messages]
uploadMessage
end
check_number_of_messages
cleanup
end
private
def uploadMessage
ary = getHpks
pairary = _get_random_pair(@config[:number_of_mailboxes] - 1)
hpk = ary[pairary[0]].from_b64
to_hpk = ary[pairary[1]]
data = { cmd: 'upload', to: to_hpk, payload: 'hello world 0' }
n = _make_nonce
@session_key = Rails.cache.read("session_key_#{hpk}")
@client_key = Rails.cache.read("client_key_#{hpk}")
skpk = @session_key.public_key
skpk = b64enc skpk
ckpk = @client_key.to_b64
_post '/command', hpk, n, _client_encrypt_data(n, data)
end
# after all of the messages have been uploaded
# check to make sure the number of messages is correct
def check_number_of_messages
iterations = rds.get(@config[:number_of_iterations]).to_i
if iterations.nil?
rds.set(@config[:number_of_iterations], 1)
iterations = 1
else
iterations = iterations.to_i + 1
rds.set(@config[:number_of_iterations], iterations)
end
total_messages = get_total_number_of_messages
numofmessages = @config[:number_of_messages] + 1
total_messages_calc = iterations * numofmessages
assert_equal(total_messages, total_messages_calc)
end
# this gets the total number of messages across all mailboxes
def get_total_number_of_messages
ary = getHpks
total_messages = 0
ary.each do |key|
mbxkey = 'mbx_' + key
num_of_messages = rds.hlen(mbxkey)
total_messages += num_of_messages.to_i
end
total_messages
end
# Calls the ProveTestHelper to get back an HPK
# which is then stored for future calls to getHpks
def setHpks
cleanup
for i in 0..@config[:number_of_mailboxes] - 1
hpk = setup_prove
rds.sadd(@config[:hpkey], hpk.to_b64)
end
end
# get an array of HPKs from a Redis set
def getHpks
rds.smembers(@config[:hpkey])
end
# this is the way you configure the test
def getConfig
config = {
number_of_mailboxes: 3,
number_of_messages: 24,
hpkey: 'hpksupload',
number_of_iterations: 'hpkiteration'
}
end
# delete and cleanup keys from Redis
def cleanup
ary = getHpks
ary.each do |hpk|
result_mbx = rds.exists?("mbx_#{hpk}")
rds.del("mbx_#{hpk}")
msg_keys = rds.keys("msg_#{hpk}_*")
msg_keys.each do |key|
rds.del(key) if rds.exists?(key)
end
end
rds.del(@config[:hpkey])
rds.del(@config[:number_of_iterations])
end
end
|
class Api::V1::PagesController < Api::V1::BaseController
def show
@page = Page.find(params[:id])
authorize @page
end
end
|
module Lita
module Handlers
class AddMemberToTeam < Handler
namespace :team
template_root File.expand_path("../../../../templates", __FILE__)
route(
/(\S*) team (\+1|add me|add (\S*))$/i,
:add,
command: true,
help: {
"<name> team +1" => "add me to team",
"<name> team add me" => "add me to team",
"<name> team add <member>" => "add member to team"
}
)
def add(response)
team_name = response.match_data[1]
if team = get_team(team_name)
if team[:limit] && team[:limit] <= team[:members].count
return response.reply(
render_template(:team_cannot_perform_operation,
team_name: team_name)
)
end
member_name = (response.match_data[3] ||
response.user.mention_name).delete("@")
if team[:members].key?(member_name.to_sym)
return response.reply(
t("member.already_in_team",
team_name: team_name,
member_name: member_name)
)
end
member = member_data(member_name)
count_was = team[:members].count
team[:members][member_name] = member
redis.set(team_name, MultiJson.dump(team))
response.reply(
render_template(:member_added_to_team,
team_name: team_name,
member_name: member[:name],
count: count_was)
)
else
response.reply(render_template(:team_not_found, team_name: team_name))
end
end
private
def get_team(team_name)
data = redis.get(team_name)
MultiJson.load(data, symbolize_keys: true) if data
end
def member_data(member_name)
if lita_user = Lita::User.fuzzy_find(member_name)
{
id: lita_user.id,
name: lita_user.name,
mention_name: lita_user.mention_name,
confirmed: false
}
else
{ name: member_name, confirmed: false }
end
end
Lita.register_handler(self)
end
end
end
|
class ThingsToDosController < InheritedResources::Base
private
def things_to_do_params
params.require(:things_to_do).permit(:Name, :Title, :Content)
end
end
|
class Photo < ApplicationRecord
belongs_to :listing
has_attached_file :photo, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :photo, content_type: /\Aimage\/.*\z/
# s3
# has_attached_file :photo,
# stora: :s3,
# s3_permissions: :public,
# s3_credentials: "#{Rails.root}/config/s3.yml",
# path: ":attachment/:id/:style.:extension"
# do_not_validate_attachment_file_type :photo
# local
# has_attached_file :photo,
# styles: { medium: "300x300>", thumb: "100x100>" }, # 画像サイズを指定
# url: "/assets/arts/:id/:style/:basename.:extension", # 画像保存先のURL先
# path: "#{Rails.root}/public/assets/arts/:id/:style/:basename.:extension" # サーバ上の画像保存先パス
# validates_attachment :photo,
# presence: true, # ファイルの存在チェック
# less_than: 5.megabytes, # ファイルサイズのチェック
end
|
class PizzasController < ApplicationController
# GET /pizzas
# GET /pizzas.json
def index
@pizzas = Pizza.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @pizzas }
end
end
# GET /pizzas/1
# GET /pizzas/1.json
def show
@pizza = Pizza.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @pizza }
end
end
# GET /pizzas/new
# GET /pizzas/new.json
def new
@pizza = Pizza.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @pizza }
end
end
# GET /pizzas/1/edit
def edit
@pizza = Pizza.find(params[:id])
end
# POST /pizzas
# POST /pizzas.json
def create
@pizza = Pizza.new(params[:pizza])
respond_to do |format|
if @pizza.save
format.html { redirect_to @pizza, notice: 'Pizza was successfully created.' }
format.json { render json: @pizza, status: :created, location: @pizza }
else
format.html { render action: "new" }
format.json { render json: @pizza.errors, status: :unprocessable_entity }
end
end
end
# PUT /pizzas/1
# PUT /pizzas/1.json
def update
@pizza = Pizza.find(params[:id])
respond_to do |format|
if @pizza.update_attributes(params[:pizza])
format.html { redirect_to @pizza, notice: 'Pizza was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: @pizza.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pizzas/1
# DELETE /pizzas/1.json
def destroy
@pizza = Pizza.find(params[:id])
@pizza.destroy
respond_to do |format|
format.html { redirect_to pizzas_url }
format.json { head :ok }
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the 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)
User.destroy_all
user1 = User.create!({
username: "Jesse",
password: "Jesse"
})
Art.destroy_all
user1.arts.create!({
name: "Drinking Coffee",
image: "https://www.theartstory.org/images20/works/van_gogh_vincent_1.jpg?2",
description: "Van Gogh"
})
p "Created #{User.count} user"
p "Created #{Art.count} pieces of art" |
#!/usr/bin/env ruby
#
# backup-chroot-script
#
# This can be used on any LTSP machine to backup the client image to a bakcup
# location
#
# Required
# - pbzip2
#
puts "Make sure you run this with root access"
backup_dir = "i386"
Dir.chdir("/opt/ltsp")
date = Time.now.strftime("%Y%m%d-%H%M")
filename="#{date}-i386.tar.gz"
name = "/storage1/backup/chroot/#{filename}"
if File.exists?(name)
puts "\nBackup file #{name} already exists, \nplease remove before running this backup script again.\n\n"
exit
end
puts "Backup #{backup_dir} to #{name}..."
puts "Hit enter to continue"
gets
puts "Enter comment"
comment = filename + " = " + gets.chomp
puts "\n\nBacking up please wait....\n\n"
`tar --use-compress-prog=pbzip2 -cf #{name} #{backup_dir}`
`echo "#{comment}" >> readme.txt`
|
Given /^(provider "[^\"]*") is requiring strong passwords$/ do |provider|
provider.settings.update_attribute :strong_passwords_enabled, true
end
Then /^I should see the error that the password is too weak$/ do
assert has_content? User::STRONG_PASSWORD_FAIL_MSG
end
|
class AddressesController < ApplicationController
before_action :set_address, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@addresses = Address.all
end
def show
end
def new
@address = current_user.addresses.build
end
def edit
end
def create
@address = current_user.addresses.build(address_params)
if @address.save
redirect_to pages_admin_path, notice: 'address was successfully created.'
else
render action: 'new'
end
end
def update
if @address.update(address_params)
redirect_to pages_admin_path, notice: 'address was successfully updated.'
else
render action: 'edit'
end
end
def destroy
@address.destroy
redirect_to pages_admin_path
end
private
def set_address
@address = Address.find(params[:id])
end
def address_params
params.require(:address).permit(:description, :image)
end
end |
require 'minitest'
require 'minitest/unit'
require 'minitest/autorun'
require "open-uri"
require 'nokogiri'
require_relative '../../lib/readers/url_reader'
class UrlReaderTest < MiniTest::Unit::TestCase
def test_can_read?
assert ["200", "OK"] == open('https://ru.hexlet.io/lessons.rss').status
end
def test_read()
xml = Nokogiri::XML(open('https://ru.hexlet.io/lessons.rss')).text
tested_xml = UrlReader.read('https://ru.hexlet.io/lessons.rss').text
assert xml == tested_xml
end
end |
class SessionsController < ApplicationController
def create
user = User.from_omniauth(request.env['omniauth.auth'])
session[:user_id] = user.id
redirect_to root_path, notice: "You have signed in as '#{user.nickname}'"
end
def destroy
session[:user_id] = nil
redirect_to root_path, notice: "You have been signed out"
end
def failed
redirect_to root_path, notice: "Authentication with Twitter has failed"
end
end
|
# to drop the moderation tables execute the following three statements.
# Be Careful!! These are shared tables that all moderateable obects use
# self.connection.drop_table 'content_documents'
# self.connection.drop_table 'content_fields'
# self.connection.drop_table 'content_histories'
module Viewpoints
module Acts
module Moderateable
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def acts_as_moderateable(&block)
include Viewpoints::Acts::Moderateable::InstanceMethods
include Viewpoints::Acts::Moderateable::StateTransitions
cattr_accessor :moderateable_fields, :versionable_fields, :state_field, :quarantineable, :get_system_user, :author_field, :text_field_filter,
:activateable, :after_activation, :after_quarantine, :cascade_state_target, :after_initial_activation, :after_rejection
after_create :create_content_document
after_save :cascade_state
has_many :content_documents, :as => :owner, :dependent=>:destroy
has_many :filtered_words, :as => :origin
self.moderateable_fields = []
self.versionable_fields = []
self.state_field = :status
self.author_field = :user
self.quarantineable = Proc.new{|content_document| false }
self.get_system_user = Proc.new{ return }
self.text_field_filter = Proc.new{|text| []}
self.activateable = Proc.new{|content_doc| true }
self.after_activation = Proc.new{ |content_doc| nil }
self.after_initial_activation = Proc.new{ |content_doc| nil }
self.after_quarantine = Proc.new{ |content_doc| nil }
self.after_rejection = Proc.new { |content_doc| nil }
Object.new.instance_eval(<<-EVAL).instance_eval(&block)
def cascade_state(options)
#{self.name}.cascade_state_target = options[:to]
end
def after_activation(&block)
#{self.name}.after_activation = block
end
def after_initial_activation(&block)
#{self.name}.after_initial_activation = block
end
def after_quarantine(&block)
#{self.name}.after_quarantine = block
end
def after_rejection(&block)
#{self.name}.after_rejection = block
end
def moderateable_fields(*args)
#{self.name}.moderateable_fields = args
end
def moderateable_fields(*args)
#{self.name}.moderateable_fields = args
end
def versionable_fields(*args)
#{self.name}.versionable_fields = args
end
def state_field(field)
#{self.name}.state_field = field
end
def user_field(field)
#{self.name}.user_field = field
end
def quarantineable?(&block)
#{self.name}.quarantineable=block
end
def get_system_user(&block)
#{self.name}.get_system_user=block
end
def text_field_filter(&block)
#{self.name}.text_field_filter=block
end
def activateable?(&block)
#{self.name}.activateable=block
end
self
EVAL
end
def cascaded_state_field_name
"cascaded_#{self.state_field}"
end
def migrate_for_moderation
$stdout.sync=true
$stdout.write("Beginning migration for #{table_name}\n")
setup_moderation_tables
$stdout.write("Done with moderation tables\n")
$stdout.write("checking for #{self.state_field} in #{table_name}\n")
if self.columns.find{ |col| col.name == self.state_field.to_s }
change_state_column_to_string
else
$stdout.write("couldn't find #{self.state_field.to_s}\n")
add_state_column_to_table
end
end
def migrate_for_cascaded_state_field
$stdout.sync=true
$stdout.write("Beginning cascaded status migration for #{table_name}\n")
$stdout.write("checking for #{cascaded_state_field_name} in #{table_name}\n")
self.reset_column_information
unless self.columns.find{ |col| col.name == cascaded_state_field_name}
$stdout.write("couldn't find #{cascaded_state_field_name}\n")
add_cascaded_state_column_to_table
end
end
def down_migrate_for_cascaded_state_field
$stdout.sync=true
$stdout.write("Beginning cascaded status down migration for #{table_name}\n")
$stdout.write("checking for #{cascaded_state_field_name} in #{table_name}\n")
self.reset_column_information
if self.columns.find{ |col| col.name == cascaded_state_field_name }
remove_cascaded_state_column_from_table
end
end
private
def change_state_column_to_string
self.connection.change_column table_name, self.state_field, :string, :default=>'new', :null=>false
end
def add_state_column_to_table
$stdout.write("adding column #{self.state_field.to_s} to #{table_name}\n")
self.connection.add_column table_name, self.state_field, :string, :default=>'new', :null=>false
end
def add_cascaded_state_column_to_table
$stdout.write("adding column #{cascaded_state_field_name} to #{table_name}\n")
self.connection.add_column table_name, cascaded_state_field_name, :string
end
def remove_cascaded_state_column_from_table
$stdout.write("removing column #{cascaded_state_field_name} to #{table_name}\n")
self.connection.remove_column table_name, cascaded_state_field_name
end
def setup_moderation_tables
conn = self.connection
create_content_documents unless connection.table_exists? 'content_documents'
create_content_fields unless connection.table_exists? 'content_fields'
create_content_histories unless connection.table_exists? 'content_histories'
create_filtered_words unless connection.table_exists? 'filtered_words'
end
def create_content_documents
self.connection.create_table :content_documents do |t|
t.integer :owner_id
t.string :owner_type
t.string :status, :null=>false
t.integer :user_id
t.string :reason_codes
t.boolean :requires_review
t.string :comment
t.timestamps
end
self.connection.add_index :content_documents, [:owner_id, :owner_type], :unique=>false
end
def create_content_fields
self.connection.create_table :content_fields do |t|
t.integer :content_document_id
t.string :field_name
t.text :field_value
t.timestamps
end
self.connection.add_index :content_fields, [:content_document_id, :field_name], :unique=>true
end
def create_content_histories
self.connection.create_table :content_histories do |t|
t.integer :content_document_id
t.string :status, :null=>false
t.integer :user_id
t.string :comment
t.string :reason_codes
t.boolean :requires_review
t.timestamps
end
self.connection.add_index :content_histories, :content_document_id
end
def create_filtered_words
self.connection.create_table :filtered_words do |t|
t.integer :content_field_id
t.integer :origin_id
t.string :origin_type
t.string :status, :default=>'new'
t.integer :offset
t.integer :length
t.string :filter_info
t.timestamps
end
self.connection.add_index :filtered_words, [:origin_id, :origin_type, :content_field_id], :unique => false, :name=>"filtered_words_index"
end
end
module InstanceMethods
def prep_content
#TODO DAS: feels like we're playing a little too fast and loose here
forks = ContentDocument.find :conditions => ["owner_id = :id AND (:status != 'rejected' AND :status != 'active')", { :id => id }]
end
def fork
in_moderation = self.content_documents.select{ |cd| ['quarantined', 'pending_review', 'rejected'].member?(cd.status) }
returning create_content_document do
in_moderation.each{ |e| e.shelve_content! }
end
end
private
def cascade_state
return unless cascade_state_target && self.send("#{self.class.state_field}_was") != self.send(self.class.state_field)
state = self.send(state_field)
children = self.send(cascade_state_target)
children.each do |c|
c.update_attribute(c.class.cascaded_state_field_name, state)
c.content_documents.each do |cd|
comment = "Cascaded status set to #{state}"
ContentHistory.create(:content_document_id => cd.id, :status => cd.status, :user_id => cd.user_id, :comment => comment)
end
end
end
def create_content_document
if !ContentDocument.aasm_states.collect{ |e| e.name }.member?(status.to_sym)
return
end
doc = ContentDocument.new(:owner => self)
latest = self.content_documents.find(:last)
self.moderateable_fields.each do |f|
doc.content_fields.build(:field_name => f.to_s, :field_value => send("#{f.to_s}").gsub("\r\n", "\n"))
latest_content = latest.content_fields.find_by_field_name(f.to_s) if latest
if latest_content && send(f) == latest_content.field_value
# Skip text_field_filter and just copy over the filtered words from the previous entry
latest_content.filtered_words.each do |old|
doc.content_fields.last.filtered_words.build(:origin => self, :offset => old.offset, :length => old.length)
end
else
# The content in this field changed, run the text_field_filter
filtered_words = text_field_filter[send("#{f.to_s}").gsub("\r\n", "\n")]
filtered_words.each{ |fw|
doc.content_fields.last.filtered_words.build( :origin => self, :offset => fw[:offset],
:length => fw[:length])
}
end
end
self.versionable_fields.each do |f|
if self.class.reflect_on_association(f)
doc.content_fields << ContentField.new(:field_name => f, :field_value => send("#{f}"))
else
doc.content_fields.build(:field_name => f, :field_value => send("#{f.to_s}"))
end
end
doc.save!
if self.quarantineable[doc]
doc.user_id = nil
doc.comment = 'document quarantined by system'
doc.quarantine_content!
else
doc.user_id = nil
doc.comment = 'document activated by system'
doc.activate_content!
end
end
end # Instance Methods
end
end
end
|
class AddReceivedContestWork < ActiveRecord::Migration[5.2]
def change
add_column :contest_works, :received, :boolean
end
end
|
# frozen_string_literal: true
class V1::UsersController < ApplicationController
include Avatarable
before_action :authenticate_user!
before_action :set_user, only: %i[avatar show]
def avatar
return render_avatar_not_found unless @user.has_avatar?
redirect_to rails_representation_url(
@user.avatar.variant(resize: '150x150').processed,
only_path: true
)
end
def index
@pagy, @users = pagy(User.kept.order(created_at: :asc))
render json: UserSerializer.new(
@users,
{ meta: { pagination: pagy_metadata(@pagy) } }
), status: :ok
end
def show
render json: UserSerializer.new(@user).to_hash, status: :ok
end
private
def set_user
@user = User.find(params[:id])
end
end
|
require "test_helper"
module RegexpPreview
class MultilineTest < ActiveSupport::TestCase
test "simple usage" do
config = {
"format_firstline" => "/foo/",
"time_format" => "time_format",
}
config["format1"] = "/(?<foo>foo)\n/"
config["format2"] = "/(?<bar>bar)/"
3.upto(Fluentd::Setting::InTail::MULTI_LINE_MAX_FORMAT_COUNT) do |i|
config["format#{i}"] = "//"
end
preview = RegexpPreview::MultiLine.new(fixture_path("error0.log"), "multiline", config)
matches = [
{
whole: "foo\nbar\nbaz\n1\n2\n3\n4\n5\n6\n10\n11\n12",
matches: [
{ key: "foo", matched: "foo", pos: [0, 3] },
{ key: "bar", matched: "bar", pos: [4, 7] }
]
}
]
assert_equal(matches, preview.matches[:matches])
end
test "detect only continuous patterns" do
config = {
"format_firstline" => "/foo/",
"time_format" => "time_format",
}
config["format1"] = "/(?<foo>foo)\n/"
config["format2"] = "/(?<bar>baz)/"
3.upto(Fluentd::Setting::InTail::MULTI_LINE_MAX_FORMAT_COUNT) do |i|
config["format#{i}"] = "//"
end
preview = RegexpPreview::MultiLine.new(fixture_path("error0.log"), "multiline", config)
assert_equal([], preview.matches[:matches])
end
# http://docs.fluentd.org/articles/in_tail
test "example on document" do
config = {
"format_firstline" => "/\\d{4}-\\d{1,2}-\\d{1,2}/",
"format1" => "/^(?<time>\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}) \\[(?<thread>.*)\\] (?<level>[^\\s]+)(?<message>.*)/",
"time_format" => "%Y-%m-%d %H:%M:%S",
"keep_time_key" => true
}
2.upto(Fluentd::Setting::InTail::MULTI_LINE_MAX_FORMAT_COUNT) do |i|
config["format#{i}"] = "//"
end
preview = RegexpPreview::MultiLine.new(fixture_path("multiline_example.log"), "multiline", config)
matches = [
{
whole: "2013-3-03 14:27:33 [main] INFO Main - Start\n",
matches: [
{ key: "time", matched: "2013-3-03 14:27:33", pos: [0, 18] },
{ key: "thread", matched: "main", pos: [20, 24] },
{ key: "level", matched: "INFO", pos: [26, 30] },
{ key: "message", matched: " Main - Start\n", pos: [30, 45] }
]
},
{
whole: "2013-3-03 14:27:33 [main] ERROR Main - Exception\njavax.management.RuntimeErrorException: null\n at Main.main(Main.java:16) ~[bin/:na]\n",
matches: [
{ key: "time", matched: "2013-3-03 14:27:33", pos: [0, 18] },
{ key: "thread", matched: "main", pos: [20, 24] },
{ key: "level", matched: "ERROR", pos: [26, 31] },
{ key: "message", matched: " Main - Exception\njavax.management.RuntimeErrorException: null\n at Main.main(Main.java:16) ~[bin/:na]\n", pos: [31, 136] },
]
},
{
whole: "2013-3-03 14:27:33 [main] INFO Main - End",
matches: [
{ key: "time", matched: "2013-3-03 14:27:33", pos: [0, 18] },
{ key: "thread", matched: "main", pos: [20, 24] },
{ key: "level", matched: "INFO", pos: [26, 30] },
{ key: "message", matched: " Main - End", pos: [30, 42] },
]
}
]
assert_equal(matches, preview.matches[:matches])
end
end
end
|
# Define a method hello(name) that takes a string representing a name and returns the
# string "Hello, " concatenated with the name.
def hello(name)
"Hello, #{name}"
end
# Define a method starts_with_consonant?(s) that takes a string and returns true if it
# starts with a consonant and false otherwise. (For our purposes, a consonant is any
# letter other than A, E, I, O, U.) NOTE: be sure it works for both upper and lower case
# and for nonletters!
def starts_with_consonant?(s)
if s.empty? then return false end
unless s.match( /(\A[^aeiou^\d^\s^\W])\.*/i ) == nil then
return true
else
return false
end
end
# Define a method binary_multiple_of_4?(s) that takes a string and returns true if the
# string represents a binary number that is a multiple of 4. NOTE: be sure it returns
# false if the string is not a valid binary number!
def binary_multiple_of_4?(s)
if s.empty? then return false end
if s.match( /[^01]/ ) == nil then
return s.to_i(2) % 4 == 0
else
return false
end
end
|
class SessionsController < ApplicationController
skip_before_action :session_expiration, only: [:destroy]
def index
if !Admin.where(email: session[:email]).first.nil?
session[:admin_logged_in] = true
session[:teacher_logged_in] = true
session[:student_logged_in] = true
@admin = Admin.where(email: session[:email]).first
# @admin = create_admin(session[:fname], session[:lname], session[:email]) # to add an admin for the first time
redirect_to admins_path
elsif !Teacher.where(email: session[:email]).first.nil?
session[:teacher_logged_in] = true
session[:student_logged_in] = true
@teacher = Teacher.where(email: session[:email]).first
redirect_to teacher_path(@teacher)
elsif session[:email].to_s.end_with?("@tamu.edu") # if not an admin or teacher but has tamu email, then student
session[:student_logged_in] = true
@student = create_from_omniauth(session[:fname],session[:lname],session[:email],session[:picture])
redirect_to student_path(@student)
end
end
def googleAuth
session.clear
access_token = request.env["omniauth.auth"]
refresh_token = access_token.credentials.refresh_token
session[:fname] = access_token.info.first_name
session[:lname] = access_token.info.last_name
session[:email] = access_token.info.email
session[:picture] = access_token.info.image
t = Time.now + 30.minutes
session[:expires_at] = t.to_i
# session[:token] = refresh_token # or use @user.google_refresh_token
redirect_to root_path
end
def destroy
# session.clear
session.delete(:fname)
session.delete(:lname)
session.delete(:email)
session.delete(:picture)
session.delete(:admin_logged_in)
session.delete(:teacher_logged_in)
session.delete(:student_logged_in)
# session.delete(:expires_at)
session.delete(:alert)
redirect_to root_path
session[:alert] = flash[:alert]
end
private
def exist_email(email)
ret = false
for student in Student.all do
if email == student.email
ret = true
end
end
ret
end
def create_from_omniauth(fname, lname, email, pic)
# Creates a new user only if it doesn't exist
if Student.where(email: email).first.nil?
@newstudent = Student.new
@newstudent.fname = fname
@newstudent.lname = lname
@newstudent.email = email
@newstudent.picture = pic
@newstudent.save!
else
@newstudent = Student.where(email: email).first
end
@newstudent
end
def create_admin(fname, lname, email)
if Admin.where(email: email).first.nil?
@newadmin = Admin.new
@newadmin.fname = fname
@newadmin.lname = lname
@newadmin.email = email
@newadmin.save!
else
@newadmin = Admin.where(email: email).first
end
@newadmin
end
end
|
class HomeController < ApplicationController
include HTTParty
# require 'open-uri' # from nokogiri xml parsing tutorial
base_uri 'http://iaspub.epa.gov/enviro/efservice/PUB_DIM_FACILITY'
# website http://www.epa.gov/enviro/facts/ghg/summary_model.html
def index
# @main_data = HTTParty.get('http://iaspub.epa.gov/enviro/efservice/PUB_DIM_FACILITY/ROWS/0:100/XML')
# @emissions_data = HTTParty.get('http://iaspub.epa.gov/enviro/efservice/PUB_FACTS_SUBP_GHG_EMISSION/ROWS/0:500/XML')
# @emissions= Nokogiri::XML('@emissions_data')
@emissions_data = HTTParty.get('http://iaspub.epa.gov/enviro/efservice/c_fuel_level_information/ROWS/0:500')
end
# def index
# @facilities = Facility.all
# end
# def facilities.js
# Facility.all.to_json
# end
# def posts(options={})
# self.class.get('/posts/get', options)
# end
end
|
require "rails_helper"
require Rails.root.join("db", "data", "20230306143819_setup_one_off_medication_reminders_bangladesh")
RSpec.describe SetupOneOffMedicationRemindersBangladesh do
it "sets up the current notifications" do
allow(CountryConfig).to receive(:current_country?).with("Bangladesh").and_return true
stub_const("SIMPLE_SERVER_ENV", "production")
stub_const("SetupOneOffMedicationRemindersBangladesh::PATIENTS_PER_DAY", 2)
create_list(:patient, 5, :with_overdue_appointments)
excluded_facility = create(:facility, id: SetupOneOffMedicationRemindersBangladesh::EXCLUDED_FACILITIES.first)
_excluded_patients = create_list(:patient, 2, registration_facility_id: excluded_facility)
described_class.new.up
expect(Notification.count).to eq(5)
expect(Notification.pluck(:status)).to all eq("pending")
expect(Notification.pluck(:message)).to all eq("notifications.one_off_medications_reminder")
expect(Notification.pluck(:purpose)).to all eq("one_off_medications_reminder")
expect(Notification.order(:remind_on).pluck(:remind_on)).to eq [
1.days.from_now.to_date,
1.days.from_now.to_date,
2.days.from_now.to_date,
2.days.from_now.to_date,
3.days.from_now.to_date
]
end
end
|
class Guest
attr_reader :name, :age, :fav_song
attr_accessor :money
def initialize (name, age, money, fav_song)
@name = name
@age = age
@money = money
@fav_song = fav_song
end
end
|
class AddWarningMsgToImportTrail < ActiveRecord::Migration
def change
add_column :import_trails, :warning_msg, :string
end
end
|
require 'brew_dg/dependency_manifest'
require 'brew_dg/graph'
require 'brew_dg/graph_installation'
require 'brew_dg/package'
require 'brew_dg/queryable_dependencies'
module BrewDG
class Library
def initialize(options = {})
@package_cache = options.fetch(:package_cache, {})
@packages = options.fetch(:packages) do
%x(brew list).lines.map(&:strip)
end
@relevant_dependency_types = options.fetch(:relevant_dependency_types) do
[:required, :recommended]
end
end
def graph
@packages.reduce(Graph.new) do |graph, name|
subgraph = subgraph(name)
graph.add_edges!(*subgraph.edges)
graph.add_vertices!(*subgraph.vertices)
end
end
def installation_order
installation = GraphInstallation.new(graph)
installation.list.map(&:to_s)
end
private
def subgraph(name)
package = package(name)
Graph.new.tap do |graph|
graph.add_vertex!(package)
manifests = @relevant_dependency_types.map do |type|
package.dependencies.of_type(type)
end
manifests.reduce(graph) do |manifest_graph, manifest|
manifest.dependencies.reduce(manifest_graph) do |subgraph, dependency|
subgraph.add_edge!(package, dependency, manifest)
subgraph.add_edges!(*subgraph(dependency.name).edges)
end
end
end
end
def package(name)
@package_cache.fetch(name) do
manifests = DependencyManifest.for_package(name)
manifests.map! do |manifest|
packages = manifest.dependencies.map(&method(:package))
DependencyManifest.new(type: manifest.type, dependencies: packages)
end
dependencies = QueryableDependencies.new(manifests)
Package.new(name: name, dependencies: dependencies).tap do |package|
@package_cache.store(name, package)
end
end
end
end
end
|
require 'climate'
require 'yaml'
module AptControl
# Some class methods for defining config keys
module ConfigDSL
def config(key, description, options={})
options = {:required => true}.merge(options)
configs << [key, description, options]
end
def configs
@configs ||= []
end
end
module CLI
def self.main
init_commands
Climate.with_standard_exception_handling do
begin
Root.run(ARGV)
rescue Exec::UnexpectedExitStatus => e
$stderr.puts("Error executing: #{e.command}")
$stderr.puts(e.stderr)
exit 1
end
end
end
def self.init_commands
require 'apt_control/cli/status'
require 'apt_control/cli/watch'
require 'apt_control/cli/include'
require 'apt_control/cli/set'
require 'apt_control/cli/promote'
end
module Common
# FIXME tidy up with some meta magic
def package_states ; ancestor(Root).package_states ; end
def new_include_cmd(options={}) ; ancestor(Root).new_include_cmd(options) ; end
def apt_site ; ancestor(Root).apt_site ; end
def control_file ; ancestor(Root).control_file ; end
def build_archive ; ancestor(Root).build_archive ; end
def jabber ; ancestor(Root).jabber ; end
def jabber_enabled? ; ancestor(Root).jabber_enabled? ; end
def notify(msg) ; ancestor(Root).notify(msg) ; end
def validate_config! ; ancestor(Root).validate_config! ; end
def logger ; ancestor(Root).logger ; end
def fs_listener_factory ; ancestor(Root).fs_listener_factory ; end
def each_package_state(&block)
control_file.distributions.each do |dist|
dist.package_rules.each do |rule|
included = apt_site.included_version(dist.name, rule.package_name)
available = build_archive[rule.package_name]
yield(dist, rule, included, available)
end
end
end
end
class Root < Climate::Command('apt_control')
class << self
include ConfigDSL
end
DEFAULT_CONFIG_FILE_LOCATION = '/etc/apt_control/config.yaml'
config :log_file, "File to send log output to, defaults to /dev/null", :required => false
config :apt_site_dir, "Directory containing apt files"
config :control_file, "Path to control file containing inclusion rules"
config :build_archive_dir, "Directory containing debian build files"
config :jabber_enabled, "Enable jabber integration", :required => false
config :jabber_id, "Jabber ID for notifications", :required => false
config :jabber_password, "Password for connecting to jabber server", :required => false
config :jabber_chatroom_id, "Jabber ID for chatroom to send notifications to", :required => false
config :disable_inotify, "Set to true to disable use of inotify", :required => false
description """
Move packages from an archive in to your reprepro style apt repository.
CONFIG
All configuration can be set by passing an option on the command line, but you can
avoid having to pass these each time by using a config file. By default,
apt_control looks for #{DEFAULT_CONFIG_FILE_LOCATION}, which is expected to be a
YAML file containing a single hash of key value/pairs for each option.
#{configs.map {|k, d| "#{k}: #{d}" }.join("\n\n") }
"""
opt :config_file, "Alternative location for config file",
:type => :string, :short => 'f'
opt :config_option, "Supply a config option on the command line", :multi => true,
:type => :string, :short => 'o'
def config
@config ||= build_config
end
#
# Read yaml file if one exists, then apply overrides from the command line
#
def build_config
file = [options[:config_file], DEFAULT_CONFIG_FILE_LOCATION].
compact.find {|f| File.exists?(f) }
hash =
if file
YAML.load_file(file).each do |key, value|
stderr.puts("Warn: Unknown key in config file: #{key}") unless
self.class.configs.find {|opt| opt.first.to_s == key.to_s }
end
else
{}
end
options[:config_option].map {|str| str.split('=') }.
inject(hash) {|m, (k,v)| m.merge(k.to_sym => v) }
end
def validate_config!
self.class.configs.each do |key, desc, options|
if options[:required]
config[key] or raise Climate::ExitException, "Error: No config supplied for #{key}"
end
end
if config[:jabber_enabled]
self.class.configs.each do |key, desc, options|
next unless key.to_s['jabber_']
config[key] or raise Climate::ExitException, "Error: you must supply all jabber options if jabber is enabled"
end
end
Celluloid.logger = logger
end
def logger
log_file = config[:log_file] || '/dev/null'
@logger ||= Logger.new(log_file == 'STDOUT' ? STDOUT : log_file).tap do |logger|
logger.level = Logger::DEBUG
end
end
def package_states
@package_states ||= PackageStates.new(apt_site: apt_site,
build_archive: build_archive,
control_file: control_file)
end
def apt_site
@apt_site ||= AptSite.new(config[:apt_site_dir], logger)
end
def control_file
@control_file ||= ControlFile.new(config[:control_file], logger)
end
def build_archive
@build_archive ||= BuildArchive.new(config[:build_archive_dir], logger)
end
def jabber
@jabber ||= Jabber.new(:jid => config[:jabber_id], :logger => logger,
:password => config[:jabber_password], :room_jid => config[:jabber_chatroom_id],
:enabled => jabber_enabled?)
end
def jabber_enabled?
config[:jabber_enabled].to_s == 'true'
end
def new_include_cmd(options={})
defaults = {apt_site: apt_site, build_archive: build_archive}
options = options.merge(defaults)
AptControl::Commands::Include.new(options)
end
class FSListenerFactory
attr_reader :disable_inotify
def initialize(options={})
@disable_inotify = options[:disable_inotify]
end
def new(dir, pattern, &on_change)
Listen.to(dir).filter(pattern).tap do |listener|
if disable_inotify
listener.force_polling(true)
listener.polling_fallback_message(false)
else
listener.force_adapter(Listen::Adapters::Linux)
end
listener.change(&on_change)
end
end
end
def fs_listener_factory
@fs_listener_factory ||= FSListenerFactory.new(
disable_inotify: config[:disable_inotify].to_s == 'true')
end
def notify(message)
logger.info("notify: #{message}")
begin
jabber.actor.async.send_message(message)
rescue => e
logger.error("Unable to send notification to jabber: #{e}")
logger.error(e)
end
end
end
end
end
|
require_relative 'test_helper.rb'
require './lib/ship.rb'
class ShipTest < MiniTest::Test
attr_reader :ship, :destroyer, :submarine
def setup
@ship = Ship.new
@destroyer = ship.destroyer
@submarine = ship.submarine
end
def test_destroyer_is_an_array
assert_equal Array, ship.destroyer.class
end
def test_destroyer_array_has_two_identical_elements
assert 2, destroyer.count
assert destroyer[0].eql?(destroyer[1])
end
def test_each_destroyer_element_is_string_d
assert 2, destroyer.bsearch {|e| e == 'd'}
end
def test_submarine_is_an_array
assert_equal Array, submarine.class
end
def test_submarine_has_three_identical_elements
assert_equal 3, submarine.count
assert submarine[0].eql?(submarine[1])
assert submarine[1].eql?(submarine[2])
end
def test_each_submarine_element_is_string_s
assert 3, submarine.bsearch {|e| e == 's'}
end
end
|
Pod::Spec.new do |s|
s.name = 'KRCMulticastDelegate'
s.module_name = 'MulticastDelegate'
s.version = '0.1.6'
s.summary = 'KRCMulticastDelegate - A linked list of delegates, also called an invokation list.'
s.description = <<-DESC
KRCMulticastDelegate - A linked list of delegates, also called an invokation list.
- When a multicast delegate is invoked, the delegates in the list are called synchronously in the order in which they've been added to the delegate table.
- Delegate invocation will run on the caller's thread.
DESC
s.homepage = 'https://github.com/kaosdg/MulticastDelegate'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Karl Catigbe' => 'spam@gmail.com' }
s.social_media_url = 'https://twitter.com/KaosDG'
s.source = { :git => 'https://github.com/kaosdg/MulticastDelegate.git', :tag => s.version.to_s }
s.ios.deployment_target = '9.0'
s.swift_version = '4.0'
s.tvos.deployment_target = '9.0'
s.source_files = ['Sources/**/*.swift', 'Sources/**/*.h']
s.public_header_files = 'Sources/**/*.h'
end
|
# encoding: utf-8
require 'spec_helper'
describe Rubocop::Cop::Lint::UnusedMethodArgument do
subject(:cop) { described_class.new }
before do
inspect_source(cop, source)
end
context 'when a method takes multiple arguments' do
context 'and an argument is unused' do
let(:source) { <<-END }
def some_method(foo, bar)
puts bar
end
END
it 'registers an offense' do
expect(cop.offenses.size).to eq(1)
expect(cop.offenses.first.message).to eq(
'Unused method argument - `foo`. ' \
"If it's necessary, use `_` or `_foo` " \
"as an argument name to indicate that it won't be used."
)
expect(cop.offenses.first.severity.name).to eq(:warning)
expect(cop.offenses.first.line).to eq(1)
expect(cop.highlights).to eq(['foo'])
end
end
context 'and all the arguments are unused' do
let(:source) { <<-END }
def some_method(foo, bar)
end
END
it 'registers offenses and suggests the use of `*`' do
expect(cop.offenses.size).to eq(2)
expect(cop.offenses.first.message).to eq(
'Unused method argument - `foo`. ' \
"If it's necessary, use `_` or `_foo` " \
"as an argument name to indicate that it won't be used. " \
'You can also write as `some_method(*)` if you want the method ' \
"to accept any arguments but don't care about them.")
end
end
end
context 'when a singleton method argument is unused' do
let(:source) { <<-END }
def self.some_method(foo)
end
END
it 'registers an offense' do
expect(cop.offenses.size).to eq(1)
expect(cop.offenses.first.line).to eq(1)
expect(cop.highlights).to eq(['foo'])
end
end
context 'when an underscore-prefixed method argument is unused' do
let(:source) { <<-END }
def some_method(_foo)
end
END
it 'accepts' do
expect(cop.offenses).to be_empty
end
end
context 'when a method argument is used' do
let(:source) { <<-END }
def some_method(foo)
puts foo
end
END
it 'accepts' do
expect(cop.offenses).to be_empty
end
end
context 'when a variable is unused' do
let(:source) { <<-END }
def some_method
foo = 1
end
END
it 'does not care' do
expect(cop.offenses).to be_empty
end
end
context 'when a block argument is unused' do
let(:source) { <<-END }
1.times do |foo|
end
END
it 'does not care' do
expect(cop.offenses).to be_empty
end
end
context 'in a method calling `super` without arguments' do
context 'when a method argument is not used explicitly' do
let(:source) { <<-END }
def some_method(foo)
super
end
END
it 'accepts since the arguments are guaranteed to be the same as ' \
"superclass' ones and the user has no control on them" do
expect(cop.offenses).to be_empty
end
end
end
context 'in a method calling `super` with arguments' do
context 'when a method argument is unused' do
let(:source) { <<-END }
def some_method(foo)
super(:something)
end
END
it 'registers an offense' do
expect(cop.offenses.size).to eq(1)
expect(cop.offenses.first.line).to eq(1)
expect(cop.highlights).to eq(['foo'])
end
end
end
end
|
require 'rails_helper'
describe GlassesService do
let(:service) { GlassesService.new }
let(:user) { FactoryGirl.create(:user) }
let(:wine_name) { "Chemin de Fer" }
let(:vintage) { "2013" }
let(:winemaker_name) { "Lasseter Family Winery" }
let(:rating) { 5 }
describe "#add_a_glass_for_freedom" do
def add_that_glass
service.add_a_glass_for_freedom(wine_name: wine_name,
vintage: vintage,
winemaker_name: winemaker_name,
date: Date.today,
rating: rating,
notes: nil,
user_id: user.id)
end
context "wine does not already exist" do
context "winemaker already exists" do
let!(:winemaker) { FactoryGirl.create(:winemaker, name: winemaker_name) }
it "should add a wine with the existing winemaker and add a glass" do
response = add_that_glass
expect(response.glass).to_not eq(nil)
expect(Wine.find(response.glass.wine.id).name).to eq(wine_name)
expect(Winemaker.find(response.glass.wine.winemaker.id)).to eq(winemaker)
end
end
context "winemaker does not already exist" do
it "should add a wine with a new winemaker and add a glass" do
response = add_that_glass
expect(response.glass).to_not eq(nil)
expect(Wine.find(response.glass.wine_id).name).to eq(wine_name)
expect(Winemaker.find(response.glass.wine.winemaker.id).name).to eq(winemaker_name)
end
end
end
context "wine with same name but different vintage exists" do
let!(:winemaker) { FactoryGirl.create(:winemaker, name: winemaker_name) }
let!(:wine) { FactoryGirl.create(:wine, name: wine_name, vintage: "1000") }
it "should create a new wine and add a glass" do
response = add_that_glass
expect(response.glass).to_not eq(nil)
expect(Wine.find(response.glass.wine_id)).to_not eq(wine)
expect(response.glass.wine.name).to eq(wine_name)
expect(response.glass.wine.vintage).to eq(vintage)
end
end
context "wine already exists" do
let!(:winemaker) { FactoryGirl.create(:winemaker, name: winemaker_name) }
let!(:wine) { FactoryGirl.create(:wine, name: wine_name, vintage: vintage) }
it "should add a glass with the existing wine" do
response = add_that_glass
expect(response.glass).to_not eq(nil)
expect(Wine.find(response.glass.wine_id)).to eq(wine)
expect(response.glass.wine.name).to eq(wine_name)
expect(response.glass.wine.vintage).to eq(vintage)
end
end
end
end
|
require "test_helper"
class CollectionTest < MiniTest::Unit::TestCase
def test_instantiates_with_app_and_name
app, stubs = make_application
users = Orchestrate::Collection.new(app, :users)
assert_equal app, users.app
assert_equal 'users', users.name
end
def test_instantiates_with_client_and_name
client, stubs = make_client_and_artifacts
stubs.head("/v0") { [200, response_headers, ''] }
users = Orchestrate::Collection.new(client, :users)
assert_equal client, users.app.client
assert_equal 'users', users.name
end
def test_destroy
app, stubs = make_application
users = Orchestrate::Collection.new(app, :users)
stubs.delete("/v0/users") do |env|
assert_equal "true", env.params["force"]
[204, response_headers, '']
end
assert true, users.destroy!
end
def test_equality
app, stubs = make_application
app2, stubs = make_application
items1 = app[:items]
items2 = app[:items]
other = app[:other]
assert_equal items1, items2
refute_equal items1, other
refute_equal items1, OpenStruct.new({name: 'items'})
refute_equal items1, 3
refute_equal items1, app2[:items]
assert items1.eql?(items2)
assert items2.eql?(items1)
refute items1.eql?(other)
refute other.eql?(items1)
refute items1.eql?(app2[:items])
# equal? is for object identity only
refute items1.equal?(items2)
refute other.equal?(items1)
end
def test_sorting
app, stubs = make_application
app2, stubs = make_application
assert_equal(-1, app[:users] <=> app[:items])
assert_equal 0, app[:items] <=> app[:items]
assert_equal 1, app[:items] <=> app[:users]
assert_nil 2 <=> app[:items]
assert_nil app2[:items] <=> app[:items]
end
end
|
#
# Cookbook Name:: erlang
# Recipe:: default
#
# Copyright 2013, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
def install_erlang(source, build_dir, file, prefix)
remote_file "#{Chef::Config[:file_cache_path]}/#{file}" do
source source + file
mode '0644'
action :create_if_missing
not_if "test -e #{prefix}/bin/escript"
end
bash "install-erlang-#{build_dir}" do
user 'root'
cwd Chef::Config[:file_cache_path]
code <<-EOH
set -ex
tar xf #{file}
cd #{build_dir}
./otp_build autoconf
./configure --prefix=#{prefix}
nice make -j3
make install
EOH
not_if "test -e #{prefix}/bin/escript"
end
end
install_erlang(
'http://www.erlang.org/download/',
'otp_src_17.0',
'otp_src_17.0.tar.gz',
'/usr/local/erlang-17.0')
install_erlang(
'http://www.erlang.org/download/',
'otp_src_18.1',
'otp_src_18.1.tar.gz',
'/usr/local/erlang-18.1')
|
require File.join(File.dirname(File.expand_path(__FILE__)), "spec_helper")
describe "Sequel::Plugins::StaticCache" do
before do
@db = Sequel.mock
@db.fetch = [{:id=>1}, {:id=>2}]
@db.numrows = 1
@c = Class.new(Sequel::Model(@db[:t]))
@c.columns :id, :name
end
it "should not attempt to validate objects" do
@c.send(:define_method, :validate){errors.add(:name, 'bad')}
proc{@c.plugin(:static_cache)}.should_not raise_error
@c.map{|o| o.valid?}.should == [true, true]
end
shared_examples_for "Sequel::Plugins::StaticCache" do
it "should use a ruby hash as a cache of all model instances" do
@c.cache.should == {1=>@c.load(:id=>1), 2=>@c.load(:id=>2)}
@c.cache[1].should equal(@c1)
@c.cache[2].should equal(@c2)
end
it "should make .[] method with primary key use the cache" do
@c[1].should == @c1
@c[2].should == @c2
@c[3].should be_nil
@c[[1, 2]].should be_nil
@c[nil].should be_nil
@c[].should be_nil
@db.sqls.should == []
end
it "should have .[] with a hash not use the cache" do
@db.fetch = {:id=>2}
@c[:id=>2].should == @c2
@db.sqls.should == ['SELECT * FROM t WHERE (id = 2) LIMIT 1']
end
it "should support cache_get_pk" do
@c.cache_get_pk(1).should == @c1
@c.cache_get_pk(2).should == @c2
@c.cache_get_pk(3).should be_nil
@db.sqls.should == []
end
it "should have each just iterate over the hash's values without sending a query" do
a = []
@c.each{|o| a << o}
a = a.sort_by{|o| o.id}
a.first.should == @c1
a.last.should == @c2
@db.sqls.should == []
end
it "should have map just iterate over the hash's values without sending a query if no argument is given" do
@c.map{|v| v.id}.sort.should == [1, 2]
@db.sqls.should == []
end
it "should have count with no argument or block not issue a query" do
@c.count.should == 2
@db.sqls.should == []
end
it "should have count with argument or block not issue a query" do
@db.fetch = [[{:count=>1}], [{:count=>2}]]
@c.count(:a).should == 1
@c.count{b}.should == 2
@db.sqls.should == ["SELECT count(a) AS count FROM t LIMIT 1", "SELECT count(b) AS count FROM t LIMIT 1"]
end
it "should have map not send a query if given an argument" do
@c.map(:id).sort.should == [1, 2]
@db.sqls.should == []
@c.map([:id,:id]).sort.should == [[1,1], [2,2]]
@db.sqls.should == []
end
it "should have map without a block or argument not raise an exception or issue a query" do
@c.map.to_a.should == @c.all
@db.sqls.should == []
end
it "should have map without a block not return a frozen object" do
@c.map.frozen?.should == false
end
it "should have map with a block and argument raise" do
proc{@c.map(:id){}}.should raise_error(Sequel::Error)
end
it "should have other enumerable methods work without sending a query" do
a = @c.sort_by{|o| o.id}
a.first.should == @c1
a.last.should == @c2
@db.sqls.should == []
end
it "should have all return all objects" do
a = @c.all.sort_by{|o| o.id}
a.first.should == @c1
a.last.should == @c2
@db.sqls.should == []
end
it "should have all not return a frozen object" do
@c.all.frozen?.should == false
end
it "should have all return things in dataset order" do
@c.all.should == [@c1, @c2]
end
it "should have to_hash without arguments run without a query" do
a = @c.to_hash
a.should == {1=>@c1, 2=>@c2}
a[1].should == @c1
a[2].should == @c2
@db.sqls.should == []
end
it "should have to_hash with arguments return results without a query" do
a = @c.to_hash(:id)
a.should == {1=>@c1, 2=>@c2}
a[1].should == @c1
a[2].should == @c2
a = @c.to_hash([:id])
a.should == {[1]=>@c1, [2]=>@c2}
a[[1]].should == @c1
a[[2]].should == @c2
@c.to_hash(:id, :id).should == {1=>1, 2=>2}
@c.to_hash([:id], :id).should == {[1]=>1, [2]=>2}
@c.to_hash(:id, [:id]).should == {1=>[1], 2=>[2]}
@c.to_hash([:id], [:id]).should == {[1]=>[1], [2]=>[2]}
@db.sqls.should == []
end
it "should have to_hash not return a frozen object" do
@c.to_hash.frozen?.should == false
end
it "should have to_hash_groups without arguments return the cached objects without a query" do
a = @c.to_hash_groups(:id)
a.should == {1=>[@c1], 2=>[@c2]}
a[1].first.should == @c1
a[2].first.should == @c2
a = @c.to_hash_groups([:id])
a.should == {[1]=>[@c1], [2]=>[@c2]}
a[[1]].first.should == @c1
a[[2]].first.should == @c2
@c.to_hash_groups(:id, :id).should == {1=>[1], 2=>[2]}
@c.to_hash_groups([:id], :id).should == {[1]=>[1], [2]=>[2]}
@c.to_hash_groups(:id, [:id]).should == {1=>[[1]], 2=>[[2]]}
@c.to_hash_groups([:id], [:id]).should == {[1]=>[[1]], [2]=>[[2]]}
@db.sqls.should == []
end
it "subclasses should work correctly" do
c = Class.new(@c)
c.all.should == [c.load(:id=>1), c.load(:id=>2)]
c.to_hash.should == {1=>c.load(:id=>1), 2=>c.load(:id=>2)}
@db.sqls.should == ['SELECT * FROM t']
end
it "set_dataset should work correctly" do
ds = @c.dataset.from(:t2)
ds.instance_variable_set(:@columns, [:id])
ds._fetch = {:id=>3}
@c.dataset = ds
@c.all.should == [@c.load(:id=>3)]
@c.to_hash.should == {3=>@c.load(:id=>3)}
@c.to_hash[3].should == @c.all.first
@db.sqls.should == ['SELECT * FROM t2']
end
end
describe "without options" do
before do
@c.plugin :static_cache
@c1 = @c.cache[1]
@c2 = @c.cache[2]
@db.sqls
end
it_should_behave_like "Sequel::Plugins::StaticCache"
it "should work correctly with composite keys" do
@db.fetch = [{:id=>1, :id2=>1}, {:id=>2, :id2=>1}]
@c = Class.new(Sequel::Model(@db[:t]))
@c.columns :id, :id2
@c.set_primary_key([:id, :id2])
@c.plugin :static_cache
@db.sqls
@c1 = @c.cache[[1, 2]]
@c2 = @c.cache[[2, 1]]
@c[[1, 2]].should equal(@c1)
@c[[2, 1]].should equal(@c2)
@db.sqls.should == []
end
it "all of the static cache values (model instances) should be frozen" do
@c.all.all?{|o| o.frozen?}.should == true
end
it "should make .[] method with primary key return cached instances" do
@c[1].should equal(@c1)
@c[2].should equal(@c2)
end
it "should have cache_get_pk return cached instances" do
@c.cache_get_pk(1).should equal(@c1)
@c.cache_get_pk(2).should equal(@c2)
end
it "should have each yield cached objects" do
a = []
@c.each{|o| a << o}
a = a.sort_by{|o| o.id}
a.first.should equal(@c1)
a.last.should equal(@c2)
end
it "should have other enumerable methods work yield cached objects" do
a = @c.sort_by{|o| o.id}
a.first.should equal(@c1)
a.last.should equal(@c2)
end
it "should have all return cached instances" do
a = @c.all.sort_by{|o| o.id}
a.first.should equal(@c1)
a.last.should equal(@c2)
end
it "should have to_hash without arguments use cached instances" do
a = @c.to_hash
a[1].should equal(@c1)
a[2].should equal(@c2)
end
it "should have to_hash with arguments return cached instances" do
a = @c.to_hash(:id)
a[1].should equal(@c1)
a[2].should equal(@c2)
a = @c.to_hash([:id])
a[[1]].should equal(@c1)
a[[2]].should equal(@c2)
end
it "should have to_hash_groups without single argument return the cached instances" do
a = @c.to_hash_groups(:id)
a[1].first.should equal(@c1)
a[2].first.should equal(@c2)
a = @c.to_hash_groups([:id])
a[[1]].first.should equal(@c1)
a[[2]].first.should equal(@c2)
end
it "should not allow the saving of new objects" do
proc{@c.create}.should raise_error(Sequel::HookFailed)
end
it "should not allow the saving of existing objects" do
@db.fetch = {:id=>1}
proc{@c.first(:id=>1).save}.should raise_error(Sequel::HookFailed)
end
it "should not allow the destroying of existing objects" do
@db.fetch = {:id=>1}
proc{@c.first(:id=>1).destroy}.should raise_error(Sequel::HookFailed)
end
end
describe "with :frozen=>false option" do
before do
@c.plugin :static_cache, :frozen=>false
@c1 = @c.cache[1]
@c2 = @c.cache[2]
@db.sqls
end
it_should_behave_like "Sequel::Plugins::StaticCache"
it "record retrieved by primary key should not be frozen" do
@c[1].frozen?.should == false
@c.cache_get_pk(1).frozen?.should == false
end
it "none of values returned in #all should be frozen" do
@c.all.all?{|o| !o.frozen?}.should == true
end
it "none of values yielded by each should be frozen" do
a = []
@c.each{|o| a << o}
a.all?{|o| !o.frozen?}.should == true
end
it "none of values yielded by Enumerable method should be frozen" do
@c.sort_by{|o| o.id}.all?{|o| !o.frozen?}.should == true
end
it "none of values returned by map without an argument or block should be frozen" do
@c.map{|o| o}.all?{|o| !o.frozen?}.should == true
@c.map.all?{|o| !o.frozen?}.should == true
end
it "none of values in the hash returned by to_hash without an argument should be frozen" do
@c.to_hash.values.all?{|o| !o.frozen?}.should == true
end
it "none of values in the hash returned by to_hash with a single argument should be frozen" do
@c.to_hash(:id).values.all?{|o| !o.frozen?}.should == true
end
it "none of values in the hash returned by to_hash with a single array argument should be frozen" do
@c.to_hash([:id, :id]).values.all?{|o| !o.frozen?}.should == true
end
it "none of values in the hash returned by to_hash_groups with a single argument should be frozen" do
@c.to_hash_groups(:id).values.flatten.all?{|o| !o.frozen?}.should == true
end
it "none of values in the hash returned by to_hash_groups with a single array argument should be frozen" do
@c.to_hash_groups([:id, :id]).values.flatten.all?{|o| !o.frozen?}.should == true
end
it "should not automatically update the cache when creating new model objects" do
o = @c.new
o.id = 3
@db.autoid = 3
@db.fetch = [[{:id=>1}, {:id=>2}, {:id=>3}], [{:id=>3}]]
o.save
@c[3].should == nil
end
it "should not automatically update the cache when updating model objects" do
o = @c[2]
@db.fetch = [[{:id=>1}, {:id=>2, :name=>'a'}]]
o.update(:name=>'a')
@c[2].values.should == {:id=>2}
end
it "should not automatically update the cache when updating model objects" do
o = @c[2]
@db.fetch = [[{:id=>1}]]
o.destroy
@c[2].should == @c2
end
end
end
|
class GithubService
def initialize(token)
@token = token
end
def get_repos
get_json("/user/repos?per_page=5")
end
def get_followers
get_json("/user/followers")
end
def get_followed_users
get_json("/user/following")
end
def get_members(github_handle)
get_json("/users/#{github_handle}")
end
private
def get_json(url)
@response ||= conn.get(url)
@parsed ||= JSON.parse(@response.body, symbolize_names: true)
end
def conn
Faraday.new(:url => 'https://api.github.com') do |faraday|
faraday.headers['Authorization'] = "token #{@token}"
faraday.adapter Faraday.default_adapter
end
end
end |
module StatCalculationHelper
def self.calculate_accuracy(score)
# https://osu.ppy.sh/help/wiki/Accuracy
d = 300 * (score.count_miss + score.count_50 + score.count_100 + score.count_300)
if d.zero?
Rails.logger.tagged(self.class.name) { Rails.logger.debug "Denominator for accuracy calculation of score #{score} is zero, using zero acc instead." }
return 0
end
n = ((50 * score.count_50) + (100 * score.count_100) + (300 * score.count_300))
n / d.to_f
end
def self.fc?(score, beatmap)
score['count_miss'].to_i.zero? && (beatmap.max_combo - score['max_combo'].to_i) <= 0.01 * beatmap.max_combo
end
end
|
require 'spec_helper'
describe "NonConsumables" do
describe "GET /non_consumables" do
let!(:non_consumable) { Factory(:non_consumable) }
before(:each) do
visit non_consumables_path
end
it "should be successful" do
page.should have_content("Listing Non Consumables")
end
it "should have a link to create new non_consumable" do
click_link("New Product")
page.should have_content("New Non Consumable")
end
it "should show created non_consumables" do
page.should have_content(non_consumable.product_id)
end
it "should have link for editing non_consumables" do
click_link "Edit"
page.should have_content("Editing Non Consumable")
end
it "should have link for showing non_consumables" do
click_link "Show"
page.should have_content("Name:")
end
it "should have link for deleting non_consumables" do
pending("Need to implement this. This is working in app")
end
end
describe "GET /non_consumables/new" do
before(:each) do
visit new_non_consumable_path
fill_in 'Product ID', with: 'com.example.issue.1'
fill_in 'Name', with: 'Product Name'
end
it "should save if the product is valid" do
click_button "Create Non consumable"
page.should have_content("Non consumable was successfully created.")
end
it "should render new template if non_consumable is not valid" do
fill_in 'Product ID', with: nil
click_button "Create Non consumable"
page.should have_content("Some errors were found, please take a look:")
end
it "should redirect to index once subscription is saved" do
click_button "Create Non consumable"
page.should have_content("Listing Non Consumables")
end
end
describe "GET /non_consumables/edit" do
let!(:non_consumable) { Factory(:non_consumable) }
before(:each) do
visit edit_non_consumable_path(non_consumable)
end
it "should update the non consumable" do
fill_in 'Name', with: "My New name"
click_button "Update Non consumable"
non_consumable.reload
non_consumable.name.should eq("My New name")
end
it "should redirect to index once non consumable is updated" do
click_button "Update Non consumable"
page.should have_content("Listing Non Consumables")
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Board, type: :model do
it { should validate_presence_of(:rows) }
it { should validate_presence_of(:cols) }
it { should validate_presence_of(:mines_percentage) }
it { should have_many(:cells).dependent(:destroy) }
it { should belong_to(:game) }
end
|
class RemoveRoleIdFromIdeas < ActiveRecord::Migration
def change
remove_column :ideas, :role_id, :integer
end
end
|
module PowerAPI
module Data
class Section
def initialize(details)
@details = details
# Occasionally, a section won't have any final_grades objects
if @details[:final_grades] != nil
@final_grades = {}
@details[:final_grades].each do |final_grade|
@final_grades[
@details[:reporting_terms][final_grade["reportingTermId"]]
] = final_grade["percent"]
end
else
@final_grades = nil
end
end
def assignments
@details[:assignments]
end
def expression
@details[:section]["expression"]
end
def final_grades
@final_grades
end
def name
@details[:section]["schoolCourseTitle"]
end
def room_name
@details[:section]["roomName"]
end
def teacher
{
:first_name => @details[:teacher]["firstName"],
:last_name => @details[:teacher]["lastName"],
:email => @details[:teacher]["email"],
:school_phone => @details[:teacher]["schoolPhone"]
}
end
end
end
end
|
class Mcq < ActiveRecord::Base
attr_accessible :correct_answer_id, :creator_id, :description, :max_grade, :order
belongs_to :creator, class_name: "User"
has_many :mcq_answers, dependent: :destroy
has_many :std_mcq_answers, dependent: :destroy
has_many :asm_qns, as: :qn, dependent: :destroy
end
|
module Orthographer
class Checker
def self.check(filename, personal_dict: nil)
new(filename, personal_dict: personal_dict).check
end
def initialize(filename, personal_dict: nil)
@filename = filename
@personal_dict = personal_dict
@line = 1
end
def check
results = []
for output_line in output_lines
results << output_line.result_for(@line)
@line += 1 if output_line.empty?
end
results.compact
end
private
def output
@output ||= `#{commands.join(' | ')}`
end
def commands
[
cat_file,
remove_code_blocks,
remove_special_character_lines,
mask_inline_code,
check_spelling
]
end
def cat_file
"cat #{@filename}"
end
def remove_code_blocks
%q|ruby -e 'puts gets(nil).gsub(/```.*```\n/m) { "\n" * $~.to_s.split("\n").count }'|
end
def remove_special_character_lines
"sed 's/^[^[:alnum:]]*$//g'"
end
def mask_inline_code
%q|ruby -pne '$_.gsub!(/`([^`]*)`/) { "`#{?1 * $~[1].length}`" }'|
end
def check_spelling
command = 'hunspell -a'
command << " -p #{@personal_dict}" if @personal_dict
command
end
def output_lines
output.split("\n").map &OutputLine.method(:new)
end
end
end
|
class BackstagePass < Item
def initialize(base_item)
@name = base_item.name
@sell_in = base_item.sell_in
@quality = base_item.quality
end
def update_item_quality
increase_quality
increase_quality if @sell_in < 11
increase_quality if @sell_in < 6
end
def update_item_sell_in
@sell_in -= 1
end
def update_expired_item
@quality = 0
end
def increase_quality
@quality += 1 if @quality < 50
end
def expired?
@sell_in < 0
end
end
|
class RemoveTransactionIdfromTransactions < ActiveRecord::Migration
def change
remove_column :transactions, :transaction_id
end
end
|
# frozen-string-literal: true
module Sequel
class Database
# ---------------------
# :section: 3 - Methods that create datasets
# These methods all return instances of this database's dataset class.
# ---------------------
# Returns a dataset for the database. If the first argument is a string,
# the method acts as an alias for Database#fetch, returning a dataset for
# arbitrary SQL, with or without placeholders:
#
# DB['SELECT * FROM items'].all
# DB['SELECT * FROM items WHERE name = ?', my_name].all
#
# Otherwise, acts as an alias for Database#from, setting the primary
# table for the dataset:
#
# DB[:items].sql #=> "SELECT * FROM items"
def [](*args)
args.first.is_a?(String) ? fetch(*args) : from(*args)
end
# Returns a blank dataset for this database.
#
# DB.dataset # SELECT *
# DB.dataset.from(:items) # SELECT * FROM items
def dataset
@dataset_class.new(self)
end
# Returns a dataset instance for the given SQL string:
#
# ds = DB.fetch('SELECT * FROM items')
#
# You can then call methods on the dataset to retrieve results:
#
# ds.all
# # SELECT * FROM items
# # => [{:column=>value, ...}, ...]
#
# If a block is given, it is passed to #each on the resulting dataset to
# iterate over the records returned by the query:
#
# DB.fetch('SELECT * FROM items'){|r| p r}
# # {:column=>value, ...}
# # ...
#
# +fetch+ can also perform parameterized queries for protection against SQL
# injection:
#
# ds = DB.fetch('SELECT * FROM items WHERE name = ?', "my name")
# ds.all
# # SELECT * FROM items WHERE name = 'my name'
#
# See caveats listed in Dataset#with_sql regarding datasets using custom
# SQL and the methods that can be called on them.
def fetch(sql, *args, &block)
ds = @default_dataset.with_sql(sql, *args)
ds.each(&block) if block
ds
end
# Returns a new dataset with the +from+ method invoked. If a block is given,
# it acts as a virtual row block
#
# DB.from(:items) # SELECT * FROM items
# DB.from{schema[:table]} # SELECT * FROM schema.table
def from(*args, &block)
if block
@default_dataset.from(*args, &block)
elsif args.length == 1 && (table = args[0]).is_a?(Symbol)
@default_dataset.send(:cached_dataset, :"_from_#{table}_ds"){@default_dataset.from(table)}
else
@default_dataset.from(*args)
end
end
# Returns a new dataset with the select method invoked.
#
# DB.select(1) # SELECT 1
# DB.select{server_version.function} # SELECT server_version()
# DB.select(:id).from(:items) # SELECT id FROM items
def select(*args, &block)
@default_dataset.select(*args, &block)
end
end
end
|
class ApiFileLog
attr_accessor :directory
FILENAME = 'access.csv'
def initialize directory
Dir.mkdir directory unless Dir.exists? directory
@directory = directory
end
def log object
return unless object.respond_to? :to_csv
log_file = File.new log_file_name.to_s, "a"
log_file.write object.csv_header if log_file.size == 0
log_file.write "#{object.to_csv}"
log_file.close
end
private
def log_file_name
Pathname.new [Rails.root, @directory, ApiFileLog::FILENAME].join '/'
end
end |
module Middleman
module BlogPage
class Options
KEYS = [
:prefix,
:permalink,
:sources,
:layout,
:default_extension
]
KEYS.each do |name|
attr_accessor name
end
def initialize(options={})
options.each do |k,v|
self.send(:"#{k}=", v)
end
end
end
class << self
def registered(app, options_hash={}, &block)
require 'middleman-blog/blog_page_data'
require 'middleman-blog/blog_page_article'
require 'active_support/core_ext/time/zones'
app.send :include, Helpers
options = Options.new(options_hash)
yield options if block_given?
options.permalink ||= ":title.html"
options.sources ||= "pages/:title.html"
options.layout ||= "layout"
options.default_extension ||= ".markdown"
# If "prefix" option is specified, all other paths are relative to it.
if options.prefix
options.prefix = "/#{options.prefix}" unless options.prefix.start_with? '/'
options.permalink = File.join(options.prefix, options.permalink)
options.sources = File.join(options.prefix, options.sources)
end
app.after_configuration do
# Make sure ActiveSupport's TimeZone stuff has something to work with,
# allowing people to set their desired time zone via Time.zone or
# set :time_zone
Time.zone = self.time_zone if self.respond_to?(:time_zone)
time_zone = Time.zone if Time.zone
zone_default = Time.find_zone!(time_zone || 'UTC')
unless zone_default
raise 'Value assigned to time_zone not recognized.'
end
Time.zone_default = zone_default
# Initialize blog with options
blog_page(options)
sitemap.register_resource_list_manipulator(
:blog_pages,
blog_page,
false
)
end
end
alias :included :registered
end
# Helpers for use within templates and layouts.
module Helpers
# Get the {BlogPageData} for this site.
# @return [BlogPageData]
def blog_page(options=nil)
@_blog_page ||= BlogPageData.new(self, options)
end
# Determine whether the currently rendering template is a blog article.
# This can be useful in layouts.
# @return [Boolean]
def is_blog_page?
!current_blog_page.nil?
end
# Get a {Resource} with mixed in {BlogArticle} methods representing the current article.
# @return [Middleman::Sitemap::Resource]
def current_blog_page
blog_page.page(current_resource.path)
end
def current_blog_page?(page)
current_blog_page == page
end
# Returns the list of articles to display on this page.
# @return [Array<Middleman::Sitemap::Resource>]
def blog_pages
blog_page.pages
end
end
end
end
|
# -*- coding: utf-8 -*-
module Plugin::Search
class Search < Diva::Model
extend Memoist
register :search_search, name: Plugin[:search]._('検索')
field.string :query, required: true
field.has :world, Diva::Model, required: true
handle ->uri {
uri.scheme == 'search' && find_world(uri) && uri.path.size >= 2
} do |uri|
host = CGI.unescape(uri.host)
new(query: CGI.unescape(uri.path), world: find_world(uri))
end
def self.find_world(uri)
Plugin.collect(:worlds).lazy.map { |w|
w.slug.to_s
}.find(CGI.unescape(uri.host))
end
def title
Plugin[:search]._("「%{query}」を%{world}で検索") % {query: query, world: world.title}
end
def uri
Diva::URI.new("search://#{CGI.escape(self.world.slug.to_s)}/#{CGI.escape(self.query)}")
end
end
end
|
Rails.application.routes.draw do
devise_for :users
get 'hello_world', to: 'hello_world#index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
#
get 'admin/*all', to: 'admin/home#index', constraints: { all: /.*/ }
namespace 'api' do
post 'auth', to: 'auth#create'
end
end
|
# frozen_string_literal: true
FactoryBot.define do
factory :line_up, class: PlayerStatistics::Models::LineUp do
team
trait :with_players do
transient do
count { 15 }
end
after(:create) do |line_up, evaluator|
create_list(:player, evaluator.count).each do |player|
line_up.add_player(player)
end
end
end
trait :with_game do
after(:create) do |line_up|
create(:game, line_up_1_id: line_up.id)
end
end
end
end
|
class PanelsController < ApplicationController
before_action :set_panel, only: :show
def index
@panels = Panel.paginate(page: params[:page], per_page:5)
end
def show
@panel = Panel.find(params[:id])
end
private
def set_panel
@panel = Panel.find(params[:id])
end
end
|
require_relative 'weapon'
require "pry"
class BattleBot
@@count = 0
attr_reader :name, :health, :enemies, :weapon
def initialize(name)
@name = name
@health = 100
@enemies = []
@weapon = nil
@@count += 1
end
def dead?
@health > 0 ? false : true
end
def take_damage(damage)
return @health if damage.nil?
if damage.is_a?(Fixnum)
@health - damage >= 0 ? @health -= damage : @health = 0
@@count -= 1 if @health == 0
@health
else
raise(ArgumentError)
end
end
def has_weapon?
@weapon ? true : false
end
def pick_up(weapon)
if weapon.is_a?(Weapon)
raise (ArgumentError) if !weapon.bot.nil?
if @weapon.nil?
@weapon = weapon
@weapon.bot = self
return @weapon
else
nil
end
else
raise(ArgumentError)
end
end
def drop_weapon
@weapon.bot = nil
@weapon = nil
end
def heal
return @health if dead?
@health + 10 <= 100 ? @health += 10 : @health = 100
end
def attack(bot)
if !bot.is_a?(BattleBot) || bot == self || self.weapon.nil?
raise(ArgumentError)
else
bot.receive_attack_from(self)
end
end
def receive_attack_from(bot)
if !bot.is_a?(BattleBot) || bot == self || bot.weapon.nil?
raise(ArgumentError)
else
if !bot.dead? && !dead? && bot.has_weapon?
@enemies << bot if !@enemies.index(bot)
take_damage(bot.weapon.damage)
defend_against(bot)
end
end
end
def defend_against(bot)
if !bot.is_a?(BattleBot) || bot == self
raise(ArgumentError)
else
if !dead? && !bot.dead? && has_weapon?
attack(bot)
end
end
end
def self.count
@@count
end
end
|
class RemoveProjectIdFromBidCategories < ActiveRecord::Migration
def change
remove_column :bid_categories, :project_id, :integer
end
end
|
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module OpenlocsApp
class Application < Rails::Application
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'Madrid'
config.active_record.time_zone_aware_types = [:datetime]
config.generators do |g|
g.test_framework :rspec,
fixtures: true,
view_specs: false,
helper_specs: false,
routing_specs: false,
controller_specs: false,
request_specs: false
g.fixture_replacement :factory_girl, dir: "spec/factories"
end
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
|
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
self.primary_key = :id
end
|
module Canada_FooterPanel
include PageObject
link(:contact_us_canada, :text => 'CONTACT US')
link(:home_canada, :text => 'HOME')
link(:privacy_canada, :text => 'PRIVACY')
link(:security_canada, :text => 'SECURITY')
link(:privacy_canada, :text => 'PRIVACY')
# link(:privacy_canada, :text => 'PRIVACY')
# link(:CONTACT_US, :id => 'footer_CONTACT US_link')
# link(:home_canada, :id => 'footer_HOME_link')
# link(:careers, :text => 'CAREERS')
# link(:privacy, :text => 'PRIVACY')
# link(:security, :text => 'SECURITY')
#link(:accessibility, :text => 'ACCESSIBILITY')
link(:terms_canada, :text => 'TERMS & CONDITIONS')
section(:footer, :id => 'dynamic_footer_section')
#image(:fdic, :id => 'footerMedia1Img')
#image(:equal_housing_lender, :id => 'footerMedia2Img')
image(:verisign_can, :id => 'footerMedia2Img')
image(:safe_secure_can, :id => 'footerMedia1Img')
image(:verisign_can_ang, :id => 'footerMedia1Img')
image(:safe_secure_can_ang, :id => 'footerMedia0Img')
paragraph(:footer_message, :class => 'type_xsmall')
def wait_for_footer_to_load_canada
wait_until do
footer_element.visible?
end
end
def select_link_canada (footer_link)
self.send("#{footer_link}_element").click
end
def wait_for_external_page_to_load_canada()
wait_until do
@browser.windows.last.url.length > 0
end
end
end |
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.define "master" do |master|
master.vm.box = "ravi/docker"
master.vm.network "private_network", ip: "192.168.50.4"
master.vm.provider "virtualbox" do |vb|
vb.memory = "512"
end
master.vm.provision "shell", inline: <<-SHELL
chmod +x /vagrant/master.sh
/vagrant/master.sh
SHELL
end
config.vm.define "worker1" do |worker1|
worker1.vm.box = "ravi/docker"
worker1.vm.network "private_network", ip: "192.168.50.5"
worker1.vm.provider "virtualbox" do |vb|
vb.memory = "512"
end
worker1.vm.provision "shell", inline: <<-SHELL
chmod +x /vagrant/worker.sh
/vagrant/worker.sh
SHELL
end
config.vm.define "worker2" do |worker2|
worker2.vm.box = "ravi/docker"
worker2.vm.network "private_network", ip: "192.168.50.6"
worker2.vm.provider "virtualbox" do |vb|
vb.memory = "512"
end
worker2.vm.provision "shell", inline: <<-SHELL
chmod +x /vagrant/worker.sh
/vagrant/worker.sh
SHELL
end
end
|
class QuizzesController < ApplicationController
def index
@quizzes = Quiz.all
end
def show
@quiz = Quiz.find(params[:id])
end
def edit
@quiz = Quiz.find(params[:id])
@results = @quiz.results
end
def quiz_results
@quiz = Quiz.find(params[:id])
@quiz.results.build
end
def quiz_questions
@quiz = Quiz.find(params[:id])
@results = @quiz.results
question = @quiz.questions.build
question.choices.build
end
def new
@quiz = Quiz.new
end
def create
@quiz = current_user.quizzes.build(quiz_params)
if @quiz.save
flash[:success] = "Your quiz has been saved."
redirect_to quiz_results_path(@quiz)
else
flash[:notice] = "There was a problem and your quiz wasn't saved. Please try again."
render 'new'
end
end
def update
@quiz = Quiz.find(params[:id])
if @quiz.update_attributes(quiz_params)
flash[:success] = "Quiz updated."
redirect_to @quiz
else
render "edit"
end
end
def update_quiz_results
@quiz = Quiz.find(params[:id])
if @quiz.update_attributes(quiz_params)
flash[:success] = "Your results have been saved."
redirect_to quiz_questions_path(@quiz)
else
render "quiz_results"
end
end
def update_quiz_questions
@quiz = Quiz.find(params[:id])
if @quiz.update_attributes(quiz_params)
flash[:success] = "Your quiz has been created!"
redirect_to @quiz
else
render "quiz_questions"
end
end
private
def quiz_params
params.require(:quiz).permit(:title, :description, results_attributes: [:id, :title, :description, :quiz_id], questions_attributes: [:id, :title, :quiz_id, choices_attributes: [:id, :title, :question_id, :result_id]])
end
end |
RSpec.describe User do
describe "#set_current_game!" do
before do
user.set_current_game! game
end
it "sets the current game" do
expect(user.current_game).to eq game
end
it "clears the current game" do
user.set_current_game! nil
expect(user.current_game).to be_nil
end
it "keeps the game's owner intact when cleared" do
user.set_current_game! nil
expect(game.user).to eq user
end
end
end
|
class CustomersController < ApplicationController
def create
@customer = current_user.customers.new(customer_params)
respond_to do |format|
if @customer.save
format.html
format.js
else
format.html
format.js
end
end
end
def destroy
@customer = current_user.customers.destroy_all
redirect_to root_path
end
private
def customer_params
params.require(:customer).permit(:name, price_point_attributes: [:id, :amount, :action, :target, :currency, :_destroy])
end
end
|
class Booking < ActiveRecord::Base
default_scope { where(canceled_at: nil) }
belongs_to :user
belongs_to :coach, class_name: :User
# Validate associations
validates :user, :coach, presence: true
# Validate attributes
validates :start_at,
:end_at,
presence: true
validate :start_at_now_or_in_future
validate :start_at_before_end_at
private
def start_at_now_or_in_future
if start_at &&
start_at < Time.zone.now
errors.add(:start_at, "should be now or in future")
end
end
def start_at_before_end_at
if start_at &&
end_at &&
start_at >= end_at
errors.add(:start_at, "should be before End At")
end
end
# Not required on Booking. Move check to Scheduler.rb
# def timeshift_is_valid
# if timeshift % availability.duration != 0
# errors.add(:start_at, "hasn't valid timeshift")
# end
# end
# def timeshift
# (availability.opening_of_day.seconds_since_midnight - start_at.seconds_since_midnight) / 60
# end
end
|
module Spotlight
module Resources
##
# A PORO to construct a solr hash for a given Dri Object json
class DriObject
attr_reader :collection
def initialize(attrs = {})
@id = attrs[:id]
@metadata = attrs[:metadata]
@files = attrs[:files]
@solr_hash = {}
end
def to_solr(exhibit:)
with_exhibit(exhibit)
add_document_id
add_depositing_institute
add_label
add_creator
if metadata.key?('subject') && metadata['subject'].present?
add_subject_facet
add_theme_facet
add_subtheme_facet
add_type_facet
add_oral_history_facet
add_collection_facet
if metadata['type'] != ['Collection']
add_grantee_facet
add_grant_facet
end
end
add_temporal_coverage
add_geographical_coverage
add_metadata
add_collection_id
if metadata['type'] == ['Collection']
add_subcollection_type
else
add_image_urls
end
add_thumbnail
solr_hash
end
def with_exhibit(e)
@exhibit = e
end
def compound_id(id)
Digest::MD5.hexdigest("#{exhibit.id}-#{id}")
end
private
attr_reader :id, :exhibit, :metadata, :files, :solr_hash
delegate :blacklight_config, to: :exhibit
def add_creator
solr_hash['readonly_creator_ssim'] = metadata['creator']
end
def add_depositing_institute
if metadata.key?('institute')
metadata['institute'].each do |institute|
if institute['depositing'] == true
solr_hash['readonly_depositing_institute_tesim'] = institute['name']
end
end
end
end
def add_oral_history_facet
solr_hash['readonly_oral_history_ssim'] = dri_object.oral_history
end
def add_subject_facet
solr_hash['readonly_subject_ssim'] = metadata['subject']
end
def add_temporal_coverage
return unless metadata.key?('temporal_coverage') && metadata['temporal_coverage'].present?
solr_hash['readonly_temporal_coverage_ssim'] = dri_object.dcmi_name(metadata['temporal_coverage'])
end
def add_theme_facet
themes = dri_object.themes
return if themes.blank?
solr_hash['readonly_theme_ssim'] = themes
end
def add_thumbnail
files.each do |file|
# skip unless it is an image
next unless file && file.key?(surrogate_postfix)
file_id = file_id_from_uri(file[surrogate_postfix])
solr_hash[thumbnail_field] = "#{iiif_manifest_base}/#{id}:#{file_id}/full/!400,400/0/default.jpg"
solr_hash[thumbnail_list_field] = "#{iiif_manifest_base}/#{id}:#{file_id}/square/100,100/0/default.jpg"
break
end
if ['Oral histories','Grant documentation'].include?(solr_hash['readonly_collection_ssim']) && !solr_hash.key?(thumbnail_list_field)
thumbnail_url = "#{repository_base}/collections/#{metadata['isGovernedBy'].first}/cover"
solr_hash[thumbnail_field] = thumbnail_url
solr_hash[thumbnail_list_field] = thumbnail_url
end
end
def add_subtheme_facet
subthemes = dri_object.subthemes
return if subthemes.blank?
solr_hash['readonly_subtheme_ssim'] = subthemes
end
def add_geographical_coverage
return unless metadata.key?('geographical_coverage') && metadata['geographical_coverage'].present?
solr_hash['readonly_geographical_coverage_ssim'] = dri_object.dcmi_name(metadata['geographical_coverage'])
end
def add_grantee_facet
solr_hash['readonly_grantee_ssim'] = dri_object.grantee
end
def add_grant_facet
solr_hash['readonly_grant_ssim'] = dri_object.grant
end
def add_type_facet
solr_hash['readonly_type_ssim'] = metadata['type'].map(&:strip)
end
def add_document_id
solr_hash['readonly_dri_id_ssim'] = id
solr_hash[blacklight_config.document_model.unique_key.to_sym] = compound_id(id)
end
def add_collection_id
if metadata.key?('isGovernedBy')
solr_hash[collection_id_field] = [compound_id(metadata['isGovernedBy'])]
end
end
def add_collection_facet
return unless metadata.key?('subject') && metadata['subject'].present?
solr_hash['readonly_collection_ssim'] = dri_object.collection
end
def add_subcollection_type
unless metadata['type'] == ['Collection']
solr_hash['readonly_subcollection_type_ssim'] = nil
return
end
return unless metadata['ancestor_title'].present?
root_title = metadata['ancestor_title'].last.downcase
if root_title.include?("grant documentation")
solr_hash['readonly_subcollection_type_ssim'] = if metadata['title'].first.start_with?("Grant")
'grant'
else
'grantee'
end
elsif root_title.include?("oral histories")
solr_hash['readonly_subcollection_type_ssim'] = 'oral'
elsif root_title.include?("publications")
solr_hash['readonly_subcollection_type_ssim'] = 'publications'
end
end
def collection_id_field
:collection_id_ssim
end
def add_image_urls
if solr_hash['readonly_collection_ssim'] == 'Oral histories' && metadata['type'].map(&:strip).include?('audio')
solr_hash[tile_source_field] = related_image_url
else
solr_hash[tile_source_field] = image_urls
end
end
def add_label
return unless title_field && metadata.key?('title')
solr_hash[title_field] = metadata['title']
end
def add_metadata
solr_hash.merge!(object_metadata)
sidecar.update(data: sidecar.data.merge(object_metadata))
sidecar.private! if metadata['type'] == ['Collection']
end
def object_metadata
return {} unless metadata.present?
item_metadata = dri_object.to_solr
create_sidecars_for(*item_metadata.keys)
item_metadata.each_with_object({}) do |(key, value), hash|
next unless (field = exhibit_custom_fields[key])
hash[field.field] = value
end
end
def dri_object
@dri_object ||= metadata_class.new(metadata)
end
def create_sidecars_for(*keys)
missing_keys(keys).each do |k|
exhibit.custom_fields.create! label: k, readonly_field: true
end
@exhibit_custom_fields = nil
end
def missing_keys(keys)
custom_field_keys = exhibit_custom_fields.keys.map(&:downcase)
keys.reject do |key|
custom_field_keys.include?(key.downcase)
end
end
def exhibit_custom_fields
@exhibit_custom_fields ||= exhibit.custom_fields.each_with_object({}) do |value, hash|
hash[value.configuration['label']] = value
end
end
def iiif_manifest_base
Spotlight::Resources::Dri::Engine.config.iiif_manifest_base
end
def repository_base
DriSpotlight::Application.config.repository_base
end
def image_urls
@image_urls ||= files.map do |file|
# skip unless it is an image
next unless file && file.key?(surrogate_postfix)
file_id = file_id_from_uri(file[surrogate_postfix])
"#{iiif_manifest_base}/#{id}:#{file_id}/info.json"
end.compact
end
def related_image_url
results = Blacklight::Solr::Repository.new(blacklight_config).search(
fq: "collection_id_ssim:#{solr_hash[collection_id_field].first} AND readonly_type_ssim:image"
)
docs = results['response']['docs']
return if docs.empty?
related_id = docs[0]['id']
r_doc = ::SolrDocument.find(related_id)
r_doc['content_metadata_image_iiif_info_ssm'] unless r_doc.blank?
end
def file_id_from_uri(uri)
File.basename(URI.parse(uri).path).split("_")[0]
end
def thumbnail_field
blacklight_config.index.try(:thumbnail_field)
end
def thumbnail_list_field
blacklight_config.view.list.try(:thumbnail_field)
end
def tile_source_field
blacklight_config.show.try(:tile_source_field)
end
def title_field
blacklight_config.index.try(:title_field)
end
def sidecar
@sidecar ||= document_model.new(id: compound_id(id)).sidecar(exhibit)
end
def surrogate_postfix
Spotlight::Resources::Dri::Engine.config.surrogate_postfix
end
def document_model
exhibit.blacklight_config.document_model
end
def metadata_class
Spotlight::Resources::DriObject::Metadata
end
###
# A simple class to map the metadata field
# in an object to label/value pairs
# This is intended to be overriden by an
# application if a different metadata
# strucure is used by the consumer
class Metadata
THEMES = ["human rights", "education", "communities"].freeze
SUB_THEMES = [
"lgbtq people", "disability", "migrants", "reconciliation",
"infrastructure", "knowledge and learning", "knowledge application",
"senior citizens", "children and youth", "citizen participation"
].freeze
GRANTEES = [
"glen (organisation)",
"national lgbt federation (ireland)",
"transgender equality network ireland",
"national university of ireland, galway. centre for disability law and policy",
"irish penal reform trust",
"akidwa",
"irish refugee council",
"south tyrone empowerment programme",
"genio (organization)",
"glencree centre for reconciliation",
"disability action northern ireland",
"community foundation for northern ireland",
"immigrant council of ireland",
"northside partnership (dublin, ireland)",
"ireland's age friendly cities and counties programme",
"third age foundation",
"the alzheimer society of ireland",
"barnardos (ireland)",
"we the citizens-university college dublin foundation",
"university college dublin foundation",
"derry theatre trust",
"marriage equality (organisation)",
"greater shankill partnership",
"dublin university educational",
"cork university foundation",
"university of limerick foundation",
"integrated education fund",
"trinity foundation",
"queen's university of belfast foundation",
"galway university foundation"
]
COLLECTIONS = ["grant documentation", "oral histories", "publications", "essays"].freeze
def initialize(metadata)
@metadata = metadata
end
def to_solr
metadata_hash.merge(descriptive_metadata)
end
def curated_collections
return unless metadata.key?('subject') && metadata['subject'].present?
@curated_collections ||= metadata['subject'].select { |s| s.downcase.start_with?('curated collection')}.map { |t| t.split('--')[1..-1].join(' and ') }
end
def collection
return if curated_collections.blank?
curated_collections.select { |c| COLLECTIONS.include?(c.downcase) }[0]
end
def dcmi_name(value)
value.map do |v|
name = v[/\Aname=(?<name>.+?);/i, 'name']
name.try(:strip) || v
end
end
def grantee
return unless metadata.key?('subject') && metadata['subject'].present?
metadata['subject'].select { |s| GRANTEES.include?(s.downcase) }[0]
end
def grant
return unless metadata.key?('subject') && metadata['subject'].present?
grant = metadata['subject'].select { |s| s.start_with?('Grant') }
return if grant.empty?
grant
end
def oral_history
return if curated_collections.blank?
curated_collections.reject do |c|
COLLECTIONS.include?(c.downcase) || THEMES.include?(c.downcase) || SUB_THEMES.include?(c.downcase)
end
end
def themes
return [] if curated_collections.blank?
curated_collections.select { |c| THEMES.include?(c.downcase) }
end
def subthemes
return [] if curated_collections.blank?
curated_collections.select { |c| SUB_THEMES.include?(c.downcase) }
end
private
attr_reader :metadata
def metadata_hash
return {} unless metadata.present?
return {} unless metadata.is_a?(Array)
metadata.each_with_object({}) do |md, hash|
next unless md['label'] && md['value']
hash[md['label']] ||= []
hash[md['label']] += Array(md['value'])
end
end
def descriptive_metadata
desc_metadata_fields.each_with_object({}) do |field, hash|
case field
when 'attribution'
add_attribution(field, hash)
next
when 'temporal_coverage'
add_dcmi_field(field, hash)
next
when 'geographical_coverage'
add_dcmi_field(field, hash)
next
when 'grantee'
add_grantee(field, hash)
next
when 'grant'
add_grant(field, hash)
next
when 'oral_history'
add_oral_history(field, hash)
next
when 'theme'
add_theme(field, hash)
next
when 'subtheme'
add_subtheme(field, hash)
next
when 'collection'
add_collection(field, hash)
next
when 'doi'
add_doi(field, hash)
next
end
next unless metadata[field].present?
hash[field.capitalize] ||= []
hash[field.capitalize] += Array(metadata[field])
end
end
def desc_metadata_fields
%w(description doi creator subject grantee grant oral_history theme subtheme collection geographical_coverage temporal_coverage type attribution rights license)
end
def add_attribution(field, hash)
return unless metadata.key?('institute')
hash[field.capitalize] ||= []
metadata['institute'].each do |institute|
hash[field.capitalize] += Array(institute['name'])
end
end
def add_doi(field, hash)
if metadata['doi'].present? && metadata['doi'].first.key?('url')
hash[field.capitalize] = metadata['doi'].first['url']
end
end
def add_grantee(field, hash)
hash[field.capitalize] ||= []
hash[field.capitalize] = grantee
end
def add_grant(field, hash)
hash[field.capitalize] ||= []
hash[field.capitalize] = grant
end
def add_oral_history(field, hash)
hash[field.capitalize] ||= []
hash[field.capitalize] = oral_history
end
def add_theme(field, hash)
return if themes.empty?
hash[field.capitalize] ||= []
hash[field.capitalize] = themes
end
def add_subtheme(field, hash)
return if subthemes.empty?
hash[field.capitalize] ||= []
hash[field.capitalize] = subthemes
end
def add_collection(field, hash)
hash[field.capitalize] ||= []
hash[field.capitalize] = collection
end
def add_dcmi_field(field, hash)
return unless metadata.key?(field)
hash[field.capitalize] ||= []
hash[field.capitalize] = dcmi_name(metadata[field])
end
end
end
end
end
|
class AddIndexToTradeShipments < ActiveRecord::Migration
def change
add_index :trade_shipments, :sandbox_id
end
end
|
=begin
input: string
output: new string
rules: every uppercase letter is turned lower case and vice versa
data: string
algo:
iterate each character
check if it's uppercase or lower
change into upper or lower on different conditions, or unchanged
=end
def swapcase(string)
changed = string.chars.map do |char|
case
when char =~ /[a-z]/
char.upcase
when char =~ /[A-Z]/
char.downcase
else
char
end
end
changed.join
end
p swapcase('CamelCase') == 'cAMELcASE'
p swapcase('Tonight on XYZ-TV') == 'tONIGHT ON xyz-tv' |
class ChangeLocationContactGroupId < ActiveRecord::Migration
def change
rename_column :user_location_contact_groups, :user_id, :user_location_id
end
end
|
class ActionsController < ApplicationController
before_action :require_signin
before_action :require_admin
def index #show an index of all in the db that belong to opp
@opp = Opportunity.find(params[:opportunity_id])
@actions = @opp.actions
@upcoming = Action.upcoming
end
def show #details view
@opp = Opportunity.find(params[:opportunity_id])
@actionstuff = @opp.actions.find(params[:id])
end
def edit
@opp = Opportunity.find(params[:opportunity_id])
@actionstuff = @opp.actions.find(params[:id])
end
def update
@opp = Opportunity.find(params[:opportunity_id])
@actionstuff = @opp.actions.find(params[:id])
@actionstuff.update(action_params)
redirect_to opportunity_action_path
end
def new
@opp = Opportunity.find(params[:opportunity_id])
@actionstuff = @opp.actions.new
end
def create
@opp = Opportunity.find(params[:opportunity_id])
@actionstuff = @opp.actions.new(action_params)
@actionstuff.save
if @actionstuff.save
redirect_to opportunity_actions_path(@opp), notice: "action was successfully created"
else
render :new
end
end
def destroy
@opp = Opportunity.find(params[:opportunity_id])
@actionstuff = @opp.actions.find(params[:id])
@actionstuff.destroy
redirect_to opportunity_actions_path(@opp)
end
private
def action_params
params.require(:foo).permit(:name, :action_type, :due_date, :next, :completed)
end
end
|
require 'test_helper'
class WarehouseTransactionsControllerTest < ActionDispatch::IntegrationTest
setup do
@warehouse_transaction = warehouse_transactions(:one)
end
test "should get index" do
get warehouse_transactions_url
assert_response :success
end
test "should get new" do
get new_warehouse_transaction_url
assert_response :success
end
test "should create warehouse_transaction" do
assert_difference('WarehouseTransaction.count') do
post warehouse_transactions_url, params: { warehouse_transaction: { date: @warehouse_transaction.date, serial: @warehouse_transaction.serial, status: @warehouse_transaction.status } }
end
assert_redirected_to warehouse_transaction_url(WarehouseTransaction.last)
end
test "should show warehouse_transaction" do
get warehouse_transaction_url(@warehouse_transaction)
assert_response :success
end
test "should get edit" do
get edit_warehouse_transaction_url(@warehouse_transaction)
assert_response :success
end
test "should update warehouse_transaction" do
patch warehouse_transaction_url(@warehouse_transaction), params: { warehouse_transaction: { date: @warehouse_transaction.date, serial: @warehouse_transaction.serial, status: @warehouse_transaction.status } }
assert_redirected_to warehouse_transaction_url(@warehouse_transaction)
end
test "should destroy warehouse_transaction" do
assert_difference('WarehouseTransaction.count', -1) do
delete warehouse_transaction_url(@warehouse_transaction)
end
assert_redirected_to warehouse_transactions_url
end
end
|
require 'fileutils'
require 'libis/workflow/base/work_item'
require 'libis/workflow/task_runner'
module Libis
module Workflow
module Base
# Base module for all workflow runs. It is created by an associated workflow when the workflow is executed.
#
# This module lacks the implementation for the data attributes. It functions as an interface that describes the
# common functionality regardless of the storage implementation. These attributes require some implementation:
#
# - start_date: [Time] the timestamp of the execution of the run
# - job: [Object] a reference to the Job this Run belongs to
# - id: [String] (Optional) a unique run number
#
# Note that ::Libis::Workflow::Base::WorkItem is a parent module and therefore requires implementation of the
# attributes of that module too.
#
# A simple in-memory implementation can be found in ::Libis::Workflow::Run
module Run
include ::Libis::Workflow::Base::WorkItem
attr_accessor :tasks, :action
def work_dir
# noinspection RubyResolve
dir = File.join(Libis::Workflow::Config.workdir, self.name)
FileUtils.mkpath dir unless Dir.exist?(dir)
dir
end
def name
self.job.run_name(self.start_date)
end
def names
Array.new
end
def namepath
self.name
end
def workflow
self.job.workflow
end
def logger
self.properties['logger'] || self.job.logger rescue ::Libis::Workflow::Config.logger
end
# Execute the workflow.
#
# The action parameter defines how the execution of the tasks will behave:
# - With the default :run action each task will be executed regardsless how the task performed on the item
# previously.
# - When using the :retry action a task will not perform on an item if it was successful the last time. This
# allows you to retry a run when an temporary error (e.g. asynchronous wait or halt) occured.
#
# @param [Symbol] action the type of action to take during this run. :run or :retry
def run(action = :run)
self.action = action
unless action == :retry
self.start_date = Time.now
self.options = workflow.prepare_input(self.options)
end
self.tasks = workflow.tasks
configure_tasks self.options
self.save!
runner = Libis::Workflow::TaskRunner.new nil
self.tasks.each do |task|
runner << task
end
runner.run self
end
protected
def configure_tasks(opts)
self.tasks.each { |task| task.apply_options opts }
end
end
end
end
end
|
module Stinger
class Client < ActiveRecord::Base
# has_many :assets
# has_many :vulnerabilities
def assets
Stinger::Sharded::Asset.using(shard_name).all
end
def vulnerabilities
Stinger::Sharded::Vulnerability.using(shard_name).all
end
private
def shard_name
Stinger::Sharded::Utils.shard_name_for(id)
end
end
end
|
# frozen_string_literal: true
module Api
module V1
class BreedsController < ApplicationController
def index
breeds = Breed.all.with_attached_image.order(created_at: :desc)
render json: breeds, each_serializer: BreedSerializer
end
def show
breed = Breed.with_attached_image.find(params[:id])
render json: breed, serializer: BreedSerializer
end
end
end
end
|
class ClientSerializer
include FastJsonapi::ObjectSerializer
attributes :fullname, :email, :phone, :id
attribute :organization_ids do |org|
org.organizations.map(&:id)
end
attribute :organizations do |org|
org.organizations.map { |c| {value: c.id, label: c.name} }
end
end
|
# frozen_string_literal: true
require 'test_helper'
class CommentsControllerTest < ActionDispatch::IntegrationTest
setup do
@article = articles(:one)
@comment = @article.comments
end
test 'should create comment' do
post article_comments_path(@article.id), params: { comment: { body: 'Comment from Alex', commenter: 'Alex' } }
new_comment = Comment.find_by commenter: 'Alex'
assert new_comment.present?
end
test 'should destroy article' do
delete article_comment_path(@article.id, @comment.ids),
headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') }
assert !Comment.exists?(id: @comment.ids)
end
end
|
require 'zlib'
module Microprocess
module Protocol
macro_def :range do |options|
i = options.fetch(:i, :chunk)
o = options.fetch(:o, :range)
seek options.first
max = options.last + 1
pos = options.first
on(:chunk) do |chunk|
if @range_end
emit(:chunk_range, chunk)
else
pos += chunk.size
if pos > max
slice = pos - max
chunk.slice!(chunk.size - slice, chunk.size)
close
@range_end = true
emit(:chunk_range, chunk) if !chunk.empty?
emit(:flush)
else
emit(:chunk_range, chunk)
end
end
end
o
end
macro_def :prepend do |options|
i = options.fetch(:i, :chunk)
o = options.fetch(:o, :prepend)
ok = false
on i do |chunk|
if !ok
ok = true
emit(o, options[:content] + chunk)
else
emit(o, chunk)
end
end
o
end
macro_def :chunk_size do |options|
i = options.fetch(:i, :chunk)
o = options.fetch(:o, :chunk_size)
data_buffer = ""
data_buffer_size = options.fetch(:size, nil)
on i do |chunk|
if chunk.nil?
emit(o, data_buffer) unless data_buffer.empty?
emit(o, nil)
else
data_buffer_size ||= chunk.size
data_buffer << chunk
if data_buffer.size < data_buffer_size
self.next if next?
else
while data_buffer.size >= data_buffer_size
emit(o, data_buffer.slice!(0, data_buffer_size))
end
end
end
end
o
end
macro_def :append do |options|
i = options.fetch(:i, :chunk)
o = options.fetch(:o, :append)
on(i) do |chunk|
if chunk.nil?
emit(o, options[:content])
end
emit(o, chunk)
end
o
end
macro_def :http_chunk do |options|
i = options.fetch(:i, :chunk)
o = options.fetch(:o, :http_chunk)
on(i) do |chunk|
if chunk.nil?
emit(o, "0\r\n")
emit(o, nil)
else
emit(o, "#{chunk.size.to_s(16)}\r\n#{chunk}\r\n")
end
end
o
end
DEFLATE_ARGS = [
Zlib::DEFAULT_COMPRESSION,
-Zlib::MAX_WBITS, # drop the zlib header which causes both Safari and IE to choke
Zlib::DEF_MEM_LEVEL,
Zlib::DEFAULT_STRATEGY
]
# compression
macro_def :deflate do |options|
i = options.fetch(:i, :chunk)
o = options.fetch(:o, :deflate)
deflate = Zlib::Deflate.new(*DEFLATE_ARGS)
on i do |chunk|
if chunk.nil?
emit(o, deflate.finish)
deflate.close
emit(o, nil)
else
chunk = deflate.deflate(chunk, Zlib::SYNC_FLUSH)
emit(o, chunk)
end
end
o
end
# décompression
macro_def :inflate do |options|
i = options.fetch(:i, :chunk)
o = options.fetch(:o, :inflate)
inflate = Zlib::Inflate.new
on i do |chunk|
if chunk.nil?
inflate.close
emit(o, nil)
else
unziped = inflate.inflate(chunk)
unless unziped.empty?
emit(o, unziped)
end
end
end
o
end
end
end
class StringIO
include Events
include Microprocess::Protocol
has :read_size, default: 4096
def next
if c = read(read_size)
emit(:chunk, c)
else
raise StopIteration if @nomore
@nomore = true
emit(:chunk, nil)
end
end
def next?
@nomore.nil?
end
end
class File
include Events
include Microprocess::Protocol
has :read_size, default: 4096
def next
if c = read(read_size)
emit(:chunk, c)
else
raise StopIteration if @nomore
@nomore = true
emit(:chunk, nil)
end
end
def next?
@nomore.nil?
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
namespace :api do
namespace :v1 do
get 'forecast', to: "forecast#index"
get 'backgrounds', to: "backgrounds#show"
post 'users', to: 'user#create'
post 'sessions', to: 'session#create'
post 'favorites', to: 'favorite#create'
get 'favorites', to: 'favorite#index'
end
end
end
|
class CreateRequests < ActiveRecord::Migration
def change
create_table :requests do |t|
t.string :full_name
t.string :email
t.float :price
t.string :location
t.string :rooms
t.boolean :furnished
t.boolean :through_agents
t.text :extra
t.timestamps
end
end
end
|
require File.dirname(__FILE__) + '/../spec_helper'
describe SubscriptionDiscount do
before(:each) do
@discount = SubscriptionDiscount.new(:amount => 5, :code => 'foo')
end
it "should be 0 for amounts less than or equal to zero" do
@discount.calculate(0).should == 0
@discount.calculate(-1).should == 0
end
it "should not be greater than the subtotal" do
@discount.calculate(4).should == 4
end
it "should not be greater than the amount" do
@discount.calculate(5).should == 5
@discount.calculate(6).should == 5
end
it "should calculate based on percentage" do
@discount = SubscriptionDiscount.new(:amount => 0.1, :percent => true)
@discount.calculate(78.99.to_d).to_f.should == 7.9
end
it "should not be available if starting in the future" do
SubscriptionDiscount.new(:start_on => 1.day.from_now.to_date).should_not be_available
end
it "should not be available if ended in the past" do
SubscriptionDiscount.new(:end_on => 1.day.ago.to_date).should_not be_available
end
it "should be available if started in the past" do
SubscriptionDiscount.new(:start_on => 1.week.ago.to_date).should be_available
end
it "should be available if ending in the future" do
SubscriptionDiscount.new(:end_on => 1.week.from_now.to_date).should be_available
end
it "should be 0 if not available" do
@discount = SubscriptionDiscount.new(:amount => 0.1, :percent => true, :end_on => 1.week.ago.to_date)
@discount.calculate(10).should == 0
end
it "should be greater than another discount if the amount is greater than the other one" do
@lesser_discount = SubscriptionDiscount.new(:amount => @discount.amount - 1)
(@discount > @lesser_discount).should be_true
(@discount < @lesser_discount).should be_false
end
it "should not be greater than another discount if the amount is less than the other one" do
@greater_discount = SubscriptionDiscount.new(:amount => @discount.amount + 1)
(@discount > @greater_discount).should be_false
(@discount < @greater_discount).should be_true
end
it "should be greater than another discount if other one is nil" do
(@discount > nil).should be_true
(@discount < nil).should be_false
end
it "should raise an error when comparing percent vs. amount discounts" do
@other_discount = SubscriptionDiscount.new(:amount => 0.1, :percent => true)
lambda { @discount > @other_discount }.should raise_error(SubscriptionDiscount::ComparableError)
end
end |
module Yaks
class Mapper
class Form
extend Forwardable, Util
def_delegators :config, :name, :action, :title, :method,
:media_type, :fields, :dynamic_blocks
def self.create(*args, &block)
args, options = extract_options(args)
options[:name] = args.first if args.first
new(config: Config.build(options, &block))
end
############################################################
# instance
include Attribs.new(:config)
def add_to_resource(resource, mapper, _context)
return resource if config.if && !mapper.expand_value(config.if)
resource.add_form(to_resource_form(mapper))
end
def to_resource_form(mapper)
attrs = {
fields: config.to_resource_fields(mapper),
action: mapper.expand_uri(action)
}
[:name, :title, :method, :media_type].each do |attr|
attrs[attr] = mapper.expand_value(public_send(attr))
end
Resource::Form.new(attrs)
end
end
end
end
|
class Goal < ActiveRecord::Base
belongs_to :position
has_one :player, :through => :position
after_save :complete_game
before_save :timestamp
scope :scored_goal, -> { where(quantity: 1)}
scope :own_goal, -> { where(quantity: -1)}
def timestamp
scored_at = DateTime.now
end
#complete a game if a team reached 10 goals
def complete_game
game = self.position.team.game
isGameComplete = false
game.teams.each do |team|
if team.get_goals_total == 10
team.winner = true
team.save!
game.completed_at = DateTime.now
game.save!
isGameComplete = true
end
end
end
def own_goal?
if self.quantity > 0 then
false
else
true
end
end
def blue_goal?
return (self.position.team.blue? && !self.own_goal?) || (self.position.team.red? && self.own_goal?)
end
def red_goal?
return (self.position.team.red? && self.quantity > 0) || (self.position.team.blue? && self.own_goal?)
end
end
|
class CreateRepairOrderRecords < ActiveRecord::Migration
def change
create_table :repair_order_records do |t|
t.integer :repair_order
t.text :recommendations
t.text :maintenance
t.timestamps null: false
end
end
end
|
class Customer < ApplicationRecord
validates :name,:email,:contact_no, presence: true
validates :email, :uniqueness => { :scope => [:is_deleted], :case_sensitive => false }
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }
default_scope -> { where(is_deleted: false) }
default_scope -> { order(name: :asc) }
include SearchCop
search_scope :search do
attributes :name, :email,:contact_no
end
end
|
class HomeController < ApplicationController
before_action :authenticate_user!, except: [:debug_sign_in]
def index
=begin
# TODO someday, latest 5 updates, most stale updates
if(params[:view] == 'stale')
@scores = Score.order('created_at').limit(5)
else
@scores = Score.order('created_at desc').limit(5)
end
=end
end
def about
@active_nav = "about"
end
def search
#@goals = Goal.all.search(params[:q]) if params[:q].present?
if params[:q].present?
words = params[:q]
@goals = Goal.where('lower(name) LIKE ?',"%#{words.downcase}%")
@teams = Team.where('lower(name) LIKE ?',"%#{words.downcase}%")
#.where("lower(name) LIKE ? ","%#{words.downcase}%").collect{|u| u.goals}.flatten
end
end
#simple GET request login for testing (ONLY works in Dev & Test)
#bypasses domain restrictions and creates a new session
#user must exist in database
def debug_sign_in
if ((Rails.env.test? || Rails.env.development?) && params['email'].present?)
#create this user in the step definition
if(user = User.find_by_email(params['email']))
sign_in user
flash['notice'] = "Successfully signed in as " + user.name.to_s
else
flash['error'] = "Could not find test user with email " + params['email'].to_s
end
redirect_to "/"
end
end
end
|
module Vfs
class File < Entry
# Attributes.
alias_method :exist?, :file?
# CRUD.
def read options = {}, &block
options[:bang] = true unless options.include? :bang
driver.open do
begin
if block
driver.read_file path, &block
else
data = ""
driver.read_file(path){|buff| data << buff}
data
end
rescue StandardError => e
raise Vfs::Error, "can't read Dir #{self}!" if dir.exist?
attrs = get
if attrs and attrs[:file]
# unknown internal error
raise e
elsif attrs and attrs[:dir]
raise Error, "You are trying to read Dir '#{self}' as if it's a File!"
else
if options[:bang]
raise Error, "file #{self} not exist!"
else
block ? block.call('') : ''
end
end
end
end
end
# def content options = {}
# read options
# end
def create options = {}
write '', options
self
end
def write *args, &block
if block
options = args.first || {}
else
data, options = *args
data ||= ""
options ||= {}
end
raise "can't do :override and :append at the same time!" if options[:override] and options[:append]
driver.open do
try = 0
begin
try += 1
if block
driver.write_file(path, options[:append], &block)
else
driver.write_file(path, options[:append]){|writer| writer.write data}
end
rescue StandardError => error
parent = self.parent
if entry.exist?
entry.delete
elsif !parent.exist?
parent.create(options)
else
# unknown error
raise error
end
try < 2 ? retry : raise(error)
end
end
self
end
def append *args, &block
options = (args.last.is_a?(Hash) && args.pop) || {}
options[:append] = true
write(*(args << options), &block)
end
def update options = {}, &block
data = read options
write block.call(data), options
end
def delete
delete_entry
end
# Transfers.
def copy_to to, options = {}
raise Error, "you can't copy to itself" if self == to
target = if to.is_a? File
to
elsif to.is_a? Dir
to.file #(name)
elsif to.is_a? UniversalEntry
to.file
else
raise "can't copy to unknown Entry!"
end
target.write options do |writer|
read(options){|buff| writer.write buff}
end
target
end
def move_to to
copy_to to
delete
to
end
# Extra Stuff.
def render *args
require 'tilt'
args.unshift Object.new if args.size == 1 and args.first.is_a?(Hash)
template = Tilt.new(path){read}
template.render *args
end
def size; get :size end
def basename
::File.basename(name, ::File.extname(name))
end
def extension
::File.extname(name).sub(/^\./, '')
end
end
end |
class Selection < ActiveRecord::Base
belongs_to :cardset
belongs_to :user
end
|
require 'spec_helper'
module TwitterCli
describe "user interface" do
let(:conn) { PG.connect(:dbname => ENV['database']) }
it "should give help to the user when asked for help" do
username = 'anugrah'
help = ' __ __ .__
/ \ / \ ____ | | ____ ____ _____ ____
\ \/\/ _/ __ \| | _/ ___\/ _ \ / \_/ __ \
\ /\ ___/| |_\ \__( <_> | Y Y \ ___/
\__/\ / \___ |____/\___ \____/|__|_| /\___ >
\/ \/ \/ \/ \/
anugrah to TwitchBlade
help
tweet : for tweeting
follow : for following other twitchers
unfollow : for unfollowing other twitchers
timeline : view timeline of self
search : view timeline of other users
stream : view your stream
retweet : retweet
help : for displaying help
logout : for logging out'
user_interface = UserInterface.new(username)
expect(user_interface.process('help')).to eq(help)
end
it "should process if given input is tweet" do
conn.exec('begin')
username = 'anugrah'
msg = 'trolling around'
user_interface = UserInterface.new(username)
allow(user_interface).to receive(:get_tweet) { msg }
expect(user_interface.process('tweet')).to eq("Successfully tweeted")
conn.exec('rollback')
end
it "should process if given input is retweet" do
conn.exec('begin')
user_interface = UserInterface.new('anugrah')
allow(user_interface).to receive(:get_tweet_id) { 4 }
expect(user_interface.process('retweet')).to eq(Retweet.new(conn, 'anugrah', 4).execute)
conn.exec('rollback')
end
it "should process if given input is follow" do
user_interface = UserInterface.new('anugrah')
allow(user_interface).to receive(:user_to_follow) { 'red' }
expect(user_interface.process('follow')).to eq("Successfully followed red")
end
it "should process if given input is unfollow" do
user_interface = UserInterface.new('anugrah')
allow(user_interface).to receive(:user_to_unfollow) { 'red' }
expect(user_interface.process('unfollow')).to eq("Successfully unfollowed red")
end
it "should process if given input is timeline" do
conn.exec('begin')
user_interface = UserInterface.new('anugrah')
expect(user_interface.process('timeline')).to eq(Timeline.new(conn, 'anugrah').process)
conn.exec('rollback')
end
it "should process if given input is search" do
conn.exec('begin')
user_interface = UserInterface.new('anugrah')
allow(user_interface).to receive(:get_name) { 'red' }
expect(user_interface.process('search')).to eq(Timeline.new(conn, 'red').process)
conn.exec('rollback')
end
it "should process if given input is timeline" do
conn.exec('begin')
user_interface = UserInterface.new('anugrah')
expect(user_interface.process('stream')).to eq(Stream.new(conn, 'anugrah').get_stream)
conn.exec('rollback')
end
it "should return appropriate error message if input doesnot match expectations" do
user_interface = UserInterface.new('anugrah')
expect(user_interface.process('foo')).to eq("Not a valid input!")
end
it "should return appropriate error message if input doesnot match expectations" do
user_interface = UserInterface.new('anugrah')
expect(user_interface.process('logout')).to eq("logging out")
end
end
end
|
require 'curb'
require 'json'
require 'open-uri'
class CrmConnector
CRM_URL = "https://kleer.capsulecrm.com/api"
def self.subscribe_person( email, fname, lname, influence_zone_tag )
crm_ids = CrmConnector::get_crm_ids(email)
if crm_ids.size == 0
new_id = CrmConnector::create_person( email, fname, lname )
CrmConnector::add_crm_tag new_id, influence_zone_tag
CrmConnector::add_crm_tag new_id, 'OR-Website'
else
crm_ids.each do |crm_id|
CrmConnector::add_crm_tag crm_id, 'OR-Website'
end
end
end
def self.create_person( email, fname, lname )
c = CrmConnector::create_crm_curl(CRM_URL + "/person")
c.headers['Content-Type'] = 'application/xml'
new_crm_person_xml = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" +
"<person>" +
"<firstName>#{fname}</firstName>" +
"<lastName>#{lname}</lastName>" +
"<contacts>" +
"<email>" +
"<emailAddress>#{email}</emailAddress>" +
"</email>" +
"</contacts>" +
"</person>"
c.http_post( new_crm_person_xml )
redirect_url = c.header_str.match(/Location: (.*)/).to_s
from_index = redirect_url.rindex("/")+1
to_index = redirect_url.length-1
new_id = redirect_url[from_index..to_index].strip
new_id
end
def self.add_crm_tag(id_crm, tag)
if !tag.nil? && tag != ""
encoded_tag = URI::encode(tag)
c = CrmConnector::create_crm_curl(CRM_URL + "/party/#{id_crm}/tag/#{encoded_tag}")
c.http_post
end
end
def self.get_crm_ids(email)
crm_ids = Array.new
encoded_email = URI::encode(email)
c = CrmConnector::create_crm_curl(CRM_URL + "/party?email=#{encoded_email}")
c.headers["Accept"] = "application/json"
c.http_get
response = JSON.parse( c.body_str )
if response["parties"]["@size"].to_i > 0
if response["parties"]["person"].class == Hash
crm_ids << response["parties"]["person"]["id"]
elsif response["parties"]["person"].class == Array
response["parties"]["person"].each do |person|
crm_ids << person["id"]
end
end
end
crm_ids
end
def self.create_crm_curl(url)
c = Curl::Easy.new(url)
c.http_auth_types = :basic
c.username = ENV["KLEER_CRM_TOKEN"]
c.password = ENV["KLEER_CRM_PASSWORD"]
c
end
end
|
module Admin::GroupsHelper
def rights_column(record)
rights = record.rights(:include => :forum)
rights.empty? ? '-' : rights.collect { |r| r.forum }.join(', ')
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Product.create(name: "Pikachu", description: "First edition from Ash himself", price: 100000)
Product.create(name: "Charmander", description: "Great for cooking meals or heating your home!", price: 150000)
Product.create(name: "Mew", description: "Not sure what it does, but it's real cute and psychic", price: 10000000) |
require 'spec_helper'
describe CoordinateCalculator do
coordinates_and_direction = {x:1, y: 2, direction: "N"}
context 'when the instruction is right' do
it 'changes direction to the right' do
cc = described_class.new(coordinates_and_direction.merge instructions: 'R')
cc.calculate_instructions
expect(cc.direction).to be eq((cc.send :r_rules).to_s.upcase)
end
end
end
|
#!/usr/bin/env ruby
class Properties::LaunchEmr
def self.addProps(manager)
manager.add(
ArgOpts.direct("batch.cluster.name", "batch-processing", 'Name of the cluster'),
ArgOpts.direct("batch.cluster.main", "== MAIN CLASS ==", 'Main class to run in the batch cluster'),
ArgOpts.direct("batch.cluster.s3.bucket", "deploy.fineo.io", "s3 bucket where the jar is stored"),
ArgOpts.direct("batch.cluster.s3.key", "== KEY ==", "s3 patch where the jar is stored"))
end
end
|
require 'rails_helper'
RSpec.describe Place, type: :model do
let(:test_place) { create(:place) }
let(:test_book) { create(:book) }
describe "validations" do
it "returns false if the name is not unique" do
test_place
other_place = FactoryGirl.build(:place, name: "Peoria")
expect(other_place.valid?).to eq(false)
end
end
describe "add" do
it "adds book to book_places" do
test_place.add(test_book)
expect(test_place.books.last).to eq(test_book)
end
end
describe "toss" do
it "removes book from book_places" do
test_place.add(test_book)
test_place.toss(test_book)
expect(test_place.books).not_to include(test_book)
end
end
end
|
require 'net/http'
require 'net/https'
require 'rubygems'
require 'json'
require 'yaml'
require 'etc'
class SendEventFailed < StandardError
end
module Squab
class Client
attr_accessor :source, :uid, :api_url, :ssl_verify
attr_accessor :api_version_prefix, :events_prefix
# Opts accepts
# api => The API URL to hit
# user => The user to report
# source => the source to report
def initialize(opts={})
@source = get_my_source(opts[:source])
@uid = get_my_user(opts[:user])
parse_config
@api_url = get_api(opts[:api] || @config[:api])
@ssl_verify = @config['ssl_verify'] || true
@api_version_prefix = @config['api_prefix'] || '/api/v1'
@events_prefix = [@api_version_prefix, 'events'].join('/')
end
def send(event, url=nil)
payload = {
"uid" => @uid,
"source" => @source,
"value" => event,
"url" => url,
}.to_json
header = {'Content-Type' => 'application/json'}
req = Net::HTTP::Post.new(@events_prefix, initheader = header)
req.body = payload
try_count = 1
begin
http = Net::HTTP.new(@api_url.host, @api_url.port)
http = setup_ssl(http) if @api_url.scheme == "https"
response = http.request(req)
rescue EOFError, Errno::ECONNREFUSED => e
raise SendEventFailed, "Could not reach the Squab server"
end
response
end
def list_sources
req = make_request('sources')
get_req(req)
end
def list_users
req = make_request('users')
get_req(req)
end
def list_urls
req = make_request('urls')
get_req(req)
end
def get(max=5, since=nil)
req = if since
make_event_request("since/#{since.to_i}")
else
make_event_request("limit/#{max}")
end
get_req(req)
end
def get_from_event(event_num)
req = make_event_request("starting/#{event_num}")
get_req(req)
end
def get_from_user(username)
req = make_event_request("user/#{username}")
get_req(req)
end
def get_from_source(source)
req = make_event_request("source/#{source}")
get_req(req)
end
def simple_search(search_val)
req = make_event_request("search/value/#{search_val}/limit/5")
get_req(req)
end
def search(search_params)
req = Net::HTTP::Post.new([ @events_prefix, 'search' ].join('/'))
req.body = JSON.dump(search_params)
get_req(req)
end
def get_api(url)
url ? URI.parse(url) : URI.parse(
"http://squab/"
)
end
def parse_config(file=nil)
# Default
config_file = file || '/etc/squab.yaml'
# Instance override
if File.exist?(config_file)
@config = YAML.load(File.open(config_file).read)
else
@config = {}
end
end
def get_my_source(source=nil)
source || File.basename($PROGRAM_NAME)
end
def get_my_user(username=nil)
username || Etc.getpwuid(Process.uid).name
end
private
def setup_ssl(http)
http.use_ssl = true
http.ca_file = OpenSSL::X509::DEFAULT_CERT_FILE
if @ssl_verify
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
else
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
$stderr.puts("Bypassing SSL verification, this should only happen "+
"during testing and development")
end
http.verify_depth = 5
http
end
def get_req(req, full_req=false)
http = Net::HTTP.new(@api_url.host, @api_url.port)
http = setup_ssl(http) if @api_url.scheme == "https"
resp = http.start { |h| h.request(req) }
if full_req
resp
else
resp.body
end
end
def make_event_request(to)
Net::HTTP::Get.new([ @events_prefix, to ].join('/'))
end
def make_request(to)
Net::HTTP::Get.new([ @api_version_prefix, to ].join('/'))
end
end
end
# Old name space, deprecated and should be removed eventually
class SquabClient < Squab::Client
def initialize(api_url=nil, source=nil, uid=nil)
super(:api => api_url, :source => source, :user => uid)
end
end
|
class Quotation
attr_reader :message, :image
def self.get_quotation(mood)
if mood
# quotes= all_options[mood]
mood = all_options[mood].sample
@message= mood[0]
@image= mood[1]
end
Quotation.new(@message, @image)
end
def self.all_options
{
"Mad"=> [ ["“When you're mad, try to sit alone and think back. Remember,
sometimes we need to fix ourselves first before we fix others”- Author Unknown","mad-kitten.jpg"],
["“The only real conflict you will ever have in your life won’t be with others,
but with yourself.” ― Shannon L. Alder","mad2.jpg"],
["“Anybody can become angry - that is easy, but to be angry with the
right person and to the right degree and at the right time and for the right purpose,
and in the right way - that is not within everybody's power and is not easy.” -Aristotle","mad3.jpg"]],
"Sad"=> [ ["“You cannot protect yourself from sadness without protecting yourself from happiness.” ― Jonathan Safran Foer", "sad_dog.jpg"],
["“When I despair, I remember that all through history the way of truth and love have always won. There have been tyrants and murderers, and for a time, they can seem invincible, but in the end, they always fall. Think of it--always.” ― Mahatma Gandhi", "sad2.jpg"],
["“Every man has his secret sorrows which the world knows not; and often times we call a man cold when he is only sad.” ― Henry Wadsworth Longfellow", "sad3.jpg"]],
"Happy"=> [["“It is not how much we have, but how much we enjoy that makes happiness” - Charles Spurgeon", "happy_goat.jpeg" ],
[ "“Folks are usually about as happy as they make their minds up to be.” ― Abraham Lincoln", "happy2.jpg"],
[ "“It's so hard to forget pain, but it's even harder to remember sweetness. We have no scar to show for happiness. We learn so little from peace.” ― Chuck Palahniuk,", "happy3.jpg"],
[ "“Happiness is when what you think, what you say, and what you do are in harmony.” ― Mahatma Gandhi", "happy4.jpg"]],
"Hungry"=>[["“There are people in the world so hungry, that God cannot appear to them except in the form of bread.” ― Mahatma Gandhi", "hungry_cat.jpg"],
[ "“The belly is an ungrateful wretch, it never remembers past favors, it always wants more tomorrow.” ― Aleksandr Solzhenitsyn,", "hungry2.jpg"],
["“When I give food to the poor, they call me a saint. When I ask why the poor have no food, they call me a communist.” ― Hélder Câmara", "hungry3.jpg"]],
"Tired"=> [["“When you come to the end of your rope, tie a knot and hang on.” -Franklin D. Roosevelt", "tired_dog.jpg"],
["“Sleep did not honor me with it’s presence.” ― Alysha Speer", "tired2.jpg"],
["“I'm so tired I never want to wake up again. But I've figured out now that it was never them that made me feel that way. It was just me, all along.” ― Maggie Stiefvater", "tired3.jpeg"]],
"Stressed"=> [["“In times of stress, the best thing we can do for each other is to listen with our ears and our hearts and to be assured that our questions are just as important as our answers.” -Fred \"Mister\" Rogers", "stressed.jpg"],
["“The people in my circle? Those who make me feel blessed; not stressed.”― Steve Maraboli", "stressed2.jpg"],
["“You must learn to let go. Release the stress. You were never in control anyway.” ― Steve Maraboli", "stressed3.jpg"]]
}
end
def initialize(message, image)
@message= message
@image= image
end
end
|
require 'helper'
class NestedConfigEvaluateOnceTest < NestedConfigSpec
let(:config) do
Class.new(NestedConfig) do
include NestedConfig::EvaluateOnce
end.new
end
context "evaluates once w/o argument" do
context "w/o argument" do
before do
config.startup_time = proc { Time.now }
end
test "has time value" do
assert_instance_of Time, config.startup_time
end
test "value does not change" do
n = config.startup_time
assert_same n, config.startup_time
end
end
context "with argument" do
before do
config.env = proc { |e| e.to_s.upcase }
config.env(:development)
end
test "replaces original value" do
assert_equal "DEVELOPMENT", config.env
end
test "value does not change" do
env = config.env
assert_same env, config.env
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.