text stringlengths 10 2.61M |
|---|
module TacticCommandModule
@template = {}
Index = {
:basic => [
# category #condition # args # action # args
[:targeting, :nearest_visible, [true], :set_target, [nil] ],
[:fighting, :any, [true], :attack_mainhoof, [nil] ],
]
}
def self.load_template(symbol, battler)
commands = @template[symbol].collect{|command| command.dup}
commands.each do |command|
command.battler = battler
command.action.user = battler
end
return commands
end
def self.compile_modules
Index.each do |key, commands|
result = []
commands.each do |command|
cmd = Game_TacticCommand.new(nil, command[2])
cmd.category = command[0]
cmd.condition_symbol = command[1]
cmd.action = Game_Action.new(nil, nil, command[3])
result.push(cmd)
end
@template[key] = result
end
end
compile_modules
end
|
require 'rails_helper'
describe SessionsController do
describe "GET#{}new" do
it "renders the :new template" do
get :new
expect(response).to render_template :new
end
end
describe "POST#create" do
before :each do
@user = create(:user, username:'user1', password: 'oldpassword', password_confirmation: 'oldpassword')
end
context "with valid username and password" do
it "assigns user to session variable" do
post :create, params:{ username: 'user1', password: 'oldpassword' }
expect(session[:user_id]).to eq(@user.id)
end
it "redirect to admin index page" do
post :create, params:{ username: 'user1', password: 'oldpassword' }
expect(response).to redirect_to store_index_url
end
end
context "with invalid username and password" do
it "redirect to login page" do
post :create, params:{ username: 'user1', password: 'wrongpassword' }
expect(response).to redirect_to login_url
end
end
end
describe "DELETE#destroy" do
before :each do
@user = create(:user)
end
it "remove user_id from session " do
delete :destroy, params: {id:@user}
expect(session[:user_id]).to eq(nil)
end
it "redirect to login page" do
delete :destroy, params: {id: @user}
expect(response).to redirect_to store_index_url
end
end
end
|
FactoryGirl.define do
factory :user, class: User do
email "user@example.com"
password "password"
factory :new_user, class: User do
password_confirmation "password"
end
end
factory :edit_user, class: User do
email "edit_user@example.com"
password "12345678"
password_confirmation "12345678"
current_password "password"
end
end
|
class MigrateAccountSourceId < ActiveRecord::Migration
def change
Account.find_each do |account|
unless account.source_id.nil?
source = Source.where(id: account.source_id).last
unless source.nil?
account.sources << source
end
end
end
remove_column :accounts, :source_id
end
end
|
module Rack
module OAuth2
class Server
# Authorization request. Represents request on behalf of client to access
# particular scope. Use this to keep state from incoming authorization
# request to grant/deny redirect.
class AuthRequest < ActiveRecord::Base
belongs_to :client, :class_name => 'Rack::OAuth2::Server::Client'
# Find AuthRequest from identifier.
# def find(request_id)
# id = BSON::ObjectId(request_id.to_s)
# Server.new_instance self, collection.find_one(id)
# rescue BSON::InvalidObjectId
# end
# Create a new authorization request. This holds state, so in addition
# to client ID and scope, we need to know the URL to redirect back to
# and any state value to pass back in that redirect.
def self.create(client, scope, redirect_uri, response_type, state)
scope = Utils.normalize_scope(scope) & Utils.normalize_scope(client.scope) # Only allowed scope
attributes = {
:code => Server.secure_random,
:client_id => client.id,
:scope => scope.join(' '),
:redirect_uri => (client.redirect_uri || redirect_uri),
:response_type => response_type,
:state => state
}
super(attributes)
end
# Grant access to the specified identity.
def grant!(identity)
raise ArgumentError, "Must supply a identity" unless identity
return if revoked
if response_type == "code" # Requested authorization code
access_grant = AccessGrant.create(identity, client, scope, redirect_uri)
update_attributes(:grant_code => access_grant.code, :authorized_at => Time.now)
else # Requested access token
access_token = AccessToken.get_token_for(identity, client, scope)
update_attributes(:access_token => access_token.token, :authorized_at => Time.now)
end
end
# Deny access.
# this seems broken … ?
def deny!
# self.authorized_at = Time.now.to_i
# self.class.collection.update({ :_id=>id }, { :$set=>{ :authorized_at=>authorized_at } })
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe TwitterService, type: :model do
describe '.get_data' do
context 'with a valid hashtag' do
it 'should return not raise an error' do
expect{TwitterService.get_data('MUFC')}.to_not raise_error
end
end
end
end |
RSpec.describe Api::V0x0::ContainerProjectsController, type: :controller do
let(:source) { Source.create!(:tenant => tenant) }
let(:tenant) { Tenant.create! }
it "get /container_projects lists all Container Projects" do
project = ContainerProject.create!(:tenant => tenant, :source => source, :name => "test_container_project")
get_path(api_v0x0_container_projects_url)
expect(response.status).to eq(200)
expect(JSON.parse(response.parsed_body)).to match([a_hash_including("id" => project.id.to_s)])
end
it "get /container_projects/:id returns a Container Project" do
project = ContainerProject.create!(:tenant => tenant, :source => source, :name => "test_container_project")
get_path(api_v0x0_container_project_url(project.id))
expect(response.status).to eq(200)
expect(JSON.parse(response.parsed_body)).to match(a_hash_including("id" => project.id.to_s))
end
end
|
class Follow < ActiveRecord::Base
belongs_to :user#一个人关注很多商品
belongs_to :commidity #一件商品被很多人关注
validates :follower_id,presence:true
validates :commodity_id,presence:true
end
|
# Class representing an lti advantage launch inside a controller
#
# When a controller includes the `lti_support` concern, an
# instance of this class will be accessible from the 'lti' property.
module LtiAdvantage
class LtiAdvantage::Request
attr_reader :lti_token, :lti_params
# delegate all other methods to the lti_params class
delegate_missing_to :@lti_params
def initialize(request, application_instance)
@application_instance = application_instance
@request = request
@lti_token = validate!
@lti_params = AtomicLti::Params.new(@lti_token)
end
def validate!
if @request.env["atomic.validated.id_token"].blank?
raise LtiAdvantage::Exceptions::InvalidToken
end
JWT.decode(@request.env["atomic.validated.id_token"], nil, false)[0]
end
def user_from_lti
LtiAdvantage::LtiUser.new(lti_token, @application_instance).user
end
def lti_provider
AtomicLti::Definitions.lms_host(@lti_token)
end
def account_launch?
canvas_account_id && !canvas_course_id
end
def lms_course_id
lms_course_id = custom_data[:lms_course_id].to_s.presence || canvas_course_id
if lms_course_id.blank?
# Here we manufacture an lms_course_id to use as an identifier for
# scoping course resources.
#
# We're not including the deployment_id here so that
# redeploying a tool doesn't lose all resources.
lms_course_id = "#{iss}##{tool_consumer_instance_guid}##{context_id}"
end
lms_course_id
end
def canvas_api_domain
custom_data[:canvas_api_domain]
end
end
end
|
# Storage for the user's original names and converted results.
$originalNames = [ ]
$convertedNames = [ ]
def nameconvert (inputname)
vowels = "aeiou"
consonants = 'bcdfghjklmnpqrstvwxyz'
# Cycles through each letter in input.
for i in 0...inputname.length
# If character in question is a consonant,
# converts consonants one letter forward, b --> c --> d --> f --> g
if consonants.index(inputname[i]) != nil
inputname[i] = consonants[consonants.index(inputname[i])-consonants.length+1]
# If character is a vowel, converts forward a --> e --> i --> o --> u
elsif vowels.index(inputname[i]) != nil
inputname[i] = vowels[vowels.index(inputname[i])-vowels.length+1]
end
end
# Transforms string to an array, switches first/last names.
inputname = inputname.split(' ').reverse!
# Applies First Last capitalization to the new names.
for i in 0...inputname.length
inputname[i].capitalize!
end
# Finally, prints out new name.
inputname = inputname.join(" ")
output = inputname
$convertedNames.push(output)
puts "Old: #{$originalNames.last} ---> New: #{output}"
end
response = nil;
# Until the user asks to 'quit', continue prompting the user for more inputs
until response == 'quit'
puts "","Enter your full name and we'll convert it to a code name! To quit, please type 'quit'."
# Stores the user's name input as entered in $originalNames
$originalNames << gets.chomp
# Makes the user's entry lowercase, so that requests to 'quit' end the program.
response = $originalNames.last.downcase
#So long as the user enters a string other than 'quit', the program will convert to code name.
if response == 'quit'
# Should the user enter 'quit', displays summary of aliases user has made.
puts "","Summary of Aliases:"
for i in 0...$convertedNames.length
puts "- #{$originalNames[i]} is actually #{$convertedNames[i]}"
end
break
else
# If the user does not enter 'quit', converts entered name into alias.
nameconvert(response)
end
end |
require 'octokit'
require './lib/parsers'
module Wrappers
module Github
include Parsers
OCTOKIT = Octokit::Client.new(access_token: ENV['ACCESS_TOKEN'])
def commit_message(repo, sha)
OCTOKIT.commit(repo, sha).commit.message
end
def pr_body(repo, number)
OCTOKIT.pull_request(repo, number).body
end
def contents_hash(repo, path)
contents = OCTOKIT.contents(repo, path: path)
{
sha: contents.sha,
contents: parse_lines(Base64.decode64(contents.content))
}
end
def update(repo, path, message, sha, contents, branch)
OCTOKIT.update_contents(repo, path, message, sha, contents, branch: branch)
end
end
end
|
class CreateRelations < ActiveRecord::Migration
def change
create_table :relations do |t|
t.references :user, index: true
t.integer :followed_id, index: true
t.timestamps null: false
end
add_foreign_key :relations, :users
add_foreign_key :relations, :users, column: :followed_id, primary_key: "id"
end
end
|
require 'rails_helper'
describe User do
describe '#create' do
it "項目がすべて存在すれば登録できること" do
user = build(:user)
expect(user).to be_valid
end
it "nicknameがない場合は登録できないこと" do
user = build(:user, nickname: nil)
user.valid?
expect(user.errors[:nickname]).to include("を入力してください")
end
it "nicknameが20文字より長い場合は登録できないこと" do
user = build(:user, nickname: "テストユーザテストユーザテストユーザテスト")
user.valid?
expect(user.errors[:nickname]).to include("は20文字以内で入力してください")
end
it "nicknameが一意でない場合は登録できないこと" do
user = create(:user, email: "testuser2@gmail.com")
another_user = build(:user)
another_user.valid?
expect(another_user.errors[:nickname]).to include("はすでに存在します")
end
it "emailがない場合は登録できないこと" do
user = build(:user, email: nil)
user.valid?
expect(user.errors[:email]).to include("を入力してください")
end
it "emailが一意でない場合は登録できないこと" do
user = create(:user, nickname: "テストユーザ2")
another_user = build(:user)
another_user.valid?
expect(another_user.errors[:email]).to include("はすでに存在します")
end
it "emailがメールフォーマットに則っていない場合は登録できないこと" do
user = build(:user, email: "testusergmail.com")
user.valid?
expect(user.errors[:email]).to include("を正しく入力してください")
end
it "fist_nameがない場合は登録できないこと" do
user = build(:user, first_name: nil)
user.valid?
expect(user.errors[:first_name]).to include("を入力してください")
end
it "first_nameが15文字より長い場合は登録できないこと" do
user = build(:user, first_name: "テストユーザテストユーザテストユ")
user.valid?
expect(user.errors[:first_name]).to include("は15文字以内で入力してください")
end
it "first_nameがフォーマットに則っていない場合は登録できないこと" do
user = build(:user, first_name: "testuser")
user.valid?
expect(user.errors[:first_name]).to include("を正しく入力してください")
end
it "last_nameがない場合は登録できないこと" do
user = build(:user, last_name: nil)
user.valid?
expect(user.errors[:last_name]).to include("を入力してください")
end
it "last_nameが15文字より長い場合は登録できないこと" do
user = build(:user, last_name: "テストユーザテストユーザテストユ")
user.valid?
expect(user.errors[:last_name]).to include("は15文字以内で入力してください")
end
it "last_nameがフォーマットに則っていない場合は登録できないこと" do
user = build(:user, last_name: "testuser")
user.valid?
expect(user.errors[:last_name]).to include("を正しく入力してください")
end
it "fist_name_kanaがない場合は登録できないこと" do
user = build(:user, first_name_kana: nil)
user.valid?
expect(user.errors[:first_name_kana]).to include("を入力してください")
end
it "first_name_kanaが30文字より長い場合は登録できないこと" do
user = build(:user, first_name_kana: "テストユーザテストユーザテストユーザテストユーザテストユーザテ")
user.valid?
expect(user.errors[:first_name_kana]).to include("は30文字以内で入力してください")
end
it "first_name_kanaがフォーマットに則っていない場合は登録できないこと(全角ひらがな)" do
user = build(:user, first_name_kana: "てすとゆーざ")
user.valid?
expect(user.errors[:first_name_kana]).to include("を正しく入力してください")
end
it "last_name_kanaがない場合は登録できないこと" do
user = build(:user, last_name_kana: nil)
user.valid?
expect(user.errors[:last_name_kana]).to include("を入力してください")
end
it "last_name_kanaが30文字より長い場合は登録できないこと" do
user = build(:user, last_name_kana: "テストユーザテストユーザテストユーザテストユーザテストユーザテ")
user.valid?
expect(user.errors[:last_name_kana]).to include("は30文字以内で入力してください")
end
it "last_name_kanaがフォーマットに則っていない場合は登録できないこと(半角英字)" do
user = build(:user, last_name_kana: "testuser")
user.valid?
expect(user.errors[:last_name_kana]).to include("を正しく入力してください")
end
it "introductionがない場合は登録できないこと" do
user = build(:user, introduction: nil)
user.valid?
expect(user.errors[:introduction]).to include("を入力してください")
end
it "introductionが300文字より長い場合は登録できないこと" do
user = build(:user, introduction: "テストユーザテストユーザテストユーザテストユーザテストユーザ"*10 + "テ")
user.valid?
expect(user.errors[:introduction]).to include("は300文字以内で入力してください")
end
it "birthdayがない場合は登録できないこと" do
user = build(:user, birthday: nil)
user.valid?
expect(user.errors[:birthday]).to include("を入力してください")
end
it "birthdayがフォーマットに則っていない場合は登録できないこと" do
user = build(:user, birthday: "1994/05/45")
user.valid?
expect(user.errors[:birthday]).to include("を正しく入力してください")
end
it "telephoneがない場合は登録できないこと" do
user = build(:user, telephone: nil)
user.valid?
expect(user.errors[:telephone]).to include("を入力してください")
end
it "telephoneが11文字より長い場合は登録できないこと" do
user = build(:user, telephone: "012345678912")
user.valid?
expect(user.errors[:telephone]).to include("は11文字以内で入力してください")
end
it "telephoneが10文字より短い場合は登録できないこと" do
user = build(:user, telephone: "012345678")
user.valid?
expect(user.errors[:telephone]).to include("は10文字以上で入力してください")
end
it "telephoneがフォーマットに則っていない場合は登録できないこと(半角英字)" do
user = build(:user, telephone: "testnumber")
user.valid?
expect(user.errors[:telephone]).to include("を正しく入力してください")
end
it "passwordが7文字より短い場合は登録できないこと" do
user = build(:user, password: "012345", password_confirmation: "012345")
user.valid?
expect(user.errors[:password]).to include("は7文字以上で入力してください")
end
it "passwordとpassword_confirmationが異なる場合は登録できないこと" do
user = build(:user, password_confirmation: "testuserr")
user.valid?
expect(user.errors[:password_confirmation]).to include("とパスワードの入力が一致しません")
end
end
end |
# frozen_string_literal: true
# can move diagonal
class Bishop < Piece
BEHAVIORS = [
{
start_condition: 'none',
directions: %w[top_right top_left bottom_right bottom_left],
take_opponent: true
}
].freeze
def behaviors
BEHAVIORS
end
def to_s
ColorizedString["\s♗\s"].colorize(color: @color.to_sym)
end
end
|
class FixQuestionsColumnName < ActiveRecord::Migration[5.0]
def change
remove_column :questions,:questions_additional_text
change_table :questions do |t|
t.column :question_additional_text, :string
end
end
end
|
class UserstatsController < ApplicationController
before_filter :user_signed_in, :except => []
def index
@userstats = Userstat.all
end
def new
@userstat = Userstat.new
end
def create
@userstat = Userstat.new(params[:userstat])
if @userstat.save
flash[:notice] = "Userstat has been created."
redirect_to @userstat
else
flash[:alert] = "Userstat has not been created."
render :action => "new"
end
end
def show
@userstat = Userstat.find(params[:id])
@user = User.find(@userstat.user_id)
end
def edit
@userstat = Userstat.find(params[:id])
end
def update
@userstat = Userstat.find(params[:id])
if @userstat.update_attributes(params[:userstat])
flash[:notice] = 'Userstat has been updated.'
redirect_to @userstat
else
flash[:alert] = 'Userstat has not been updated.'
render :action => 'edit'
end
end
private
def user_signed_in
if !current_user
redirect_to new_user_session_path
end
end
end
|
class Backer
attr_accessor :name, :backed_projects
def initialize(name)
@name = name
@backed_projects = []
end
def back_project(project)
@backed_projects << project
project.backers << self
end
end
# When a backer has added a project to it's list of backed projects, that project should also add the backer to it's list of backers. Refer back to the Code Along about Collaborating Objects. |
require_relative 'tmux/config'
require_relative 'tmux/interface'
require_relative 'tmux/session'
require_relative 'tmux/plugins'
module Lab42
module Tmux
def config &block
$config = Config.new
$config.instance_exec( &block )
end
def new_session session_name=nil, &block
raise ArgumentError, 'No block provided' unless block
session = Session.new( session_name || File.basename( ENV["PWD"] ) )
session.run &block
end
def dry_run!
require_relative 'tmux/dry_run'
end
end # module Tmux
end # module Lab42
|
class Fluentd::Settings::RunningBackupController < ApplicationController
include SettingHistoryConcern
private
def find_backup_file
@backup_file = Fluentd::SettingArchive::BackupFile.new(@fluentd.agent.running_config_backup_file)
end
end
|
class Participation < ActiveRecord::Base
belongs_to :user
belongs_to :project
enum status: [:doing, :quited, :arrived, :finished]
end |
require 'spec_helper'
require 'bakery_app'
describe BakeryApp do
describe "#run" do
before(:each) do
allow(STDOUT).to receive(:puts)
end
it "returns if there is odd number of input params" do
inputs = (['input'] * (rand(3) * 2 + 1)).join(' ')
allow(STDIN).to receive_message_chain(:gets, :chomp).and_return(inputs)
expect(BakeryApp).to receive(:print_error_message).with('Invalid order. Are you missing an item count or a product code?')
BakeryApp.run
end
it "returns if there is no input params" do
inputs = ''
allow(STDIN).to receive_message_chain(:gets, :chomp).and_return(inputs)
expect(BakeryApp).to receive(:print_error_message).with('Invalid order. Are you missing an item count or a product code?')
BakeryApp.run
end
it "calls process_orders with order details" do
inputs = double('inputs')
allow(STDIN).to receive_message_chain(:gets, :chomp).and_return(inputs)
order_params = double('order params')
allow(order_params).to receive_message_chain(:length, :odd?).and_return(false)
allow(order_params).to receive(:empty?).and_return(false)
expect(inputs).to receive(:split).with(' ').and_return(order_params)
orders = 'orders'
expect(order_params).to receive_message_chain(:each_slice, :to_a).with(2).with(no_args).and_return(orders)
expect(BakeryApp).to receive(:process_orders).with(orders)
BakeryApp.run
end
end
describe "#process_orders" do
it "returns if there is any invalid order" do
orders = []
order_count = rand(1..3)
invalid_order_index = rand(order_count)
(0..order_count - 1).each do |i|
item_count = rand(5)
item_count_string = "#{item_count}"
product_code = "code #{i}"
order = [item_count_string, product_code]
orders << order
if i == invalid_order_index
expect(BakeryApp).to receive(:verify_order).with(item_count_string, product_code).and_return([false, nil, nil, nil])
elsif i < invalid_order_index
product = 'product'
valid_pack_combinations = 'valid pack combinations'
cost = 'cost'
expect(BakeryApp).to receive(:verify_order).with(item_count_string, product_code).and_return([true, item_count, product, valid_pack_combinations])
best_combination = 'best combination'
expect(BakeryApp).to receive(:pick_best_pack_combination).with(product, valid_pack_combinations).and_return([best_combination, cost])
end
end
expect(BakeryApp).not_to receive(:print_order_details)
BakeryApp.process_orders(orders)
end
it "calls print_order_details if all orders are valid" do
orders = []
order_details = []
order_count = rand(1..3)
(0..order_count - 1).each do |i|
item_count = rand(5)
item_count_string = "#{item_count}"
product_code = "code #{i}"
order = [item_count_string, product_code]
orders << order
product = 'product'
valid_pack_combinations = 'valid pack combinations'
cost = 'cost'
expect(BakeryApp).to receive(:verify_order).with(item_count_string, product_code).and_return([true, item_count, product, valid_pack_combinations])
best_combination = 'best combination'
expect(BakeryApp).to receive(:pick_best_pack_combination).with(product, valid_pack_combinations).and_return([best_combination, cost])
order_details << [item_count, product, best_combination, cost]
end
expect(BakeryApp).to receive(:print_order_details).with(order_details)
BakeryApp.process_orders(orders)
end
end
describe "#verify_order" do
it "returns false if item_count is not integer" do
item_count_string = 'd'
product_code = 'code'
expect(BakeryApp).to receive(:print_error_message).with("Invalid item count: #{item_count_string}. It should be an integer.")
is_valid_order, item_count, product, pack_combinations = BakeryApp.verify_order(item_count_string, product_code)
expect(is_valid_order).to be false
end
it "returns false if item_count <= 0" do
item_count_string = "#{0 - rand(3)}"
product_code = 'code'
expect(BakeryApp).to receive(:print_error_message).with("Invalid item count: #{item_count_string}. It should be greater than 0.")
is_valid_order, item_count, product, pack_combinations = BakeryApp.verify_order(item_count_string, product_code)
expect(is_valid_order).to be false
end
it "returns false if invalid product code" do
item_count_string = "#{rand(1..5)}"
product_code = 'code'
expect(BakeryApp::PRODUCTS).to receive(:[]).with(product_code).and_return(nil)
expect(BakeryApp).to receive(:print_error_message).with("Invalid product code: #{product_code}")
is_valid_order, item_count, product, pack_combinations = BakeryApp.verify_order(item_count_string, product_code)
expect(is_valid_order).to be false
end
it "returns false if can not find pack combinations that meet item count" do
item_count = rand(1..5)
item_count_string = "#{item_count}"
product_code = 'code'
product = double('product')
expect(BakeryApp::PRODUCTS).to receive(:[]).with(product_code).and_return(product)
available_packs = 'available packs'
expect(product).to receive(:available_packs).and_return(available_packs)
expect(BakeryApp).to receive(:pack_combinations).with(available_packs, item_count).and_return([])
expect(BakeryApp).to receive(:print_error_message).with("Invalid item count #{item_count} for product #{product_code}")
is_valid_order, item_count, product, pack_combinations = BakeryApp.verify_order(item_count_string, product_code)
expect(is_valid_order).to be false
end
it "returns true, item_count, product and valid_pack_combinations if valid order" do
item_count = rand(1..5)
item_count_string = "#{item_count}"
product_code = 'code'
product = double('product')
expect(BakeryApp::PRODUCTS).to receive(:[]).with(product_code).and_return(product)
available_packs = 'available packs'
expect(product).to receive(:available_packs).and_return(available_packs)
pack_combinations = 'pack combinations'
expect(BakeryApp).to receive(:pack_combinations).with(available_packs, item_count).and_return(pack_combinations)
results = BakeryApp.verify_order(item_count_string, product_code)
expect(results).to eq [true, item_count, product, pack_combinations]
end
end
describe "#pick_best_pack_combination" do
before(:each) do
@product = 'product'
@combinations = 'combinations'
@cheapest_combinations = 'cheapest combinations'
@cost = 'cost'
end
it "finds pack combinations with the least total cost" do
expect(BakeryApp).to receive(:cheapest_combinations).with(@product, @combinations).and_return([@cheapest_combinations, @cost])
allow(BakeryApp).to receive(:smallest_combination).with(@cheapest_combinations)
BakeryApp.pick_best_pack_combination(@product, @combinations)
end
it "returns pack combination with the least number of packs from the cheapest combinations" do
best_combination = 'best combination'
expect(BakeryApp).to receive(:cheapest_combinations).with(@product, @combinations).and_return([@cheapest_combinations, @cost])
expect(BakeryApp).to receive(:smallest_combination).with(@cheapest_combinations).and_return(best_combination)
expect(BakeryApp.pick_best_pack_combination(@product, @combinations)).to eq [best_combination, @cost]
end
end
describe "#pack_combinations" do
before(:each) do
@packs = [3, 5, 9]
end
it "returns empty array if there is no valid combination" do
expect(BakeryApp.pack_combinations(@packs, 1)).to eq []
expect(BakeryApp.pack_combinations(@packs, 2)).to eq []
end
it "returns all valid combinations for item count" do
combinations = [
[3, 3, 3, 3, 3],
[3, 3, 9],
[5, 5, 5]
]
results = BakeryApp.pack_combinations(@packs, 15)
combinations.each do |combination|
expect(results).to include combination
end
end
it "returns array of unique combinations" do
results = BakeryApp.pack_combinations([1, 2, 3], 6)
sorted_results = results.map{|r| r.sort}
sorted_results.uniq!
expect(sorted_results).to eq results
end
end
describe "#cheapest_pack_combinations" do
it "returns the cheapest combinations and total cost" do
prices = {
1 => rand(0.1..2.0),
2 => rand(2.1..4.0),
3 => rand(4.1..6.0)
}
product = double('product')
prices.each do |pack, price|
allow(product).to receive(:price).with(pack).and_return(price)
end
cheapest_total_cost = Float::INFINITY
cheapest_combinations = []
packs = prices.keys
combinations = []
(1..3).each do
combination = []
rand(1..3).times do
combination += [packs.sample] * rand(3)
end
combinations << combination
total_cost = combination.inject(0) {|sum, pack| (sum + product.price(pack)).round(2)}
if total_cost < cheapest_total_cost
# found new cheapest combination
cheapest_total_cost = total_cost
cheapest_combinations = [combination]
elsif total_cost == cheapest_total_cost
# found combination with the cheapest cost
cheapest_combinations << combination
end
end
expect(BakeryApp.cheapest_combinations(product, combinations)).to eq [cheapest_combinations, cheapest_total_cost]
end
end
describe "#smallest_combination" do
it "returns the combination with the least number of packs" do
fewest_pack_count = rand(1..5)
combinations_count = rand(3..5)
smallest_combination_index = rand(combinations_count)
combinations = []
smallest_combination = nil
(0..combinations_count - 1).each do |i|
if i == smallest_combination_index
combination = (0..fewest_pack_count - 1).map{|x| rand(1..3)}
smallest_combination = combination
else
combination = (0..fewest_pack_count + rand(3)).map{|x| rand(1..3)}
end
combinations << combination
end
expect(BakeryApp.smallest_combination(combinations)).to eq smallest_combination
end
end
describe "#print_order_details" do
it "calls print_order for each order" do
order_details = []
rand(1..3).times do
item_count = 'item count'
product = 'product'
pack_combination = 'pack combination'
cost = 'cost'
order_detail = [item_count, product, pack_combination, cost]
expect(BakeryApp).to receive(:print_order).with(product, item_count, pack_combination, cost)
order_details << order_detail
end
BakeryApp.print_order_details(order_details)
end
end
end
|
require 'rails_helper'
describe "Destinations API" do
it "sends a list of destinations" do
Fabricate.times(3, :destination)
get '/api/v1/destinations'
expect(response).to be_success
destinations = JSON.parse(response.body)
expect(destinations.count).to eq(3)
end
it "sends a single destination" do
id = Fabricate(:destination).id
get "/api/v1/destinations/#{id}"
destination = JSON.parse(response.body)
expect(response).to be_success
expect(destination["id"]).to eq(id)
end
it "creates a single destination" do
destination_params = { name: "stuff", zip: "12345", description: "stuff2"}
post "/api/v1/destinations", params: {destination: destination_params}
destination = Destination.last
assert_response :success
expect(response).to be_success
expect(destination.name).to eq(destination_params[:name])
end
it "can update a single destination" do
id = Fabricate(:destination).id
previous_name = Destination.last.name
destination_params = { name: "new" }
put "/api/v1/destinations/#{id}", params: {destination: destination_params}
destination = Destination.find_by(id: id)
expect(response).to be_success
expect(destination.name).to_not eq(previous_name)
expect(destination.name).to eq("new")
end
it "can delete a single destination" do
destination = Fabricate(:destination)
expect(Destination.count).to eq(1)
delete "/api/v1/destinations/#{destination.id}"
expect(response).to be_success
expect(Destination.count).to eq(0)
expect{Destination.find(destination.id)}.to raise_error(ActiveRecord::RecordNotFound)
end
end
|
# frozen_string_literal: true
require "net/http"
require "zlib"
module Sentry
class HTTPTransport < Transport
GZIP_ENCODING = "gzip"
GZIP_THRESHOLD = 1024 * 30
CONTENT_TYPE = 'application/x-sentry-envelope'
DEFAULT_DELAY = 60
RETRY_AFTER_HEADER = "retry-after"
RATE_LIMIT_HEADER = "x-sentry-rate-limits"
USER_AGENT = "sentry-ruby/#{Sentry::VERSION}"
def initialize(*args)
super
@endpoint = @dsn.envelope_endpoint
log_debug("Sentry HTTP Transport will connect to #{@dsn.server}")
end
def send_data(data)
encoding = ""
if should_compress?(data)
data = Zlib.gzip(data)
encoding = GZIP_ENCODING
end
headers = {
'Content-Type' => CONTENT_TYPE,
'Content-Encoding' => encoding,
'X-Sentry-Auth' => generate_auth_header,
'User-Agent' => USER_AGENT
}
response = conn.start do |http|
request = ::Net::HTTP::Post.new(@endpoint, headers)
request.body = data
http.request(request)
end
if response.code.match?(/\A2\d{2}/)
if has_rate_limited_header?(response)
handle_rate_limited_response(response)
end
else
error_info = "the server responded with status #{response.code}"
if response.code == "429"
handle_rate_limited_response(response)
else
error_info += "\nbody: #{response.body}"
error_info += " Error in headers is: #{response['x-sentry-error']}" if response['x-sentry-error']
end
raise Sentry::ExternalError, error_info
end
rescue SocketError => e
raise Sentry::ExternalError.new(e.message)
end
private
def has_rate_limited_header?(headers)
headers[RETRY_AFTER_HEADER] || headers[RATE_LIMIT_HEADER]
end
def handle_rate_limited_response(headers)
rate_limits =
if rate_limits = headers[RATE_LIMIT_HEADER]
parse_rate_limit_header(rate_limits)
elsif retry_after = headers[RETRY_AFTER_HEADER]
# although Sentry doesn't send a date string back
# based on HTTP specification, this could be a date string (instead of an integer)
retry_after = retry_after.to_i
retry_after = DEFAULT_DELAY if retry_after == 0
{ nil => Time.now + retry_after }
else
{ nil => Time.now + DEFAULT_DELAY }
end
rate_limits.each do |category, limit|
if current_limit = @rate_limits[category]
if current_limit < limit
@rate_limits[category] = limit
end
else
@rate_limits[category] = limit
end
end
end
def parse_rate_limit_header(rate_limit_header)
time = Time.now
result = {}
limits = rate_limit_header.split(",")
limits.each do |limit|
next if limit.nil? || limit.empty?
begin
retry_after, categories = limit.strip.split(":").first(2)
retry_after = time + retry_after.to_i
categories = categories.split(";")
if categories.empty?
result[nil] = retry_after
else
categories.each do |category|
result[category] = retry_after
end
end
rescue StandardError
end
end
result
end
def should_compress?(data)
@transport_configuration.encoding == GZIP_ENCODING && data.bytesize >= GZIP_THRESHOLD
end
def conn
server = URI(@dsn.server)
connection =
if proxy = normalize_proxy(@transport_configuration.proxy)
::Net::HTTP.new(server.hostname, server.port, proxy[:uri].hostname, proxy[:uri].port, proxy[:user], proxy[:password])
else
::Net::HTTP.new(server.hostname, server.port, nil)
end
connection.use_ssl = server.scheme == "https"
connection.read_timeout = @transport_configuration.timeout
connection.write_timeout = @transport_configuration.timeout if connection.respond_to?(:write_timeout)
connection.open_timeout = @transport_configuration.open_timeout
ssl_configuration.each do |key, value|
connection.send("#{key}=", value)
end
connection
end
def normalize_proxy(proxy)
return proxy unless proxy
case proxy
when String
uri = URI(proxy)
{ uri: uri, user: uri.user, password: uri.password }
when URI
{ uri: proxy, user: proxy.user, password: proxy.password }
when Hash
proxy
end
end
def ssl_configuration
configuration = {
verify: @transport_configuration.ssl_verification,
ca_file: @transport_configuration.ssl_ca_file
}.merge(@transport_configuration.ssl || {})
configuration[:verify_mode] = configuration.delete(:verify) ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
configuration
end
end
end
|
class TicketMailer < ActionMailer::Base
default from: 'tinam03@yahoo.com'
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.ticket_mailer.issue_confirmation.subject
#
def issue_confirmation(ticket)
mail to: ENV["EMAIL"], subject: "You've got mail."
end
end
|
class User < ApplicationRecord
has_many :friendships
has_many :friends, :through => :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :followed_by_users, :through => :inverse_friendships, :source => :user
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Tournament, type: :model do
it 'has valid factory' do
expect(create(:tournament)).to be_valid
end
end
|
require 'aurora/config'
describe Aurora::Config do
describe "#set_attributes_from_hash" do
let(:config_attrs) do
{
:aurora_admin_user => 'bliu@pivotallabs.com',
:target_rb_name => 'RB',
:aurora_initialized => true,
:aurora_service_url => 'https://10.80.129.96/datadirector/services/datacloudWS',
:gpfdist_port => '8081'
}
end
it "contains all of the neccessary attributes" do
config = Aurora::Config.new
config.should be_a_kind_of(com.vmware.aurora.client.common.config.AuroraConfig)
config.load(config_attrs)
config.aurora_admin_user.should == 'bliu@pivotallabs.com'
config.target_rb_name.should == 'RB'
config.aurora_initialized.should be_true
config.aurora_service_url.should == 'https://10.80.129.96/datadirector/services/datacloudWS'
config.gpfdist_port.should == 8081
end
end
end
|
desc "Import the local address xls file"
task :import_local_addresses => :environment do
require 'parseexcel/parser'
# XXX KML TODO get the file name in a better fashion
file = './tmp/local data.xls'
workbook = Spreadsheet::ParseExcel::Parser.new.parse file
worksheet = workbook.worksheet 0
cat_to_questions_hash = {}
cols = [
:product_id, :individual_name, :business_name, :address_1, :address_2, :city, :state,
:zip_code, :telephone, :web_site, :chain
]
line_cnt = succ_cnt = err_cnt = 0
worksheet.each(2) do |row|
data = {}
begin
line_cnt += 1
cols.each_with_index do |col,i|
data[col] = if [:product_id, :zip_code].include?(col)
row[i].nil? || row[i].kind == :blank ? nil : row[i].to_i
else
Category.cell_to_s row[i]
end
end
# use individual name if we have it, else use business name
data[:name] = data[:individual_name] || data[:business_name]
next if data[:name].blank?
# normalize this value: 'Yes', 'No', 'N/A' becomes true or false
data[:chain] = (data[:chain] == 'Yes')
# combine the address lines
data[:address] = data[:address_1]
data[:address] = data[:address] + ' ' + data[:address_2] unless data[:address_2].blank?
product = Product.find_by_id data[:product_id]
next unless product
questions = cat_to_questions_hash[product.category.id]
unless questions
questions = Hash.new
questions[:address] = ProductQuestion.find_by_category_id_and_label product.category.id, 'Address'
questions[:city] = ProductQuestion.find_by_category_id_and_label product.category.id, 'City'
questions[:state] = ProductQuestion.find_by_category_id_and_label product.category.id, 'State'
questions[:zip_code] = ProductQuestion.find_by_category_id_and_label product.category.id, 'Zip Code'
questions[:telephone] = ProductQuestion.find_by_category_id_and_label product.category.id, 'Telephone'
questions[:web_site] = ProductQuestion.find_by_category_id_and_label product.category.id, 'Web Site'
questions[:product_link_url] = ProductQuestion.find_by_category_id_and_label product.category.id, 'Product Link URL'
questions[:product_link_text] = ProductQuestion.find_by_category_id_and_label product.category.id, 'Product Link Text'
cat_to_questions_hash[product.category.id] = questions
end
questions.each do |label,question|
value = case label
when :product_link_url
s = data[:web_site]
s = 'http://' + s unless s.blank? || s =~ /^https?:\/\//
when :product_link_text
data[:web_site]
else
data[label]
end
next if value.blank?
value = value.to_s
answer = ProductAnswer.find_by_product_id_and_product_question_id product.id, question.id
answer ||= ProductAnswer.new :product => product, :question => question
if answer.value != value
answer.value = value
answer.user = nil
answer.status = 'approved'
answer.save!
end
end
product.reformat_title
product.reformat_subtitle
product.save!
product.clear_geocode
succ_cnt += 1
rescue => e
puts "Error occurred for #{data.inspect}\n#{e}\n#{e.backtrace.join("\n")}"
err_cnt += 1
end
end
puts "Import Local Data summary -- lines seen: #{line_cnt} successes: #{succ_cnt} errors: #{err_cnt}"
end
desc "Import sampling program product recipients; FILE='path/to/file' PROGRAM=id [PRODUCT=id]"
task :import_sampling_recipients => :environment do
raise "USAGE: rake import_sampling_recipients FILE='path/to/file' PROGRAM=id [PRODUCT=id]" unless ENV['FILE'] and ENV['PROGRAM']
program = Sampling::Program.find(ENV['PROGRAM'])
products = ENV['PRODUCT'] ? program.program_products.all(:conditions => { :product_id => ENV['PRODUCT'] }) : program.program_products
raise "Couldn't find Sampling::ProgramProduct with product_id=#{ENV['PRODUCT']} for Sampling::Program ID=#{program.id}" if products.blank?
file = File.new(ENV['FILE'], "r")
lines = file.readlines
lines.shift
file.close
errors = []
for row in lines
user_id = row.to_i
participant = program.participants.first(:conditions => { :user_id => user_id })
if participant.blank?
print 'E'
errors << user_id
next
end
products.each do |product|
Sampling::Sample.find_or_create_by_participant_id_and_program_id_and_program_product_id(participant.id, program.id, product.id)
end
print '.'
end
puts ''
raise "Couldn't find users with IDs: #{errors.join(', ')}" unless errors.blank?
end
|
class UsersController < ApplicationController
skip_before_action :authorized, only: [:create]
# def profile
# render json: { user: UserSerializer.new(current_user) },
# status: :accepted
# end
def create
user = User.create(user_params)
if user.valid?
token = encode_token({ user_id: user.id })
render json: { user: UserSerializer.new(user), jwt: token },
status: :created
else
render json: { error: 'failed to create user' },
status: :not_acceptable
end
end
def index
users = User.all
render json: users
end
def show
user = find_user
render json: {
id: user.id, name: user.username, buildings: user.buildings
}
end
# def create
# user = User.create(user_params)
# render json: user
# end
def update
user = find_user
user.update(user_params)
render json: user
end
private
def find_user
user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:username, :password)
end
end
|
class RentalsController < ApplicationController
def checkout
new_rental = Rental.new(rentals_params)
new_rental.checkout_date = Date.today
new_rental.due_date = Date.today + 7.days
new_rental.return_date = nil
if new_rental.customer.nil? || new_rental.video.nil?
render json: {
errors: [
"Not Found"
]
}, status: :not_found
return
end
if new_rental.save
video = new_rental.video
customer = new_rental.customer
if video.available_inventory <= 0
render json: {
errors: new_rental.errors.messages
}, status: :not_found
return
else
video.available_inventory -= 1
video.save
available_inventory = new_rental.video.available_inventory
end
customer.videos_checked_out_count += 1
customer.save
videos_checked_out_count = new_rental.customer.videos_checked_out_count
rental_view = new_rental.as_json(only: [:customer_id, :video_id,
:due_date])
rental_view[:videos_checked_out_count] = videos_checked_out_count
rental_view[:available_inventory] = available_inventory
render json: rental_view,
status: :ok
else
render json: {
errors: new_rental.errors.messages
}, status: :bad_request
return
end
end
def checkin
rental = Rental.find_by(video_id: params[:video_id], customer_id: params[:customer_id], return_date: nil)
if rental.nil?
render json: {
errors: [
"Not Found"
]
}, status: :not_found
return
end
if rental
video = rental.video
video.available_inventory += 1
video.save
available_inventory = rental.video.available_inventory
customer = rental.customer
if customer.videos_checked_out_count <= 0
render json: {
errors: rental.errors.messages
}, status: :not_found
return
else
customer.videos_checked_out_count -= 1
customer.save
videos_checked_out_count = rental.customer.videos_checked_out_count
end
rental.return_date = Date.today
puts rental.return_date
rental_view = rental.as_json(only: [:customer_id, :video_id])
rental_view[:videos_checked_out_count] = videos_checked_out_count
rental_view[:available_inventory] = available_inventory
render json: rental_view,
status: :ok
else
render json: {
errors: rental.errors.messages
}, status: :not_found
return
end
end
private
def rentals_params
return params.permit(:customer_id, :video_id)
end
end
|
require_relative '../test_helper'
class ElasticSearch9Test < ActionController::TestCase
def setup
super
setup_elasticsearch
end
test "should filter items by has_claim" do
t = create_team
p = create_project team: t
u = create_user
create_team_user team: t, user: u, role: 'admin'
with_current_user_and_team(u ,t) do
pm = create_project_media team: t, disable_es_callbacks: false
pm2 = create_project_media team: t, disable_es_callbacks: false
pm3 = create_project_media team: t, disable_es_callbacks: false
pm4 = create_project_media team: t, disable_es_callbacks: false
create_claim_description project_media: pm, disable_es_callbacks: false
create_claim_description project_media: pm3, disable_es_callbacks: false
sleep 2
results = CheckSearch.new({ has_claim: ['ANY_VALUE'] }.to_json)
assert_equal [pm.id, pm3.id], results.medias.map(&:id).sort
results = CheckSearch.new({ has_claim: ['NO_VALUE'] }.to_json)
assert_equal [pm2.id, pm4.id], results.medias.map(&:id).sort
end
end
test "should filter feed by workspace" do
RequestStore.store[:skip_cached_field_update] = false
f = create_feed
t1 = create_team ; f.teams << t1
t2 = create_team ; f.teams << t2
t3 = create_team ; f.teams << t3
FeedTeam.update_all(shared: true)
pm1 = create_project_media team: t1
c1 = create_cluster project_media: pm1
c1.project_medias << pm1
pm2 = create_project_media team: t2
c2 = create_cluster project_media: pm2
c2.project_medias << pm2
pm3 = create_project_media team: t3
c2.project_medias << pm3
sleep 2
u = create_user
create_team_user team: t1, user: u, role: 'admin'
with_current_user_and_team(u, t1) do
query = { clusterize: true, feed_id: f.id }
result = CheckSearch.new(query.to_json)
assert_equal [pm1.id, pm2.id], result.medias.map(&:id).sort
query[:cluster_teams] = [t1.id]
result = CheckSearch.new(query.to_json)
assert_equal [pm1.id], result.medias.map(&:id)
query[:cluster_teams] = [t2.id, t3.id]
result = CheckSearch.new(query.to_json)
assert_equal [pm2.id], result.medias.map(&:id)
# Get current team
assert_equal t1, result.team
end
end
test "should filter feed by report status" do
create_verification_status_stuff
RequestStore.store[:skip_cached_field_update] = false
t = create_team
f = create_feed
f.teams << t
FeedTeam.update_all(shared: true)
pm1 = create_project_media team: t
c1 = create_cluster project_media: pm1
c1.project_medias << pm1
pm2 = create_project_media team: t
c2 = create_cluster project_media: pm2
c2.project_medias << pm2
sleep 2
u = create_user
create_team_user team: t, user: u, role: 'admin'
with_current_user_and_team(u, t) do
publish_report(pm1)
query = { clusterize: true, feed_id: f.id, report_status: ['published', 'unpublished'] }
result = CheckSearch.new(query.to_json)
assert_equal [pm1.id, pm2.id], result.medias.map(&:id).sort
query[:report_status] = ['published']
result = CheckSearch.new(query.to_json)
assert_equal [pm1.id], result.medias.map(&:id)
query[:report_status] = ['unpublished']
result = CheckSearch.new(query.to_json)
assert_equal [pm2.id], result.medias.map(&:id)
end
end
test "should search for keywords with typos" do
t = create_team
p = create_project team: t
u = create_user
create_team_user team: t, user: u, role: 'admin'
with_current_user_and_team(u ,t) do
pm1 = create_project_media team: t, quote: 'Foobar 1', disable_es_callbacks: false
pm2 = create_project_media team: t, quote: 'Fobar 2', disable_es_callbacks: false
pm3 = create_project_media team: t, quote: 'Test 3', disable_es_callbacks: false
results = CheckSearch.new({ keyword: 'Foobar', fuzzy: true }.to_json)
assert_equal [pm1.id, pm2.id].sort, results.medias.map(&:id).sort
results = CheckSearch.new({ keyword: 'Fobar', fuzzy: true }.to_json)
assert_equal [pm1.id, pm2.id].sort, results.medias.map(&:id).sort
results = CheckSearch.new({ keyword: 'Test', fuzzy: true }.to_json)
assert_equal [pm3.id], results.medias.map(&:id)
end
end
test "should filter keyword by extracted text OCR" do
ft = DynamicAnnotation::FieldType.where(field_type: 'language').last || create_field_type(field_type: 'language', label: 'Language')
at = create_annotation_type annotation_type: 'language', label: 'Language'
create_field_instance annotation_type_object: at, name: 'language', label: 'Language', field_type_object: ft, optional: false
bot = create_alegre_bot(name: "alegre", login: "alegre")
bot.approve!
team = create_team
bot.install_to!(team)
create_flag_annotation_type
create_extracted_text_annotation_type
Bot::Alegre.unstub(:request_api)
Rails.stubs(:env).returns('development'.inquiry)
stub_configs({ 'alegre_host' => 'http://alegre', 'alegre_token' => 'test' }) do
WebMock.disable_net_connect! allow: /#{CheckConfig.get('elasticsearch_host')}|#{CheckConfig.get('storage_endpoint')}/
WebMock.stub_request(:post, 'http://alegre/text/langid/').to_return(body: { 'result' => { 'language' => 'es' }}.to_json)
WebMock.stub_request(:post, 'http://alegre/text/similarity/').to_return(body: 'success')
WebMock.stub_request(:delete, 'http://alegre/text/similarity/').to_return(body: {success: true}.to_json)
WebMock.stub_request(:get, 'http://alegre/text/similarity/').to_return(body: {success: true}.to_json)
WebMock.stub_request(:get, 'http://alegre/image/similarity/').to_return(body: {
"result": []
}.to_json)
WebMock.stub_request(:get, 'http://alegre/image/classification/').with({ query: { uri: 'some/path' } }).to_return(body: {
"result": valid_flags_data
}.to_json)
WebMock.stub_request(:get, 'http://alegre/image/ocr/').with({ query: { url: 'some/path' } }).to_return(body: {
"text": "ocr_text"
}.to_json)
WebMock.stub_request(:post, 'http://alegre/image/similarity/').to_return(body: 'success')
# Text extraction
Bot::Alegre.unstub(:media_file_url)
pm = create_project_media team: team, media: create_uploaded_image, disable_es_callbacks: false
Bot::Alegre.stubs(:media_file_url).with(pm).returns("some/path")
assert Bot::Alegre.run({ data: { dbid: pm.id }, event: 'create_project_media' })
sleep 2
Team.stubs(:current).returns(team)
result = CheckSearch.new({keyword: 'ocr_text'}.to_json)
assert_equal [pm.id], result.medias.map(&:id)
result = CheckSearch.new({keyword: 'ocr_text', keyword_fields: {fields: ['extracted_text']}}.to_json)
assert_equal [pm.id], result.medias.map(&:id)
result = CheckSearch.new({keyword: 'ocr_text', keyword_fields: {fields: ['title']}}.to_json)
assert_empty result.medias
Team.unstub(:current)
Bot::Alegre.unstub(:media_file_url)
end
end
test "should search by non or any for choices tasks" do
create_task_stuff
t = create_team
u = create_user
create_team_user team: t, user: u, role: 'admin'
tt = create_team_task team_id: t.id, type: 'single_choice', options: ['ans_a', 'ans_b', 'ans_c']
with_current_user_and_team(u ,t) do
pm = create_project_media team: t, disable_es_callbacks: false
pm2 = create_project_media team: t, disable_es_callbacks: false
pm3 = create_project_media team: t, disable_es_callbacks: false
pm_tt = pm.annotations('task').select{|t| t.team_task_id == tt.id}.last
pm_tt.response = { annotation_type: 'task_response_single_choice', set_fields: { response_single_choice: 'ans_a' }.to_json }.to_json
pm_tt.save!
pm2_tt = pm2.annotations('task').select{|t| t.team_task_id == tt.id}.last
pm2_tt.response = { annotation_type: 'task_response_single_choice', set_fields: { response_single_choice: 'ans_b' }.to_json }.to_json
pm2_tt.save!
sleep 2
results = CheckSearch.new({ team_tasks: [{ id: tt.id, response: 'ANY_VALUE' }]}.to_json)
assert_equal [pm.id, pm2.id], results.medias.map(&:id).sort
results = CheckSearch.new({ team_tasks: [{ id: tt.id, response: 'NO_VALUE' }]}.to_json)
assert_equal [pm3.id], results.medias.map(&:id).sort
end
end
test "should search by date range for tasks" do
at = create_annotation_type annotation_type: 'task_response_datetime', label: 'Task Response Date Time'
datetime = create_field_type field_type: 'datetime', label: 'Date Time'
create_field_instance annotation_type_object: at, name: 'response_datetime', field_type_object: datetime
t = create_team
u = create_user
create_team_user team: t, user: u, role: 'admin'
tt = create_team_task team_id: t.id, type: 'number'
create_team_task team_id: t.id, type: 'datetime'
with_current_user_and_team(u ,t) do
pm = create_project_media team: t, disable_es_callbacks: false
pm2 = create_project_media team: t, disable_es_callbacks: false
pm3 = create_project_media team: t, disable_es_callbacks: false
pm2_tt = pm2.annotations('task').select{|t| t.team_task_id == tt.id}.last
start_time = Time.now - 4.months
end_time = Time.now - 2.months
pm2_tt.response = { annotation_type: 'task_response_datetime', set_fields: { response_datetime: start_time }.to_json }.to_json
pm2_tt.save!
pm3_tt = pm3.annotations('task').select{|t| t.team_task_id == tt.id}.last
pm3_tt.response = { annotation_type: 'task_response_datetime', set_fields: { response_datetime: end_time }.to_json }.to_json
pm3_tt.save!
sleep 2
results = CheckSearch.new({ team_tasks: [{ id: tt.id, response: 'DATE_RANGE', range: { start_time: start_time }}]}.to_json)
assert_equal [pm2.id, pm3.id], results.medias.map(&:id).sort
results = CheckSearch.new({ team_tasks: [{ id: tt.id, response: 'DATE_RANGE', range: { start_time: start_time, end_time: end_time }}]}.to_json)
assert_equal [pm2.id, pm3.id], results.medias.map(&:id).sort
results = CheckSearch.new({ team_tasks: [{ id: tt.id, response: 'DATE_RANGE', range: { start_time: start_time, end_time: end_time - 1.month }}]}.to_json)
assert_equal [pm2.id], results.medias.map(&:id)
results = CheckSearch.new({ team_tasks: [{ id: tt.id, response: 'DATE_RANGE', range: { start_time: start_time + 1.month, max: end_time + 1.month }}]}.to_json)
assert_equal [pm3.id], results.medias.map(&:id)
end
end
test "should search by media id" do
t = create_team
u = create_user
pm = create_project_media team: t, quote: 'claim a', disable_es_callbacks: false
pm2 = create_project_media team: t, quote: 'claim b', disable_es_callbacks: false
sleep 2
create_team_user team: t, user: u, role: 'admin'
with_current_user_and_team(u ,t) do
# Hit ES with option id
# A) id is array (should ignore)
query = 'query Search { search(query: "{\"id\":[' + pm.id.to_s + '],\"keyword\":\"claim\"}") { medias(first: 10) { edges { node { dbid } } } } }'
post :create, params: { query: query }
assert_response :success
ids = []
JSON.parse(@response.body)['data']['search']['medias']['edges'].each do |id|
ids << id["node"]["dbid"]
end
assert_equal [pm.id, pm2.id], ids.sort
# B) id is string and exists in ES
query = 'query Search { search(query: "{\"id\":' + pm.id.to_s + ',\"keyword\":\"claim\"}") { medias(first: 10) { edges { node { dbid } } } } }'
post :create, params: { query: query }
assert_response :success
ids = []
JSON.parse(@response.body)['data']['search']['medias']['edges'].each do |id|
ids << id["node"]["dbid"]
end
assert_equal [pm.id], ids
# C) id is string and not exists in ES
$repository.delete(get_es_id(pm))
query = 'query Search { search(query: "{\"id\":' + pm.id.to_s + ',\"keyword\":\"claim\"}") { medias(first: 10) { edges { node { dbid } } } } }'
post :create, params: { query: query }
assert_response :success
assert_empty JSON.parse(@response.body)['data']['search']['medias']['edges']
end
end
# Please add new tests to test/controllers/elastic_search_10_test.rb
end
|
class Webhook < ActiveRecord::Base
has_many :attempts
belongs_to :consumer
delegate :producer, :to => :consumer, allow_nil: false
after_initialize :assign_defaults, if: 'new_record?'
scope :failed, where(failed: true)
scope :attempt, where(attempt: true)
validates_presence_of :post_data
validates_presence_of :post_uri
validate :attempt_only_if_not_failed
validate :headers_are_valid_json_if_present
MAX_ATTEMPTS = 10
def max_attempts
MAX_ATTEMPTS
end
# TODO: Fix hack - Sorry Justin :S
def attempt_explanation
explanation = ""
if failed and not attempt
explanation = "This webhook has permanently failed\n"
self.attempts.each do |attempt|
explanation += "failed at: #{attempt.created_at}\n"
end
elsif not failed and attempt
explanation = "We are trying to send this webhook\n"
self.attempts.each do |attempt|
explanation += "failed at: #{attempt.created_at}\n"
end
elsif not failed and not attempt
explanation = "We succeeded in sending this webhook\n"
attempt_array = self.attempts.to_a
attempt_array[0..-2].each do |attempt|
explanation += "failed at: #{attempt.created_at}\n"
end
attempt = attempt_array[-1]
explanation += "succeeded at: #{attempt.created_at}\n"
end
end
private
def attempt_only_if_not_failed
errors.add(:attempt, "webhook.cannot_attempt_while_failed") if failed and attempt
end
def assign_defaults
self.attempt = true if self.attempt.nil?
self.failed = false if self.failed.nil?
end
def headers_are_valid_json_if_present
headers_ok = self.post_headers ? JSON.parse(self.post_headers) : true
errors.add(:headers, "webhook.cannot_have_non_json_parsable_headers_if_they_are_present") unless headers_ok
end
end
|
class CreateUserProfiles < ActiveRecord::Migration[5.1]
def change
create_table :user_profiles do |t|
t.belongs_to :user, index: true, foreign_key: true, null: false
t.attachment :profile_picture
t.string :address
t.string :brand
t.string :business_owner
t.string :representative_name
t.string :website
t.timestamps
end
end
end
|
# == Schema Information
#
# Table name: results
#
# id :integer not null, primary key
# sets :string default([]), is an Array
# match_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Result < ApplicationRecord
belongs_to :match
def win
win_count = 0
loss_count = 0
if sets.count > 0
sets.each do |set|
set_result = set.split("-")
if set_result[0].to_i < set_result[1].to_i
loss_count += 1
else
win_count += 1
end
end
win_count > loss_count
else
nil
end
end
def is_match_in_the_future
match = Match.find(match_id)
match.match_datetime && match.match_datetime > Time.now
end
def summary
win_count = 0
loss_count = 0
if sets.count > 0
sets.each do |set|
set_result = set.split("-")
if set_result[0].to_i < set_result[1].to_i
loss_count += 1
else
win_count += 1
end
end
if win_count > loss_count
"Win"
else
"Loss"
end
elsif is_match_in_the_future
"Upcoming"
else
"Please add result"
end
end
def show_sets
sets.join(' , ')
end
end
|
class AddFeedItemCreatorId < ActiveRecord::Migration
def self.up
add_column :feed_items, :creator_id, :integer
end
def self.down
remove_column :feed_items, :creator_id
end
end
|
# -*- coding: utf-8 -*-
require 'mui/cairo_miracle_painter'
require 'gtk2'
module Gtk
class CellRendererMessage < CellRendererPixbuf
type_register
install_property(GLib::Param::String.new("uri", "uri", "Resource URI", "hoge", GLib::Param::READABLE|GLib::Param::WRITABLE))
attr_reader :message
def initialize()
super() end
# Register events for this Renderer:
signal_new("button_press_event", GLib::Signal::RUN_FIRST, nil, nil,
Gdk::EventButton, Gtk::TreePath, Gtk::TreeViewColumn,
Integer, Integer)
signal_new("button_release_event", GLib::Signal::RUN_FIRST, nil, nil,
Gdk::EventButton, Gtk::TreePath, Gtk::TreeViewColumn,
Integer, Integer)
signal_new("motion_notify_event", GLib::Signal::RUN_FIRST, nil, nil,
Gtk::BINDING_VERSION >= [2,0,3] ? Gdk::EventMotion : Gdk::EventButton,
Gtk::TreePath, Gtk::TreeViewColumn,
Integer, Integer)
signal_new("leave_notify_event", GLib::Signal::RUN_FIRST, nil, nil,
Gtk::BINDING_VERSION >= [2,0,3] ? Gdk::EventCrossing : Gdk::EventButton,
Gtk::TreePath, Gtk::TreeViewColumn,
Integer, Integer)
signal_new("click", GLib::Signal::RUN_FIRST, nil, nil,
Gdk::EventButton, Gtk::TreePath, Gtk::TreeViewColumn,
Integer, Integer)
def signal_do_button_press_event(e, path, column, cell_x, cell_y)
end
def signal_do_button_release_event(e, path, column, cell_x, cell_y)
end
def signal_do_motion_notify_event(e, path, column, cell_x, cell_y)
end
def signal_do_leave_notify_event(e, path, column, cell_x, cell_y)
end
def signal_do_click(e, path, column, cell_x, cell_y)
end
def tree=(tree)
@tree = tree
tree.add_events(Gdk::Event::BUTTON_PRESS_MASK|Gdk::Event::BUTTON_RELEASE_MASK)
armed_column = nil
last_motioned = nil
click_start = []
tree.ssc("leave_notify_event") { |w, e|
if last_motioned
signal_emit("leave_notify_event", e, *last_motioned)
last_motioned = nil end
false }
tree.ssc("motion_notify_event") { |w, e|
path, column, cell_x, cell_y = tree.get_path_at_pos(e.x, e.y)
if column
armed_column = column
motioned = [path, column, cell_x, cell_y]
signal_emit("motion_notify_event", e, *motioned)
if last_motioned
motioned_message = @tree.get_record(motioned[0]).message rescue nil
last_motioned_message = @tree.get_record(last_motioned[0]).message rescue nil
if(last_motioned_message and motioned_message != last_motioned_message)
emit_leave_notify_from_event_motion(e, *last_motioned) end end
last_motioned = motioned end }
tree.ssc("button_press_event") { |w, e|
path, column, cell_x, cell_y = tree.get_path_at_pos(e.x, e.y)
click_start = [cell_x, cell_y]
if column
armed_column = column
signal_emit("button_press_event", e, path, column, cell_x, cell_y) end
e.button == 3 && tree.get_active_pathes.include?(path) # 選択してるものを右クリックした時は、他のセルの選択を解除しない
}
tree.ssc("button_release_event") { |w, e|
path, column, cell_x, cell_y = tree.get_path_at_pos(e.x, e.y)
if column
cell_x ||= -1
cell_y ||= -1
signal_emit("button_release_event", e, path, column, cell_x, cell_y)
if click_start.size == 2 and click_start.all?{|x| x.respond_to? :-} and (column == armed_column) and (click_start[0] - cell_x).abs <= 4 and (click_start[1] - cell_y).abs <= 4
signal_emit("click", e, path, column, cell_x, cell_y) end
armed_column = nil end }
last_selected = Set.new(tree.selection.to_enum(:selected_each).map{ |m, p, i| i[3] }).freeze
tree.selection.ssc("changed") { |this|
now_selecting = Set.new(this.to_enum(:selected_each).map{ |m, p, i| i[3] }).freeze
new_selected = now_selecting - last_selected
unselected = last_selected - now_selecting
new_selected.each(&:on_selected)
unselected.each(&:on_unselected)
last_selected = now_selecting
false }
event_hooks end
# Messageに関連付けられた Gdk::MiraclePainter を取得する
def miracle_painter(message)
record = @tree.get_record_by_message(message)
if record and record.miracle_painter
record.miracle_painter
else
@tree.update!(message, Gtk::TimeLine::InnerTL::MIRACLE_PAINTER, create_miracle_painter(message)) end end
# MiraclePainterを生成して返す
def create_miracle_painter(message)
Gdk::MiraclePainter.new(message, avail_width).set_tree(@tree)
end
def uri=(uri)
record = @tree.get_record_by_uri(uri)
if record and record.message
return render_message(record.message)
else
self.pixbuf = Skin[:notfound].pixbuf(width: 64, height: 64) end
rescue Exception => err
error "#{err.class} by uri: #{uri} model: #{record ? record.message.inspect : nil}"
raise if Mopt.debug
error err
self.pixbuf = Skin[:notfound].pixbuf(width: 64, height: 64) end
private
def user
message[:user]
end
def render_message(message)
if(@tree.realized?)
h = miracle_painter(message).height
miracle_painter(message).width = @tree.get_cell_area(nil, @tree.get_column(0)).width
if(h != miracle_painter(message).height)
@tree.get_column(0).queue_resize end end
self.pixbuf = miracle_painter(message).pixbuf end
# 描画するセルの横幅を取得する
def avail_width
[@tree.get_column(0).width, 100].max
end
def event_hooks
last_pressed = nil
ssc(:click, @tree){ |r, e, path, column, cell_x, cell_y|
record = @tree.get_record(path)
record.miracle_painter.clicked(cell_x, cell_y, e) if record
false }
ssc(:button_press_event, @tree){ |r, e, path, column, cell_x, cell_y|
record = @tree.get_record(path)
if record
last_pressed = record.miracle_painter
if e.button == 1
last_pressed.pressed(cell_x, cell_y) end
Delayer.new(:ui_response) {
Plugin::GUI.keypress(::Gtk::buttonname([e.event_type, e.button, e.state]), @tree.imaginary) }
end
false }
ssc(:button_release_event, @tree){ |r, e, path, column, cell_x, cell_y|
if e.button == 1 and last_pressed
record = @tree.get_record(path)
if record
if(last_pressed == record.miracle_painter)
last_pressed.released(cell_x, cell_y)
else
last_pressed.released end end
last_pressed = nil end
false }
ssc(:motion_notify_event, @tree){ |r, e, path, column, cell_x, cell_y|
record = @tree.get_record(path)
record.miracle_painter.point_moved(cell_x, cell_y) if record
false }
ssc(:leave_notify_event, @tree){ |r, e, path, column, cell_x, cell_y|
record = @tree.get_record(path)
record.miracle_painter.point_leaved(cell_x, cell_y) if record
false }
end
# RubyGtk2 2.0.3以降は、motion_notify_eventやleave_notify_eventに
# 発行されるイベントが変更されている
if Gtk::BINDING_VERSION >= [2,0,3]
def emit_leave_notify_from_event_motion(e, *args)
signal_emit("leave_notify_event",
Gdk::EventCrossing.new(Gdk::Event::LEAVE_NOTIFY).tap{ |le|
le.time = e.time
le.x, le.y = e.x, e.y
le.x_root, le.y_root = e.x_root, e.y_root
le.focus = true
}, *args) end
else
def emit_leave_notify_from_event_motion(e, *args)
signal_emit("leave_notify_event", e, *args) end end
end
end
|
# describe "Class" do
# it "should have an attr_accessor_with_history method" do
# lambda { Class.new.attr_accessor_with_history }.should_not raise_error(::NoMethodError)
# end
# end
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s # make sure it's a string
attr_reader attr_name # create the attribute's getter
attr_reader attr_name+"_history" # create bar_history getter
class_eval %Q"
def #{attr_name}=(val)
if !defined? @#{attr_name}_history
@#{attr_name}_history = [@#{attr_name}]
end
@#{attr_name} = val
@#{attr_name}_history << val
end"
# "your code here, use %Q for multiline strings"
end
end
class Foo
attr_accessor_with_history :bar
end
f = Foo.new
f.bar = 1
f.bar = 2
puts f.bar_history # => if your code works, should be [nil,1,2]
|
# encoding: utf-8
Given(/^I visit login page$/) do
login.load
end
Given(/^I'm on login page$/) do
expect(page).to have_current_path('/login')
end
When(/^I try to login with user "([^"]*)" and password "([^"]*)"$/) do |username, password|
login.loginIn(username, password)
end
Then(/^I can see the welcome page$/) do
expect(page).to have_current_path('/employees')
end
Then(/^I should see the error message "([^"]*)"$/) do |message|
page.should have_content message
end |
source 'https://rubygems.org'
ruby '2.3.0'
gem 'rails', '>= 5.0.0.beta3', '< 5.1'
gem 'puma', '~> 3.1'
gem 'secure_headers', '~> 3.0'
gem 'pg', '~> 0.18.4'
gem 'active_model_serializers', '~> 0.10.0.rc4'
gem 'rack-cors', '~> 0.4.0'
gem 'bcrypt', '~> 3.1'
# Remove it when the rspec include this fix: https://github.com/rspec/rspec-core/pull/2197
gem 'rake', '< 11.0'
group :production, :staging do
gem 'rails_12factor', '0.0.3'
gem 'newrelic_rpm', '~> 3.15.0'
gem 'rollbar', '~> 2.8'
gem 'librato-rails', '~> 1.2'
end
group :development do
gem 'foreman', '0.78.0'
gem 'binding_of_caller', '0.7.2'
gem 'letter_opener', '1.4.1'
gem 'bullet', '~> 5.0'
gem 'listen', '~> 3.0.5'
end
group :test do
gem 'shoulda-matchers', '~> 3.1.1'
gem 'simplecov', '0.10.0', require: false
gem 'email_spec', '1.6.0'
gem 'database_cleaner', '1.4.1'
gem 'codeclimate-test-reporter', require: false
gem 'rspec-rails', '>= 3.5.0.beta1'
gem 'rails-controller-testing', '~> 0.1.1'
end
group :development, :test do
gem 'factory_girl_rails', '~> 4.6'
gem 'pry-rails', '0.3.4'
gem 'dotenv-rails', '1.0.2'
gem 'awesome_print', '1.6.1'
gem 'spring-commands-rspec', '1.0.4'
gem 'byebug', '5.0.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
|
module PasswordResettable
extend ActiveSupport::Concern
included do
validates :password_reset_token, :uniqueness => true, :allow_nil => true
before_save :unset_password_reset_token
end
def send_password_reset_instructions
set_password_reset_token
PasswordResetMailer.send_reset_instructions(self).deliver
end
private
def set_password_reset_token
self.password_reset_token = new_password_reset_token
self.save
end
def new_password_reset_token
SecureRandom.urlsafe_base64(30)
end
def unset_password_reset_token
self.password_reset_token = nil unless password_reset_token_changed?
end
end |
productos = [
'acai',
'ackee',
'apple',
'apricot',
'avocado',
'banana',
'bilberry',
'blackberry',
'blackcurrant',
'black',
'blueberry',
'boysenberry',
'breadfruit',
'buddha',
'cactus',
'crab',
'currant',
'cherry',
'cherimoya',
'chico',
'cloudberry',
'coconut',
'cranberry',
'damson',
'date',
'dragonfruit',
'durian',
'elderberry',
'feijoa',
'fig',
'goji',
'gooseberry',
'grape',
'grewia',
'raisin',
'grapefruit',
'guava',
'hala',
'honeyberry',
'huckleberry',
'jabuticaba',
'jackfruit',
'jambul',
'japanese',
'jostaberry',
'jujube',
'juniper',
'kiwano',
'kiwifruit',
'kumquat',
'lemon',
'lime',
'loganberry',
'loquat',
'longan',
'lychee',
'mango',
'mangosteen',
'marionberry',
'melon',
'cantaloupe',
'galia',
'honeydew',
'watermelon',
'miracle',
'monstera',
'mulberry',
'nance',
'nectarine',
'orange',
'blood',
'clementine',
'mandarine',
'tangerine',
'papaya',
'passionfruit',
'peach',
'pear',
'persimmon',
'plantain',
'plum',
'prune',
'pineapple',
'pineberry',
'plumcot',
'pomegranate',
'pomelo',
'purple',
'quince',
'raspberry',
'salmonberry',
'rambutan',
'redcurrant',
'salal',
'salak',
'satsuma',
'soursop',
'star',
'star',
'strawberry',
'surinam',
'tamarillo',
'tamarind',
'tangelo',
'tayberry',
'ugli',
'white',
'white',
'yuzu'
]
productos.each do |fruta|
puts fruta
end
puts ""
puts productos.include? 'chico'
puts productos.include? 'chillo'
productos [21] = 'cochinito'
puts ""
puts productos.index 'cochinito'
puts productos.index 'hala'
puts productos.index 'mangosteen'
puts ""
productos << 'zulu'
puts ""
puts productos.index 'zulu'
coconut = productos [21]
puts productos.index 'coconut'
puts productos.first
puts productos.last
|
class Amount
attr_reader :value
def initialize(value)
@value = Integer(value)
end
def sum(a)
self.new(a.value + self.value)
end
def sub(a)
self.new(a.value - self.value)
end
end |
class Restaurant < ApplicationRecord
belongs_to :cuisine
has_many :reviews
has_one :restaurant_reviews_metadatum
after_create :create_restaurant_metadata
validates :name, :address, :delivery_sla_in_minutes, :longitude, :latitude, presence: true
validates :does_accept_10bis, inclusion: { in: [true, false] }
def create_restaurant_metadata
create_restaurant_reviews_metadatum(reviews_count: 0, avarage_score: 0)
end
end
|
require 'fileutils'
class Hakiri::Manifest < Hakiri::Cli
#
# Generates a JSON manifest file
#
def generate
FileUtils::copy_file "#{File.dirname(__FILE__)}/manifest.json", "#{Dir.pwd}/manifest.json"
File.chmod 0755, "#{Dir.pwd}/manifest.json"
say '-----> Generating a manifest file...'
say " Generated a manifest file in #{Dir.pwd}/manifest.json"
say " Edit it and run \"hakiri system:scan\""
end
end |
class AddMissingColumnsToFields < ActiveRecord::Migration[5.2]
def change
add_column :fields, :validation_type, :string
add_column :fields, :description, :text
end
end
|
require 'gosu_android/input/buttons'
module Gosu
class Button
attr_reader :id
def initialize(*args)
case args.length
when 0
@id = NoButton
when 1
@id = args[0]
else
raise ArgumentError
end
end
# Tests whether two Buttons identify the same physical button.
def == other
self.id == other.id
end
def > other
self.id > other.id
end
def < other
self.id < other.id
end
end
# Struct that saves information about a touch on the surface of a multi-
# touch device.
class Touch < Struct.new(:id, :x, :y); end
# Manages initialization and shutdown of the input system. Only one Input
# instance can exist per application.
class Input
def initialize(display, window, max_x, max_y)
@display = display
@window = window
@touch_event_list = []
@key_event_list_up = []
@key_event_list_down = []
@id = 0
@max_x = max_x
@max_y = max_y
@ignore_buttons = [JavaImports::KeyEvent::KEYCODE_VOLUME_DOWN,
JavaImports::KeyEvent::KEYCODE_VOLUME_MUTE,
JavaImports::KeyEvent::KEYCODE_VOLUME_UP,
JavaImports::KeyEvent::KEYCODE_BACK,
JavaImports::KeyEvent::KEYCODE_HOME,
JavaImports::KeyEvent::KEYCODE_MENU,
JavaImports::KeyEvent::KEYCODE_POWER,
JavaImports::KeyEvent::KEYCODE_APP_SWITCH,
JavaImports::KeyEvent::KEYCODE_UNKNOWN]
end
def feed_touch_event(event)
@touch_event_list.push event
end
def feed_key_event_down(keyCode)
if @ignore_buttons.include? keyCode
return false
end
@key_event_list_down.push keyCode
return true
end
def feed_key_event_up(keyCode)
if @ignore_buttons.include? keyCode
return false
end
@key_event_list_up.push keyCode
return true
end
# Returns the character a button usually produces, or 0.
def id_to_char(btn); end
# Returns the button that has to be pressed to produce the
# given character, or noButton.
def char_to_id(ch); end
# Returns true if a button is currently pressed.
# Updated every tick.
def button_down?(id)
return @key_event_list_down.include? id
end
# Returns the horizontal position of the mouse relative to the top
# left corner of the window given to Input's constructor.
def mouseX; end
# Returns true if a button is currently pressed.
# Updated every tick.
def mouseY; end
# Immediately moves the mouse as far towards the desired position
# as possible. x and y are relative to the window just as in the mouse
# position accessors.
def set_mouse_position(x, y); end
# Undocumented for the moment. Also applies to currentTouches().
def set_mouse_factors(factorX, factorY); end
# Currently known touches.
def currentTouches; end
# Accelerometer positions in all three dimensions (smoothened).
def accelerometerX; end
def accelerometerY; end
def accelerometerZ; end
# Collects new information about which buttons are pressed, where the
# mouse is and calls onButtonUp/onButtonDown, if assigned.
def update
@touch_event_list.each do |touch_event|
touch_event.getPointerCount.times do |index|
touch = Touch.new(touch_event. getPointerId(index), touch_event.getX(index), touch_event.getY(index))
#Check is touch is inside the screen use, otherwise ignore it
if(touch.x > 0 and touch.x < @max_x and touch.y > 0 and touch.y < @max_y)
case touch_event.getAction
when JavaImports::MotionEvent::ACTION_DOWN
@window.touch_began(touch)
when JavaImports::MotionEvent::ACTION_MOVE
@window.touch_moved(touch)
when JavaImports::MotionEvent::ACTION_UP
@window.touch_ended(touch)
end
end
end
end
@key_event_list_down.each do |key_event|
@window.button_down key_event
end
@key_event_list_up.each do |key_event|
@window.button_up key_event
end
end
def clear
@touch_event_list.clear
@key_event_list_down.clear
@key_event_list_up.clear
end
# Assignable events that are called by update. You can bind these to your own functions.
# If you use the Window class, it will assign forward these to its own methods.
def button_down; end
def button_up; end
# Returns the currently active TextInput instance, or 0.
def text_input; end
# Sets the currently active TextInput, or clears it (input = 0).
def set_text_input(input); end
end
end
|
class StreetSwarm < ApplicationRecord
belongs_to :user
belongs_to :chapter
has_one :address, through: :chapter
scope :with_addresses, -> { includes(:address) }
def self.options
['Street Swarms']
end
validates :user, :chapter, presence: true
validates :mobilizers_attended,
numericality: { only_integer: true,
greater_than_or_equal_to: 1,
less_than_or_equal_to: 1_000_000_000 }
validates_length_of :identifier, maximum: 50
def self.to_csv
attributes = %w{chapter_name coordinator_email mobilizers_attended identifier report_date created_at}
CSV.generate(headers: true) do |csv|
csv << attributes
all.includes(:chapter, :user).find_each do |m|
csv << [m.chapter.name, m.user.email, m.mobilizers_attended, m.identifier, m.report_date, m.created_at]
end
end
end
end
|
# frozen_string_literal: true
require "spec_helper"
describe Decidim::Participations::FilteredParticipations do
let(:organization) { create(:organization) }
let(:participatory_process) { create(:participatory_process, organization: organization) }
let(:feature) { create(:participation_feature, participatory_space: participatory_process) }
let(:another_feature) { create(:participation_feature, participatory_space: participatory_process) }
let(:participations) { create_list(:participation, 3, feature: feature) }
let(:old_participations) { create_list(:participation, 3, feature: feature, created_at: 10.days.ago) }
let(:another_participations) { create_list(:participation, 3, feature: another_feature) }
it "returns participations included in a collection of features" do
expect(described_class.for([feature, another_feature])).to match_array participations.concat(old_participations, another_participations)
end
it "returns participations created in a date range" do
expect(described_class.for([feature, another_feature], 2.weeks.ago, 1.week.ago)).to match_array old_participations
end
end
|
class PostedProjectSerializer < ActiveModel::Serializer
attributes :id, :student_id, :project_id
end
|
class LastfmWrapper::Artist < LastfmWrapper::Base
SEARCH_LIMIT = 10
def self.info keyword, opts = {}
opts.merge! :artist => keyword, :autocorrect => 1, :lang => 'jp'
result = self.api.artist.get_info opts
if result.blank?
return nil
end
main_image = nil
thumbnail_image = nil
result['image'].each do |image|
main_image = image['content'] if image['size'] == 'mega'
thumbnail_image = image['content'] if image['size'] == 'large'
end
artist = {
:name => result['name'],
:mbid => result['mbid'],
:main_image => main_image,
:thumbnail_image => thumbnail_image.sub(/126/, '126s'),
:url => result['url'],
:summary => result['bio']['summary'].instance_of?(String) ? result['bio']['summary'] : '',
:content => result['bio']['content'].instance_of?(String) ? result['bio']['content'] : ''
}
end
def self.images keyword, opts = {}
opts.merge! :artist => keyword, :autocorrect => 1, :limit => 24
result = self.api.artist.get_images opts
artist_images = []
if result.present? && result.length > 0
result.each do |r|
next if r['sizes'].nil? || r['sizes']['size'].nil?
artist_image = {}
r['sizes']['size'].each do |size|
artist_image["#{size['name']}".to_sym] = size['content']
end
artist_images << artist_image
end
end
artist_images
end
def self.search keyword, opts = {}
opts.merge! :artist => keyword
results = Rails.cache.fetch "lastfm_wrapper_search_#{Digest::SHA256.hexdigest(keyword)}", :expires_in => 12.hours do
self.api.artist.search opts
end
if results.blank? || results['artistmatches']['artist'].nil?
return []
end
artists = []
if results['artistmatches']['artist'].instance_of? Array
results['artistmatches']['artist'].each do |artist|
res = self.format_search_result artist
artists << res if res.present?
end
elsif results['artistmatches']['artist'].instance_of? Hash
res = self.format_search_result results['artistmatches']['artist']
artists << res if res.present?
end
artists
end
private
def self.format_search_result artist
return false if artist['image'].reject{|image|image['content'].nil?}.blank?
return false if artist['image'].select{|image|image['content'] =~ /mistagged/}.present?
return false if artist['url'].blank?
mbid = (artist['mbid']=~/[0-9a-zA-Z]/) ? artist['mbid'] : nil
result = {
:name => artist['name'],
:mbid => mbid,
:url => artist['url'],
:streamable => artist['streamable'],
}
artist['image'].each do |image|
result[image['size'].to_sym] = image['content']
end
result
end
end
|
class AddCachedAnnotationsCountToProjectMedia < ActiveRecord::Migration
def change
add_column :project_medias, :cached_annotations_count, :integer, default: 0
end
end
|
Pod::Spec.new do |s|
s.name = 'RaptureXML'
s.version = '1.0.1'
s.source = { :http => 'http://repository.neonstingray.com/content/repositories/thirdparty/com/rapturexml/ios/rapturexml/1.0.1/rapturexml-1.0.1.zip' }
s.platform = :ios
s.source_files = 'RaptureXML/**/*'
s.libraries = 'z', 'xml2'
s.xcconfig = { 'HEADER_SEARCH_PATHS' => '$(SDKROOT)/usr/include/libxml2' }
end |
class Topic < ApplicationRecord
validates :name, presence: true, length: {minimum: 5}
validates :description, presence: true, length: {maximum: 250}
mount_uploader :picture, PictureUploader
# Validates the size of and Uploaded image
def picture_size
if picture.size > 5.megabytes
errors.add(:picture, "Image file size should be less than 5MB")
end
end
end |
class AddFriendlyIdToDeliveryRequests < ActiveRecord::Migration
def change
if Rails.env.test?
add_column :delivery_requests, :slug, :string
else
add_column :delivery_requests, :slug, :string, null: false
end
DeliveryRequest.find_each(&:save)
# add_column :delivery_requests, :url_hash, :string
add_index :delivery_requests, :slug, unique: true
end
end
|
module EsClient
class Client
RETRY_TIMES = 1
HTTP_VERBS = %i(get post put delete head)
SUCCESS_HTTP_CODES = [200, 201]
def initialize(host, options)
@host = host
@options = options
end
HTTP_VERBS.each do |method|
class_eval <<-DEF, __FILE__, __LINE__ + 1
def #{method}(path, options={})
request options.merge(method: :#{method}, path: path)
end
def #{method}!(path, options={})
options[:expects] = SUCCESS_HTTP_CODES
#{method}(path, options)
end
DEF
end
def request(options)
retry_times = 0
begin
raw_response = http.request(options)
response = ::EsClient::Response.new(raw_response.body, raw_response.status, raw_response.headers)
EsClient.logger.request(http, response, options) if EsClient.logger.try!(:debug?)
response
rescue Excon::Errors::SocketError => e
if retry_times >= RETRY_TIMES
EsClient.logger.exception(e, http, options) if EsClient.logger
raise
end
retry_times += 1
EsClient.logger.info "[#{retry_times}] Try reconnect to #{@host}"
reconnect!
retry
rescue Excon::Errors::BadRequest => e
EsClient.logger.exception(e, http, options.merge(response: e.response.body)) if EsClient.logger
raise
end
end
def http
@http ||= Excon.new(@host, @options)
end
def reconnect!
@http = nil
end
def log(message, level=:info)
EsClient.logger.try!(level, message)
end
end
end |
class CreatePeppers < ActiveRecord::Migration[5.2]
def change
rename_table :tomatoes, :plants
add_column :plants, :type, :string
end
end
|
# Borrowed from https://github.com/yui-knk/mruby-set
class Set
include Enumerable
def self.[](*ary)
new(ary)
end
def initialize(enum = nil, &block)
@hash ||= Hash.new
enum.nil? and return
if block_given?
do_with_enum(enum) { |o| add(block.call(o)) }
else
merge(enum)
end
end
def do_with_enum(enum, &block)
if enum.respond_to?(:each)
enum.each(&block)
else
raise ArgumentError, "value must be enumerable"
end
end
private :do_with_enum
def initialize_copy(orig)
super
@hash = orig.instance_variable_get(:@hash).dup
end
# def initialize_dup(orig)
# super
# @hash = orig.instance_variable_get(:@hash).dup
# end
# def initialize_clone(orig)
# super
# @hash = orig.instance_variable_get(:@hash).clone
# end
# def freeze
# @hash.freeze
# super
# end
# def taint
# @hash.taint
# super
# end
# def untaint
# @hash.untaintG
# super
# end
def size
@hash.size
end
alias length size
def empty?
@hash.empty?
end
def clear
@hash.clear
self
end
def replace(enum)
clear
merge(enum)
end
def to_a
@hash.keys
end
# def to_set
# end
#
def flatten_merge(set, seen = Set.new)
seen.add(set.object_id)
set.each { |e|
if e.is_a?(Set)
if seen.include?(e_id = e.object_id)
raise ArgumentError, "tried to flatten recursive Set"
end
flatten_merge(e, seen)
else
add(e)
end
}
seen.delete(set.object_id)
self
end
def flatten
self.class.new.flatten_merge(self)
end
def flatten!
if detect { |e| e.is_a?(Set) }
replace(flatten())
else
nil
end
end
def include?(o)
@hash.include?(o.to_s)
end
alias member? include?
def superset?(set)
raise ArgumentError, "value must be a set" unless set.is_a?(Set)
return false if size < set.size
set.all? { |o| include?(o) }
end
alias >= superset?
def proper_superset?(set)
raise ArgumentError, "value must be a set" unless set.is_a?(Set)
return false if size <= set.size
set.all? { |o| include?(o) }
end
alias > proper_superset?
def subset?(set)
raise ArgumentError, "value must be a set" unless set.is_a?(Set)
set.superset?(self)
end
alias <= subset?
def proper_subset?(set)
raise ArgumentError, "value must be a set" unless set.is_a?(Set)
set.proper_superset?(self)
end
alias < proper_subset?
def intersect?(set)
raise ArgumentError, "value must be a set" unless set.is_a?(Set)
if size < set.size
any? { |o| set.include?(o) }
else
set.any? { |o| include?(o) }
end
end
def disjoint?(set)
!intersect?(set)
end
def each(&block)
return to_enum :each unless block_given?
@hash.each_key(&block)
self
end
def add(o)
@hash[o] = true
self
end
alias << add
def add?(o)
if include?(o)
nil
else
add(o)
end
end
def delete(o)
@hash.delete(o)
self
end
def delete?(o)
if include?(o)
delete(o)
else
nil
end
end
def delete_if
return to_enum :delete_if unless block_given?
select { |o| yield o }.each { |o| @hash.delete(o) }
self
end
def keep_if
return to_enum :keep_if unless block_given?
reject { |o| yield o }.each { |o| @hash.delete(o) }
self
end
def collect!
return to_enum :collect! unless block_given?
set = self.class.new
each { |o| set << yield(o) }
replace(set)
end
alias map! collect!
def reject!(&block)
return to_enum :reject! unless block_given?
n = size
delete_if(&block)
size == n ? nil : self
end
def select!(&block)
return to_enum :select! unless block_given?
n = size
keep_if(&block)
size == n ? nil : self
end
def merge(enum)
if enum.instance_of?(self.class)
@hash.merge!(enum.instance_variable_get(:@hash))
else
do_with_enum(enum) { |o| add(o) }
end
self
end
def subtract(enum)
do_with_enum(enum) { |o| delete(o) }
self
end
def |(enum)
dup.merge(enum)
end
alias + |
alias union |
def -(enum)
dup.subtract(enum)
end
alias difference -
def &(enum)
n = Set.new
do_with_enum(enum) { |o| n.add(o) if include?(o) }
n
end
alias intersection &
def ^(enum)
(self | Set.new(enum)) - (self & Set.new(enum))
end
def ==(other)
if self.equal?(other)
true
elsif other.instance_of?(self.class) && self.size == other.size
other_hash = other.instance_variable_get(:@hash)
other_hash.keys.all? { |o| @hash.keys.include?(o) }
other_hash.values.all? { |o| @hash.values.include?(o) }
# @hash == other.instance_variable_get(:@hash)
elsif other.is_a?(self.class) && self.size == other.size
other.all? { |o| include?(o) }
else
false
end
end
def hash
@hash.hash
end
def eql?(o)
return false unless o.is_a?(Set)
@hash.eql?(o.instance_variable_get(:@hash))
end
def classify
return to_enum :classify unless block_given?
h = {}
each { |i|
x = yield(i)
(h[x] ||= self.class.new).add(i)
}
h
end
def divide(&func)
return to_enum :divide unless block_given?
if func.arity == 2
raise NotImplementedError, "Set#divide with 2 arity block is not implemented."
end
Set.new(classify(&func).values)
end
def inspect
"#<#{self.class}: {#{self.to_a.inspect[1..-2]}}>"
end
end
# mruby-set
#
# Copyright (c) yui-knk 2016
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
|
class AuthorsController < ApplicationController
def show
@author = Author.find(params[:id])
end
def new
end
def create
@author = Author.new(author_params)
respond_to do |format|
if @author.save
format.html { redirect_to author_path(@author), notice: 'Author Successfully created.' }
else
format.html { render :new }
end
end
end
private
def author_params
params.permit(:email, :name)
end
end
|
require 'resourceful'
require 'dm-core/adapters/abstract_adapter'
module DataMapper::Adapters
class AbstractRestAdapter < AbstractAdapter
attr_reader :http_accessor
def initialize(name, options)
super
@http = Resourceful::HttpAccessor.new
@http.logger = @options[:logger] || Resourceful::BitBucketLogger.new
setup_authenticator
setup_cache_manager
end
def setup_authenticator
return unless auth_mode = @options[:auth]
realm = @options[:realm]
username, password = @options[:username], @options[:password]
if auth_mode = :basic
@http.add_authenticator Resourceful::BasicAuthenticator.new(realm, username, password)
elsif auth_mode == :digest
@http.add_authenticator Resourceful::DigestAuthenticator.new(realm, username, password)
end
end
def setup_cache_manager
return unless cache_manager = @options[:caching]
if cache_manager == true || cache_manager == :in_memory
@http.cache_manager = Resourceful::InMemoryCacheManager.new
end
end
def logger
@http.logger
end
end
end
|
###################################################################
# Ruby Script to check if algorithm works in any of 32 posible states
# The riddle consist on a line of 5 people wearing a t-shirt with a white or black dot on the back.
# A killer with a gun asks each of them in order what's the dot's color on his t-shirt.
# If the one he is asking gets it right, lives, if doesn't he dies.
# Objective is trying to get a way always at least 4 of them survive
# Algorithm
# | f(x0) = c(1,x0)
# f(x)=|
# | f(xi) = c(1,xi) XOR f(x0) |-| 0 < xi <= 5
#
# C(1,xi): says if number of 1's is par or odd without taking into account xi or x0
###################################################################
class NotPerfectAlgorithm < RuntimeError
end
module RiddleRow5
@row, @alives, @answers = [], [], []
def self.run1 row
init row
fx
die
showResults
end
def self.runall
(0..31).each { |n| run1 ("%05b" % n).scan(/./) }
puts "All cases are completed, your algorithm is perfect, well done!"
end
private
def self.init row
@row = row
@alives.clear
@answers.clear
end
def self.fx
@answers.push fx0
ronly4.each { |xi| @answers << fxi(xi) }
end
# Kill person if answered wrong
def self.die
@row.each_with_index { |xi, i| xi == @answers[i] ? @alives << "V" : @alives << "M" }
end
def self.showResults
nAlives = @alives.count("V")
puts %[Row init:\t#{@row}\nAnswers:\t#{@answers}\nLeft alives:\t#{@alives} - #{nAlives}/5]
raise NotPerfectAlgorithm.new "Solution did not work on this case" unless nAlives >=4
puts "--------------------------------------------"
end
# What x0 sees
def self.fx0
c1 @row.first
end
# What xi sees thinking on what x0 saw
def self.fxi xi
n1 = c1 xi
(n1 ^ @answers.first.to_i).to_s
end
def self.c1 xi
block = lambda { |x| x.object_id != xi.object_id && x=="1" }
ronly4.count(&block) % 2
end
def self.ronly4
@row[1 , @row.size]
end
end
RiddleRow5.runall
|
require 'spec_helper'
describe Blog do
before do
@blog = Blog.new(title: "Hurray")
end
subject { @blog }
it { should be_valid }
# shoulda relations
it { should belong_to(:user)}
it { should belong_to(:main_photo).class_name('Photo')}
it { should have_many(:photo_sources).dependent(:destroy)}
it { should have_many(:photo_sources).class_name('PhotoSource')}
it { should have_many(:photos).through(:photo_sources)}
it { should have_many(:videos).through(:photo_sources)}
it { should have_many(:events)}
# relations
it { should respond_to(:user)}
it { should respond_to(:main_photo)}
it { should respond_to(:photo_sources)}
it { should respond_to(:photos)}
it { should respond_to(:videos)}
it { should respond_to(:events)}
it { should respond_to(:like_count)}
# attributes
it { should respond_to(:title)}
describe "blank title" do
before { @blog.title = " " }
it { should_not be_valid}
end
describe "after_save doesnt create an event" do
let(:user) { FactoryGirl.create(:user) }
it { expect do
user.blogs.create!(title: "temp")
end.to change(Event, :count).by(1) }
end
end |
class AddCountryAndWebsiteUrl < ActiveRecord::Migration[5.2]
def change
add_column :vet_profiles, :country, :string
add_column :vet_profiles, :website, :text
end
end
|
class Peep
include DataMapper::Resource
property :id, Serial
property :message, String, required: true
property :username, String
property :created_at, DateTime
belongs_to :user
end
|
class BlogEntriesController < ApplicationController
before_action :authenticate_user!, :except => [:show]
def new
@blog_entry = BlogEntry.new
end
def create
@blog_entry = BlogEntry.new(blog_entry_params)
if @blog_entry.save
flash[:notice] = "La entrada de blog ha sido guardada con éxito"
redirect_to blog_entries_path
else
flash[:alert] = "Ha ocurrido un problema y la entrada de blog no ha sido almacenada"
render :action => 'new'
end
end
def edit
@blog_entry = BlogEntry.find(params[:id])
end
def update
@blog_entry = BlogEntry.find(params[:id])
if @blog_entry.update(blog_entry_params)
flash[:notice] = "La entrada de blog ha sido editada con éxito"
redirect_to blog_entries_path
else
flash[:alert] = 'Ha ocurrido un problema y la entrada de blog no ha sido editada'
render 'edit'
end
end
def show
@blog_entry = BlogEntry.find(params[:id])
end
def index
@blog_entries = BlogEntry.all.order(created_at: :desc)
end
def destroy
@blog_entry = BlogEntry.find(params[:id])
@blog_entry.destroy
redirect_to blog_entries_path
end
private
def blog_entry_params
params.require(:blog_entry).permit(:title, :author, :image, :content)
end
end
|
class BooksController < ApplicationController
before_action :set_author, only: [:new, :create, :update]
def new
@user = current_user
@book = @author.books.build
respond_to do |format|
format.html
format.js
end
end
def create
@book = @author.books.build(book_params)
if @book.save
redirect_to author_path(@author)
flash[:success] = "New book added!"
else
redirect_to author_path(@author)
flash[:warning] = "Something went wrong. Please try again"
end
end
def edit
@book = Book.find(params[:id])
@author = @book.author
end
def update
@book = Book.find(params[:id])
updated = @book.update(book_params)
if updated
redirect_to author_path(@author)
flash[:success] = "Book information edited"
else
redirect_to author_path(@author)
flash[:warning] = "Something went wrong. Please try again"
end
end
def search
q = params[:q]
@book = Book.where("title LIKE ?", "%#{q}%").limit(8)
respond_to do |format|
format.html
format.json { render :json => @book }
end
end
private
def book_params
params.require(:book).permit(:author_id, :genre_id, :title,
:release_year, :synopsis, :language)
end
def set_author
author_id = params[:author].presence || book_params[:author_id]
@author = Author.find(author_id)
end
end
|
# =============================================================================
#
# MODULE : lib/dispatch_queue_rb/internal/thread_pool_queue.rb
# PROJECT : DispatchQueue
# DESCRIPTION :
#
# Copyright (c) 2016, Marc-Antoine Argenton. All rights reserved.
# =============================================================================
module DispatchQueue
class ThreadPoolQueue
def initialize( max_threads:nil, debug_trace:nil, thread_termination_delay:0.01 )
@max_threads = max_threads || [Dispatch.ncpu(), 2].max
@debug_trace = debug_trace
@thread_termination_delay = thread_termination_delay
@mutex = Mutex.new
@condition = ConditionVariable.new
@tasks = []
@worker_threads = Set.new
@idle_count = 0
end
def dispatch_async( group:nil, &task )
group.enter() if group
@mutex.synchronize do
@tasks << Continuation.new( group:group, &task )
@condition.signal()
_sync_try_spwan_more_threads()
end
self
end
alias_method :dispatch_barrier_async, :dispatch_async
include DispatchSyncImpl
include DispatchAfterImpl
def max_threads
@mutex.synchronize do
@max_threads
end
end
def max_threads=( new_value )
@mutex.synchronize do
@max_threads = new_value
_sync_try_spwan_more_threads()
end
end
def wait_for_all_threads_termination
loop do
sleep 0.001
break if @tasks.empty? && @worker_threads.empty?
end
end
private
def _worker_main()
Thread.current[:current_queue] = self
begin
loop do
task = _pop_task()
break if task.nil?
task.run()
end
ensure
@mutex.synchronize do
@worker_threads.delete( Thread.current )
@debug_trace.call( :terminated, { thread: Thread.current,
thread_count: @worker_threads.count,
idle_count: @idle_count,
task_count: @tasks.count } ) if @debug_trace
end
end
end
def _pop_task()
@mutex.synchronize do
return nil if @worker_threads.count > @max_threads
_sync_wait_for_item()
task = @tasks.shift();
_sync_try_spwan_more_threads() if task
task
end
end
#
# _sync_xxx() methods assume that the mutex is already owned
#
def _sync_try_spwan_more_threads()
return if @worker_threads.count >= @max_threads
return if @idle_count > 0
return if @tasks.empty?
thread = _sync_spawn_worker_thread()
@debug_trace.call( :spawned, { thread: thread,
from_thread: Thread.current,
thread_count: @worker_threads.count,
idle_count: @idle_count,
task_count: @tasks.count } ) if @debug_trace
end
def _sync_spawn_worker_thread()
thread = Thread.new { _worker_main() }
@worker_threads.add( thread )
thread
end
def _sync_wait_for_item()
if @tasks.empty?
@idle_count += 1
@condition.wait( @mutex, @thread_termination_delay )
@idle_count -= 1
end
end
end # class ThreadPoolQueue
end # module DispatchQueue
|
class ReleaseValidationsController < ApplicationController
# GET /release_validations
# GET /release_validations.json
def index
@release_validations = ReleaseValidation.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @release_validations }
end
end
# GET /release_validations/1
# GET /release_validations/1.json
def show
@release_validation = ReleaseValidation.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @release_validation }
end
end
# GET /release_validations/new
# GET /release_validations/new.json
def new
@release_validation = ReleaseValidation.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @release_validation }
end
end
# GET /release_validations/1/edit
def edit
@release_validation = ReleaseValidation.find(params[:id])
end
# POST /release_validations
# POST /release_validations.json
def create
@release_validation = ReleaseValidation.new(params[:release_validation])
respond_to do |format|
if @release_validation.save
format.html { redirect_to @release_validation, notice: 'Release validation was successfully created.' }
format.json { render json: @release_validation, status: :created, location: @release_validation }
else
format.html { render action: "new" }
format.json { render json: @release_validation.errors, status: :unprocessable_entity }
end
end
end
# PUT /release_validations/1
# PUT /release_validations/1.json
def update
@release_validation = ReleaseValidation.find(params[:id])
respond_to do |format|
if @release_validation.update_attributes(params[:release_validation])
format.html { redirect_to @release_validation, notice: 'Release validation was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @release_validation.errors, status: :unprocessable_entity }
end
end
end
# DELETE /release_validations/1
# DELETE /release_validations/1.json
def destroy
@release_validation = ReleaseValidation.find(params[:id])
@release_validation.destroy
respond_to do |format|
format.html { redirect_to release_validations_url }
format.json { head :no_content }
end
end
end
|
require "HTTParty"
require 'digest'
require 'rmagick'
require 'jaro_winkler'
class Arty
# Provide the names of the artists to render upon initialisation
def initialize(names)
@artists = names
@artwork_urls = []
@artwork_images = []
end
# Use the iTunes API to fetch the artwork images
# for the @artists provided. If an artist could not be found
# It will simply omitted from the resulting @artwork_urls array
def find_artwork
for artist in @artists
response = HTTParty.get(URI.encode("https://itunes.apple.com/search?term=#{artist}"))
response_object = JSON.parse(response.body)
for object in response_object["results"]
if JaroWinkler.distance(object["artistName"], artist) > 0.95 && object["collectionArtistName"] == nil && object["primaryGenreName"] != "Soundtrack"
url = object["artworkUrl100"]
url = url.sub("100x100", "600x600")
@artwork_urls.push(url)
break
end
end
end
while @artwork_urls.count < 4
random_artist = @artists.sample
response = HTTParty.get(URI.encode("https://itunes.apple.com/search?term=#{random_artist}"))
response_object = JSON.parse(response.body)
for object in response_object["results"]
if JaroWinkler.distance(object["artistName"], random_artist) > 0.95 && object["collectionArtistName"] == nil && object["primaryGenreName"] != "Soundtrack"
url = object["artworkUrl100"]
url = url.sub("100x100", "600x600")
if @artwork_urls.include?(url) == false
@artwork_urls.push(url)
break
end
end
end
end
end
def fetch_images
for image_url in @artwork_urls
File.open("./tmp/#{Digest::MD5.hexdigest(image_url)}.png", "wb") do |f|
f.write HTTParty.get(image_url).body
end
end
end
def generate_montage(output_file_path = nil)
self.find_artwork()
self.fetch_images()
i = Magick::ImageList.new
for image_url in @artwork_urls
i.read("./tmp/#{Digest::MD5.hexdigest(image_url)}.png")
end
image = i.montage do |mont|
mont.geometry = "400x400"
end
width = image.columns
degrees = 7
image.rotate!(degrees)
radians = degrees * Math::PI / 180
trim = Math.sin(radians) * width
image.shave!(trim, trim)
if output_file_path.nil?
output_file_path = "./tmp/output.jpeg"
end
image.write(output_file_path) {
self.quality = 100
self.format = 'JPEG'
}
end
end
|
#!/usr/bin/env ruby
# script will, given a path for projection manifests
# figure out what namespaces need to be created ahead of time
# output: list of <cluster>/<namespace> ...
# example: bf2-DEVEL/foo bf2-PRODUCTION/bar
require 'yaml'
require 'find'
require 'pathname'
path = ARGV[0] || '.'
abort "Require manifests path in as first parameter" if path.nil?
abort "#{path} is not a directory" unless File.directory? path
# now, read all yamls and figure out their namespaces
nstuples = Find.find(path).map do |p|
if File.file?(p) && File.readable?(p) && p.end_with?('.yaml')
# we need to determine what cluster this namespace is
# based on directory structure.
fullpath = File.expand_path(p)
path_components = fullpath.split(File::SEPARATOR)
az = path_components[-4]
cluster = path_components[-3]
manifest = YAML.load_file(p)
namespace = manifest['namespace']
if namespace.nil? || az.nil? || cluster.nil?
nil
else
["#{az}-#{cluster}", namespace]
end
else
nil
end
end.compact
nstuples.each do |(cluster, ns)|
puts "#{cluster}/#{ns}"
end
|
require_relative 'feed_persistence_service'
require_relative 'feed_updater'
class UpdateFeedTask
def initialize feed_persistence_service = FeedPersistenceService.new, feed_updater = FeedUpdater.new
@feed_persistence_service = feed_persistence_service
@feed_updater = feed_updater
end
def invoke
@feed_persistence_service.all.each do |feed|
begin
@feed_updater.update feed
rescue Exception => e
puts "Feed update failed for username: #{feed.username}: #{e.inspect}"
puts e.backtrace.join("\n")
end
end
end
end
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = 'avro'
spec.version = File.open('lib/avro/VERSION.txt').read.chomp
spec.authors = ['Apache Software Foundation']
spec.email = ['dev@avro.apache.org']
spec.summary = 'Apache Avro for Ruby'
spec.description = 'Avro is a data serialization and RPC format'
spec.homepage = 'https://avro.apache.org/'
spec.license = 'Apache-2.0'
spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
spec.test_files = Dir.glob('test/**/*')
spec.require_paths = ['lib']
spec.required_ruby_version = '>= 2.5'
spec.add_dependency 'multi_json', ' ~>1'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'snappy'
spec.add_development_dependency 'zstd-ruby'
spec.add_development_dependency 'test-unit'
# parallel 1.20.0 requires Ruby 2.5+
spec.add_development_dependency 'parallel', '<= 1.19.2'
# rubocop 0.82 requires Ruby 2.4+
spec.add_development_dependency 'rubocop', '<= 0.81'
# rdoc 6.2.1 requires Ruby 2.4+
spec.add_development_dependency 'rdoc', '<= 6.2.0'
end
|
json.array!(@scholarships) do |scholarship|
json.extract! scholarship, :id, :first_name, :last_name, :email, :phone, :gender, :birth_date, :employment_status, :reason, :future_plans, :full_program, :traineeship, :bootcamp_id
json.url scholarship_url(scholarship, format: :json)
end
|
class K0310
attr_reader :options, :name, :field_type, :node
def initialize
@name = "Weight Gain: Gain of 5% or more in the last month or gain of 10% or more in the last 6 months. (K0310)"
@field_type = DROPDOWN
@node = "K0310"
@options = []
@options << FieldOption.new("^", "NA")
@options << FieldOption.new("0", "No or unknown")
@options << FieldOption.new("1", "Yes, on physician-prescribed weight-loss regimen")
@options << FieldOption.new("2", "Yes, not on physician-prescribed weight-loss regimen")
end
def set_values_for_type(klass)
return "0"
end
end |
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def gif_urls
urls = self.gifs.collect{|gif| gif.url}
end
def gif_for_empty_pg(page)
case page
when page == "user"
"https://media1.giphy.com/media/xieuDEXX78OYw/giphy.gif?cid=e1bb72ff5b721ced653062486f766c3b"
when page == "/users/<%=current_user.id %>/gifs"
"https://media3.giphy.com/media/3o7bu7Xzqkq8K3MsUg/giphy.gif?cid=e1bb72ff5b6d082941355957369fe8fc"
when page == relationships_path
"https://media3.giphy.com/media/10htoZz7rhLZ6w/giphy.gif?cid=e1bb72ff5b7c64c07437726255d57718"
else
"https://media1.giphy.com/media/y63H09ZvHJdf2/giphy.gif?cid=e1bb72ff5b847740777678366b770bf1"
end
return content
# <%= raw gif_for_empty_pg(page) %>
end
end
|
module ControllerMacros
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
sign_in FactoryGirl.create(:user)
end
end
def login_admin
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:admin_user]
sign_in FactoryGirl.create(:admin_user, role: 'admin')
end
end
def sign_in(user)
visit root_path
click_link 'Log In'
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button "Sign In"
end
end |
#
# Cookbook:: docker-cookbook
# Recipe:: docker_service
#
# Copyright:: 2017, Steven Praski
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ugly conditional recipe inclusion, but it works
if node['docker-server']['storage-driver'] == 'zfs'
include_recipe 'docker-cookbook::zfs_storage'
docker_service 'default' do
storage_driver 'zfs'
action [:create, :start]
end
else
include_recipe 'docker-cookbook::lvm_storage'
docker_service 'default' do
storage_driver 'devicemapper'
storage_opts [ # ideally, should be read from /etc/sysconfig/docker-storage directly,...
'dm.fs=xfs',
'dm.thinpooldev=/dev/mapper/docker--vg-docker--pool',
'dm.use_deferred_deletion=true',
'dm.use_deferred_removal=true'
]
action [:create, :start]
end
end
|
class RenameBankToBankId < ActiveRecord::Migration[5.0]
def change
remove_column :cards, :bank, :integer, null: false
add_column :cards, :bank_id, :integer, null: false
add_index :cards, :bank_id
end
end
|
FactoryGirl.define do
factory :coupon do
code { ('a'..'z').to_a.sample(5).join }
status { [true,false].sample }
user { create :user, :seller }
discount { Random.rand(1..100) }
end
end |
class TransactionsController < ApplicationController
load_and_authorize_resource
skip_before_action :verify_authenticity_token, only: [:change_status]
before_action :set_transaction, only: [:destroy]
def index
@transactions = current_user.admin? ? Transaction.all : current_user.transactions
@transactions = @transactions.paginate(page: params[:page], per_page: Worker::PER_PAGE)
end
def withdraw
@transaction = Transaction.build_new(transaction_params, current_user)
@message = @transaction.save! ? "Withdrawal Request Sent Successfully." : "Error occurred while placing Withdrawal Request.\nPlease Try again later!"
respond_to do |format|
format.js { render 'withdraw.js.erb' }
end
end
def destroy
@transaction.destroy
respond_to do |format|
format.html { redirect_to transactions_url, alert: 'Transaction was successfully destroyed.' }
format.json { head :no_content }
end
end
def change_status
@user = User.find(params[:user_id])
@transaction = Transaction.find(params[:transaction_id])
if @transaction.pending?
@transaction.update_attributes(status: params[:status])
if params[:status] == 'Approved'
@user.update_net_income_for_currency(@transaction.amount, @transaction.currency.code)
@user.save!
end
end
respond_to :js
end
private
def transaction_params
params.permit(:currency, :amount)
end
def set_transaction
@transaction = Transaction.find(params[:id])
end
end
|
# obsolete, only here for reference
=begin
module RestoreAgent
class Snapper
require 'restore_agent/object_db'
include DRbUndumped
attr_reader :object_db
def initialize(agent)
@agent = agent
@object_db = ObjectDB.new("/tmp/myobjects.db")
puts "snapper initialized"
end
# mark objects for scanning.
def prepare_objects(objects)
@objects = objects
return "OK"
end
def execute
@objects.each_pair do |k,v|
puts "Scanning #{k}"
if o = @agent.root.find_object(k)
begin
# grab a reference to the receiver of this object on the master
modified = o.scan(self, v[:included], v[:receiver])
rescue => e
puts e.to_s
puts e.backtrace.join("\n")
end
else
puts "#{k} was not found!"
end
end
@object_db.close
end
def included?(object)
if h = @objects[object.path]
return h[:included]
end
return false
end
def excluded?(object)
if h = @objects[object.path]
return !h[:included]
end
return false
end
end
end
=end |
class Ability
include CanCan::Ability
def initialize(user)
if user.admin?
can :manage, :all
else
can :read, Ticket do |ticket|
ticket.nil? || ticket.published? || ticket.user == user
# deleted, archived?
end
can :read, Page do |page|
page.nil? || page.published?
# index, created by me?
end
end
end
end |
class ReviewSerializer < ActiveModel::Serializer
attributes :reviewer, :rating, :comment
end
|
class NewsHeadlines::Article
attr_accessor :title, :author, :news_source, :description, :url, :published_at
@@all = []
def initialize(title = nil, author = nil, description = nil, url = nil, published_at = "unavailable")
@title = title
@author = author
@description = description
@url = url
@published_at = published_at
@@all << self
end
def self.new_from_json(article)
self.new(
article["title"],
article["author"],
article["description"],
article["url"],
article["publishedAt"]
)
end
def self.find_article(article_title)
self.all.find {|article| article.title == article_title}
end
def add_news_source(news_source)
@news_source = news_source
end
def self.all
@@all
end
end
|
class Teacher < ApplicationRecord
validates :surname, presence: true,
length: { minumum: 2, maximum: 30 }
end
|
# Write a #french_ssn_info method extracting infos from French SSN (Social Security Number) using RegExp.
# Regular Expressions are useful in two main contexts: data validation and data extraction.
# In this challenge, we are going to use RegExps to extract data from a French social security number.
# check if there is a match with our pattern
# if we have the match_data we need to check:
# - if it's 1, return man, else return woman
# - if it's over 19, return 19.., else return 20..
# - get the month of birth based on the number
# - get the department of birth, based on the YAML file
# - check if the ssn_key is valid, by checking the key
# method should return the string with all this information
# Valid French social security numbers have the following pattern:
# 1 84 12 76 451089 46
# Gender (1 == man, 2 == woman)
# Year of birth (84)
# Month of birth (12)
# Department of birth (76, basically included between 01 and 99)
# 6 random digits (451 089)
# A 2 digits key (46, equal to the remainder of the division of (97 - ssn_without_key) by 97.)
# The method must return the following strings:
# french_ssn_info("1 84 12 76 451 089 46")
# => "a man, born in December, 1984 in Seine-Maritime."
# OR
# french_ssn_info("123")
# => "The number is invalid"
require "date"
require "yaml"
PATTERN = /^(?<gender>[1-2])\s?(?<year>\d{2})\s?(?<month>0[1-9]|1[0-2])\s?(?<department>0[1-9]|[1-9][0-9])\s?\d{3}\s?\d{3}\s?(?<key>\d{2})$/
def french_ssn_info(ssn)
match = ssn.match(PATTERN)
#<MatchData "1 84 12 76 451 089 46" gender:"1" year:"84" month:"12" department:"76" key:"46">
if match && valid_key?(ssn, match[:key])
gender = match[:gender].to_i == 1 ? "man" : "woman"
year = match[:year].to_i >= 20 ? "19#{match[:year].to_i}" : "20#{match[:year].to_i}"
month = Date::MONTHNAMES[match[:month].to_i]
department = YAML.load_file("data/french_departments.yml")[match[:department]]
return "a #{gender}, born in #{month}, #{year} in #{department}."
else
return "The number is invalid"
end
end
def valid_key?(ssn, key)
ssn_without_key = ssn.delete(" ")[0..-3].to_i # including the -3 position - from 0 to -3
# ssn_without_key = ssn.gsub(/\s+/, "")[0...-2]
(97 - ssn_without_key) % 97 == key.to_i
end
p french_ssn_info("1 84 12 76 451 089 46")
# def get_gender(gender)
# if gender == 1
# return "man"
# else
# return "woman"
# end
# end
# if match && valid_key?(ssn, match[:key])
# gender = get_gender(match[:gender].to_i)
# year = get_year(match[:year])
# month = get_month(match[:month])
# department = get_department(match[:department])
# return "a #{gender}, born in #{month}, #{year} in #{department}."
# else
# return "The number is invalid"
# end
# end
# def get_year(year)
# if year.to_i > 19
# return "19#{year}"
# else
# return "20#{year}"
# end
# end
# def get_month(month)
# months = Date::MONTHNAMES
# months[month.to_i]
# end
# def get_department(department)
# departments = YAML.load_file("data/french_departments.yml")
# departments[department]
# end
|
# == Schema Information
#
# Table name: contributions
#
# id :integer not null, primary key
# amount :float
# project_id :integer
# user_id :integer
# payment_status :string(255) default("UNPROCESSED")
# anonymous :boolean default(FALSE)
# created_at :datetime
# updated_at :datetime
#
class Contribution < ActiveRecord::Base
include Rails.application.routes.url_helpers
belongs_to :project
belongs_to :user
has_many :payment_notifications, dependent: :destroy
validates :amount, numericality: { greater_than: 0 }, presence: true
validates :user_id, presence: true
validates :project_id, presence: true
def paypal_url
@preapproval = PAYPAL_API.build_preapproval(preapproval_params)
# Make API call & get response
@preapproval_response = PAYPAL_API.preapproval(@preapproval)
logger.info "\r\n@preapproval_response = #{@preapproval_response.inspect}"
# Access Response
if @preapproval_response.success?
@preapproval_response.preapprovalKey
else
logger.info "\r\n@preapproval_response.error = #{@preapproval_response.error.map(&:message)}"
end
"https://www.sandbox.paypal.com/webscr?cmd=_ap-preapproval&preapprovalkey=#{@preapproval_response.preapprovalKey}"
end
def preapproval_params
host = Rails.env.production? ? 'impulsideas.com' : '0.0.0.0:3000'
{
:cancelUrl => new_project_contribution_url(self.project, host: host),
:returnUrl => project_url(self.project, host: host),
:startingDate => Time.now,
:endingDate => 180.days.from_now.localtime,
:currencyCode => "USD",
:memo => "Aporte al proyecto #{self.project.title}",
:ipnNotificationUrl => ipn_notifications_url(self.id, host: host),
:maxAmountPerPayment => self.amount,
:maxTotalAmountOfAllPayments => self.amount,
:maxNumberOfPayments => 1,
:maxNumberOfPaymentsPerPeriod => 1,
:pinType => "NOT_REQUIRED",
:feesPayer => "PRIMARYRECEIVER",
:displayMaxTotalAmount => false
}
end
end
|
# frozen_string_literal: true
module InterventionSteps
step 'I create an intervention' do
@intervention = Fabricate(:intervention)
create_intervention
end
step 'I create an intervention with :num file(s)' do |num_files|
@intervention = Fabricate(:intervention)
create_intervention(num_files.to_i)
@intervention = Intervention.last
end
step 'the correct fields should be saved' do
intervention = Intervention.last
expect(intervention.title).to eq(@intervention.title)
expect(intervention.intro).to eq(@intervention.intro)
expect(intervention.headline_points).to eq(@intervention.headline_points)
expect(intervention.how).to eq(@intervention.how)
expect(intervention.studies).to eq(@intervention.studies)
expect(intervention.costs_benefits).to eq(@intervention.costs_benefits)
intervention.outcomes.each_with_index do |outcome, i|
expect(outcome.title).to eq(@intervention.outcomes[i].title)
expect(outcome.effect).to eq(@intervention.outcomes[i].effect)
expect(outcome.evidence).to eq(@intervention.outcomes[i].evidence)
end
expect(intervention.implementation.intro).to eq(@intervention.implementation.intro)
expect(intervention.implementation.deliverer).to eq(@intervention.implementation.deliverer)
expect(intervention.implementation.training_requirements).to eq(@intervention.implementation.training_requirements)
expect(intervention.implementation.fidelity).to eq(@intervention.implementation.fidelity)
expect(intervention.implementation.support).to eq(@intervention.implementation.support)
intervention.links.each_with_index do |link, i|
expect(link.title).to eq(@intervention.links[i].title)
expect(link.url).to eq(@intervention.links[i].url)
end
intervention.contacts.each_with_index do |contact, i|
expect(contact.title).to eq(@intervention.contacts[i].title)
expect(contact.url).to eq(@intervention.contacts[i].url)
end
end
step 'the intervention should have the correct tags' do
expect(@intervention.tags.count).to eq(@tags.count)
@tags.each do |t|
expect(@intervention.tags.find_by(name: t)).to_not be_nil
end
end
step 'the intervention should have :num file(s) attached' do |num_files|
intervention = Intervention.last
expect(intervention.files.count).to eq(num_files.to_i)
end
def create_intervention(num_files = 0)
complete_field :title
complete_field :summary
complete_markdown_field :intro
complete_array_field :headline_points
complete_markdown_field :what_is_it
complete_markdown_field :how
complete_outcomes
complete_markdown_field :outcome_notes
complete_markdown_field :who_does_it_work_for
complete_markdown_field :when_where_how
complete_markdown_field :costs_benefits
complete_markdown_field :studies
complete_markdown_field :costs_benefits
complete_implementation
attach_file('intervention_files', generate_files(num_files)) if num_files > 0
complete_contacts
complete_links
complete_tags
first('input[name="commit"]').click
end
def complete_markdown_field(field_name)
within ".markdown-field-wrapper__intervention__#{field_name}" do
value = @intervention.send(field_name)
element = find('.CodeMirror', visible: false)
execute_script("arguments[0].CodeMirror.getDoc().setValue('#{value}')", element)
end
end
def complete_field(field_name)
fill_in "intervention_#{field_name}", with: @intervention.send(field_name)
end
def complete_outcome_field(field_name, outcome)
fill_in I18n.t("helpers.label.intervention[outcomes_attributes][new_outcomes].#{field_name}"), with: outcome.send(field_name)
end
def complete_outcome_select_field(field_name, outcome)
level = I18n.t("helpers.options.outcome.#{field_name}.#{outcome.send(field_name)}")
select level, from: I18n.t("helpers.label.intervention[outcomes_attributes][new_outcomes].#{field_name}")
end
def complete_link_field(field_name, link)
fill_in I18n.t("helpers.label.intervention[links_attributes][new_links].#{field_name}"), with: link.send(field_name)
end
def complete_contact_field(field_name, contact)
fill_in I18n.t("helpers.label.intervention[contacts_attributes][new_contacts].#{field_name}"), with: contact.send(field_name)
end
def complete_array_field(field_name)
array = @intervention.send(field_name)
array.each_with_index do |item, i|
all(:css, "textarea[name='intervention[#{field_name}][]']").last.set(item)
find(:css, "a#add_#{field_name}").click unless (i + 1) == array.length
end
end
def complete_implementation_field(field_name)
within ".markdown-field-wrapper__implementation__#{field_name}" do
value = @intervention.implementation.send(field_name)
element = find('.CodeMirror', visible: false)
execute_script("arguments[0].CodeMirror.getDoc().setValue('#{value}')", element)
end
end
def complete_implementation_markdown_field(field_name)
within ".markdown-field-wrapper__implementation__#{field_name}" do
value = @intervention.implementation.send(field_name)
element = find('.CodeMirror', visible: false)
execute_script("arguments[0].CodeMirror.getDoc().setValue('#{value}')", element)
end
end
def complete_subject_field(field_name, subject, type)
fill_in I18n.t("helpers.label.intervention[#{type}_subjects_attributes][new_#{type}_subjects].#{field_name}"), with: subject.send(field_name)
end
def complete_outcomes
@intervention.outcomes.each do |outcome|
within 'fieldset.outcomes' do
click_on I18n.t('administrate.fields.nested_has_many.add', resource: 'Outcome')
within :xpath, '(//div[@class="nested-fields"])[last()]' do
complete_outcome_field :title, outcome
complete_outcome_select_field :effect, outcome
complete_outcome_select_field :evidence, outcome
end
end
end
end
def complete_links
@intervention.links.each do |link|
within '.field-unit--nested.links' do
click_on I18n.t('administrate.fields.nested_has_many.add', resource: 'Link')
within :xpath, '(//div[@class="nested-fields"])[last()]' do
complete_link_field :title, link
complete_link_field :url, link
end
end
end
end
def complete_contacts
@intervention.contacts.each do |contact|
within '.field-unit--nested.contacts' do
click_on I18n.t('administrate.fields.nested_has_many.add', resource: 'Contact')
within :xpath, '(//div[@class="nested-fields"])[last()]' do
complete_contact_field :title, contact
complete_contact_field :url, contact
end
end
end
end
def complete_implementation
complete_implementation_markdown_field :intro
complete_implementation_field :deliverer
complete_implementation_field :training_requirements
complete_implementation_field :fidelity
complete_implementation_field :support
end
end
RSpec.configure { |c| c.include InterventionSteps }
|
class EmployeesController < ApplicationController
before_filter :signed_in_employee, only: [:index, :edit, :update]
before_filter :correct_employee, only: [:edit, :update]
before_filter :admin_employee, only: :destroy
# GET /employees
# GET /employees.json
def index
@employees = Employee.paginate(page: params[:page])
@responses = Response.where('employee_id' => params[:id])
respond_to do |format|
format.html # index.html.erb
format.json { render json: @employees }
end
end
# GET /employees/1
# GET /employees/1.json
def show
@employee = Employee.find(params[:id])
@skills = Skill.all
@selections = Selection.where('employee_id' => params[:id])
@responses = Response.where('employee_id' => params[:id])
@request_ids = @selections.map{|selection| selection.request_id}
@my_projects = @request_ids.map{|request_id| Request.find(request_id)}
respond_to do |format|
format.html # show.html.erb
format.json { render json: @employee }
end
end
# GET /employees/new
# GET /employees/new.json
def new
@employee = Employee.new
@locations = Location.all
end
# GET /employees/1/edit
def edit
@employee = Employee.find(params[:id])
@locations = Location.all
end
# POST /employees
# POST /employees.json
def create
@employee = Employee.new(params[:employee])
@locations = Location.all
respond_to do |format|
if @employee.save
flash[:success] = "Welcome to OneTeam! Profile was successfully created."
sign_in @employee
format.html { redirect_to @employee}
format.json { render json: @employee, status: :created, location: @employee }
else
format.html { render action: "new" }
format.json { render json: @employee.errors, status: :unprocessable_entity }
end
end
end
# PUT /employees/1
# PUT /employees/1.json
def update
@employee = Employee.find(params[:id])
@locations = Location.all
respond_to do |format|
if @employee.update_attributes(params[:employee])
flash[:success] = "Profile updated."
sign_in @employee
format.html { redirect_to requests_path, :anchor => "tabs-2" }
format.json { head :no_content }
else
flash[:failed] = "Failed to update."
format.html { render action: "edit" }
format.json { render json: @employee.errors, status: :unprocessable_entity }
end
end
end
# DELETE /employees/1
# DELETE /employees/1.json
def destroy
Employee.find(params[:id]).destroy
flash[:success] = "Employee deleted."
respond_to do |format|
format.html { redirect_to employees_url }
format.json { head :no_content }
end
end
private
def signed_in_employee
store_location
redirect_to signin_url, notice: "Please sign in." unless signed_in?
end
def correct_employee
@employee = Employee.find(params[:id])
redirect_to(root_path) unless current_employee?(@employee)
end
def admin_employee
redirect_to(root_path) unless current_employee.admin?
end
end
|
require "eventmachine"
require "bite_the_dust/version"
BTD = BiteTheDust
module BiteTheDust
def self.future?(time)
Time.now < time
end
def self.countdown(sec, &block)
EM.run do
EM.add_timer(sec) do
EM.stop_event_loop
return block.call
end
end
end
class BiteTheDust
def initialize(time)
@now = Time.now
@time = time
end
def future?
@now < @time
end
def set_timer(&block)
if future? then
begin
num_of_seconds = @time - Time.now
EM.run do
EM.add_timer(num_of_seconds.to_i) do
EM.stop_event_loop
return block.call
end
end
rescue RangeError
raise RangeError, "Time too far"
end
else
return block.call
end
end
end
end
|
require "spec_helper"
describe StudyClient do
it "has a version number" do
expect(StudyClient::VERSION).not_to be nil
end
it "has a cost_code" do
expect(StudyClient::Node.new).to respond_to :cost_code
end
it "is connected to the json api" do
url='http://localhost:9999/api/v1/'
id="123"
StudyClient::Base.site=url
stub_request(:get, url+"nodes/"+id).
with(headers: {'Accept'=>'application/vnd.api+json', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type'=>'application/vnd.api+json', 'User-Agent'=>'Faraday v0.11.0'}).
to_return(status: 200, body: "", headers: {})
stub_request(:get, url+'/nodes')
.to_return(status: 200, body: {id: id}.to_json, headers: {})
expect(StudyClient::Node.find(id)).not_to be nil
end
end
|
require 'rails_helper'
RSpec.describe "pages/home.html.erb", type: :view do
it "renders the game main page" do
render
assert_select "h1", :presence => true
assert_select "h1", :text => "HEART OF BOLD".to_s, :count => 1
assert_select "#gameContainer", :presence => true
end
end
|
require 'spec_helper'
module YahooGeminiClient
RSpec.describe GenerateMemberURI, ".execute" do
let(:base_uri) { "http://base.com" }
it "sets the query to be the given IDs" do
expect(described_class.execute(base_uri, [4, 5])).
to eq "http://base.com?id=4&id=5"
expect(described_class.execute(base_uri, 5)).
to eq "http://base.com?id=5"
end
end
end
|
# frozen_string_literal: true
require 'spec_helper'
describe 'running ExUnitRunAll command' do
it "passing test" do # {{{
content = <<~EOF
|| **CWD**%%DIRNAME%%
|| .
|| 1 test, 0 failures
EOF
expect(<<~EOF).to be_test_output("ExUnitRunAll", content)
defmodule A do
use ExUnit.Case
test "truth" do
assert 1 == 1
end
end
EOF
end # }}}
it "compilation error(undefined function)" do # {{{
content = <<~EOF
|| **CWD**%%DIRNAME%%
test/fixture_test.exs|4 error| undefined function call/0
EOF
expect(<<~EOF).to be_test_output("ExUnitRunAll", content)
defmodule A do
use ExUnit.Case
test "truth" do
call()
end
end
EOF
end # }}}
it "compilation error(missing do)" do # {{{
content = <<~EOF
|| **CWD**%%DIRNAME%%
test/fixture_test.exs|6 error| unexpected token: end
EOF
expect(<<~EOF).to be_test_output("ExUnitRunAll", content)
defmodule A do
use ExUnit.Case
test "truth"
:ok
end
end
EOF
end # }}}
it "compilation error(missing end)" do # {{{
content = <<~EOF
|| **CWD**%%DIRNAME%%
test/fixture_test.exs|8 error| missing terminator: end (for "do" starting at line 1)
EOF
expect(<<~EOF).to be_test_output("ExUnitRunAll", content)
defmodule A do
use ExUnit.Case
test "truth" do
if true do
:ok
end
end
EOF
end # }}}
it "failing assert" do # {{{
content = <<~EOF
|| **CWD**%%DIRNAME%%
test/fixture_test.exs|3 error| test truth (A)
|| Assertion with == failed
|| code: 2 == 1
|| lhs: 2
|| rhs: 1
test/fixture_test.exs|4 error| (test)
|| 1 test, 1 failure
EOF
source = <<~EOF
defmodule A do
use ExUnit.Case
test "truth" do
assert 2 == 1
end
end
EOF
expect(source).to be_test_output("ExUnitRunAll", content)
mix_test_output = <<~EOF
Generated test app
1) test truth (A)
test/fixture_test.exs:3
Assertion with == failed
code: 2 == 1
lhs: 2
rhs: 1
stacktrace:
test/fixture_test.exs:4: (test)
Finished in 0.06 seconds
1 test, 1 failure
Randomized with seed 948545
EOF
internal_content = <<~EOF
[{'lnum': 3, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': 'test truth (A)'}, {'lnum': 4, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': '(test)'}]
EOF
expect(mix_test_output).to be_matching_error("exunit_run", internal_content)
end # }}}
it "failing function call" do # {{{
content = <<~EOF
|| **CWD**%%DIRNAME%%
test/fixture_test.exs|3 error| test truth (A)
test/fixture_test.exs|8 error| A.test_me/1 ** (MatchError) no match of right hand side value: 123
test/fixture_test.exs|4 error| (test)
|| 1 test, 1 failure
EOF
expect(<<~EOF).to be_test_output("ExUnitRunAll", content)
defmodule A do
use ExUnit.Case
test "truth" do
test_me 123
end
defp test_me(arg) do
{_, _} = arg
end
end
EOF
mix_test_output = <<~EOF
Generated test app
1) test truth (A)
test/fixture_test.exs:3
** (MatchError) no match of right hand side value: 123
stacktrace:
test/fixture_test.exs:8: A.test_me/1
test/fixture_test.exs:4: (test)
Finished in 0.1 seconds
1 test, 1 failure
Randomized with seed 78859
EOF
internal_content = <<~EOF
[{'lnum': 3, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': 'test truth (A)'}, {'lnum': 8, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': 'A.test_me/1 ** (MatchError) no match of right hand side value: 123'}, {'lnum': 4, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': '(test)'}]
EOF
expect(mix_test_output).to be_matching_error("exunit_run", internal_content)
end # }}}
it "absent function call" do # {{{
content = <<~EOF
|| **CWD**%%DIRNAME%%
test/fixture_test.exs|3 error| test truth (A)
|| A.test_other(123)
test/fixture_test.exs|4 error| (test) ** (UndefinedFunctionError) function A.test_other/1 is undefined or private
|| 1 test, 1 failure
EOF
expect(<<~EOF).to be_test_output("ExUnitRunAll", content)
defmodule A do
use ExUnit.Case
test "truth" do
A.test_other 123
end
end
EOF
mix_test_output = <<~EOF
Generated test app
1) test truth (A)
test/fixture_test.exs:3
** (UndefinedFunctionError) function A.test_other/1 is undefined or private
stacktrace:
A.test_other(123)
test/fixture_test.exs:4: (test)
Finished in 0.06 seconds
1 test, 1 failure
Randomized with seed 768998
EOF
internal_content = <<~EOF
[{'lnum': 3, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': 'test truth (A)'}, {'lnum': 4, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': '(test) ** (UndefinedFunctionError) function A.test_other/1 is undefined or private'}]
EOF
expect(mix_test_output).to be_matching_error("exunit_run", internal_content)
end # }}}
it "ignore warnings" do # {{{
content = <<~EOF
|| **CWD**%%DIRNAME%%
test/fixture_test.exs|3 error| test truth (A)
|| A.test_other(123)
test/fixture_test.exs|4 error| (test) ** (UndefinedFunctionError) function A.test_other/1 is undefined or private
|| 1 test, 1 failure
EOF
expect(<<~EOF).to be_test_output("ExUnitRunAll", content)
defmodule A do
use ExUnit.Case
test "truth" do
A.test_other 123
end
defp test_warning do
:ok
end
end
EOF
mix_test_output = <<~EOF
Generated test app
warning: function test_warning/0 is unused
test/fixture_test.exs:7
1) test truth (A)
test/fixture_test.exs:3
** (UndefinedFunctionError) function A.test_other/1 is undefined or private
stacktrace:
A.test_other(123)
test/fixture_test.exs:4: (test)
Finished in 0.09 seconds
1 test, 1 failure
Randomized with seed 397976
EOF
internal_content = <<~EOF
[{'lnum': 3, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': 'test truth (A)'}, {'lnum': 4, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': '(test) ** (UndefinedFunctionError) function A.test_other/1 is undefined or private'}]
EOF
expect(mix_test_output).to be_matching_error("exunit_run", internal_content)
end # }}}
it "parse GenServer clause undefined" do # {{{
content = <<~EOF
|| **CWD**%%DIRNAME%%
test/fixture_test.exs|3 error| test truth (A)
test/fixture_test.exs|21 error| B.handle_call(:nonexistent, {#PID, #Reference}, :state) ** (FunctionClauseError) no function clause matching in B.handle_call/3
|| 1 test, 1 failure
EOF
expect(<<~EOF).to be_test_output("ExUnitRunAll", content)
defmodule A do
use ExUnit.Case
test "truth" do
{:ok, pid} = B.start_link()
GenServer.call(pid, :nonexistent)
:ok
end
end
defmodule B do
use GenServer
def start_link() do
GenServer.start_link(__MODULE__, [], [])
end
def init(_) do
{:ok, :state}
end
def handle_call(:never_called, _, state) do
{:reply, :ok, state}
end
end
EOF
mix_test_output = <<~EOF
Generated test app
=ERROR REPORT==== 27-Dec-2016::01:01:48 ===
** Generic server <0.130.0> terminating
** Last message in was nonexistent
** When Server state == state
** Reason for termination ==
** {function_clause,[{'Elixir.B',handle_call,
[nonexistent,
{<0.129.0>,#Ref<0.0.1.27>},
state],
[{file,"test/fixture_test.exs"},{line,21}]},
{gen_server,try_handle_call,4,
[{file,"gen_server.erl"},{line,615}]},
{gen_server,handle_msg,5,
[{file,"gen_server.erl"},{line,647}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,247}]}]}
1) test truth (A)
test/fixture_test.exs:3
** (EXIT from #PID<0.129.0>) an exception was raised:
** (FunctionClauseError) no function clause matching in B.handle_call/3
test/fixture_test.exs:21: B.handle_call(:nonexistent, {#PID<0.129.0>, #Reference<0.0.1.27>}, :state)
(stdlib) gen_server.erl:615: :gen_server.try_handle_call/4
(stdlib) gen_server.erl:647: :gen_server.handle_msg/5
(stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Finished in 0.1 seconds
1 test, 1 failure
Randomized with seed 442759
EOF
internal_content = <<~EOF
[{'lnum': 3, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': 'test truth (A)'}, {'lnum': 21, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': 'B.handle_call(:nonexistent, {#PID<0.129.0>, #Reference<0.0.1.27>}, :state) ** (FunctionClauseError) no function clause matching in B.handle_call/3'}]
EOF
expect(mix_test_output).to be_matching_error("exunit_run", internal_content)
end # }}}
it "parse crash inside GenServer clause" do # {{{
content = <<~EOF
|| **CWD**%%DIRNAME%%
test/fixture_test.exs|3 error| test truth (A)
test/fixture_test.exs|22 error| B.handle_call/3 ** (MatchError) no match of right hand side value: :state
|| 1 test, 1 failure
EOF
expect(<<~EOF).to be_test_output("ExUnitRunAll", content)
defmodule A do
use ExUnit.Case
test "truth" do
{:ok, pid} = B.start_link()
GenServer.call(pid, :crashes)
:ok
end
end
defmodule B do
use GenServer
def start_link() do
GenServer.start_link(__MODULE__, [], [])
end
def init(_) do
{:ok, :state}
end
def handle_call(:crashes, _, state) do
{_, _} = state
{:reply, :ok, state}
end
end
EOF
mix_test_output = <<~EOF
Generated test app
=ERROR REPORT==== 27-Dec-2016::01:22:41 ===
** Generic server <0.130.0> terminating
** Last message in was crashes
** When Server state == state
** Reason for termination ==
** {{badmatch,state},
[{'Elixir.B',handle_call,3,[{file,"test/fixture_test.exs"},{line,22}]},
{gen_server,try_handle_call,4,[{file,"gen_server.erl"},{line,615}]},
{gen_server,handle_msg,5,[{file,"gen_server.erl"},{line,647}]},
{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]}
1) test truth (A)
test/fixture_test.exs:3
** (EXIT from #PID<0.129.0>) an exception was raised:
** (MatchError) no match of right hand side value: :state
test/fixture_test.exs:22: B.handle_call/3
(stdlib) gen_server.erl:615: :gen_server.try_handle_call/4
(stdlib) gen_server.erl:647: :gen_server.handle_msg/5
(stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Finished in 0.1 seconds
1 test, 1 failure
Randomized with seed 816037
EOF
internal_content = <<~EOF
[{'lnum': 3, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': 'test truth (A)'}, {'lnum': 22, 'col': 0, 'valid': 1, 'vcol': 0, 'nr': -1, 'type': 'E', 'text': 'B.handle_call/3 ** (MatchError) no match of right hand side value: :state'}]
EOF
expect(mix_test_output).to be_matching_error("exunit_run", internal_content)
end # }}}
end
# vim: foldmethod=marker
|
class AddColNameToBuilding < ActiveRecord::Migration
def change
add_column :buildings, :name, :string
add_column :buildings, :rank, :integer
end
end
|
class SessionsController < ApplicationController
skip_before_filter :authorize, :only => [:new, :authenticate]
before_filter :restrict_if_logged_in, :only => :new
def new
@title = "Login"
@member = Member.new
end
def delete
session[:member_id] = nil
cookies.delete :remember_me_id if cookies[:remember_me_id]
cookies.delete :remember_me_code if cookies[:remember_me_code]
flash_redirect("message","Logged out", login_path)
end
def authenticate
if request.post? and @member = Member.authenticate(params[:member][:email],params[:member][:password], params[:remember_me])
session[:member_id] = @member.id
if params[:member][:remember_me] == "1"
cookies[:remember_me_id] = { :value => @member.id.to_s, :expires => 14.days.from_now }
cookies[:remember_me_code] = { :value => @member.remember_me_token,
:expires => 14.days.from_now }
end
#flash[:message] = "Welcome #{member.first_name}"
redirect_to members_path
else
flash_render("notice", "Invalid login credentials", "new")
end
end
end
|
class ParkingLot < ActiveRecord::Base
belongs_to :parking_type
attr_accessible :user_id, :parking_type_id, :latitude, :longitude
validates :user_id, :presence => true
validates :parking_type_id, :presence => {:message => "Tienes que seleccionar el tipo de plaza"}
validates :latitude, :presence => true
validates :longitude, :presence => true
end
|
include Warden::Test::Helpers
=begin NOT USED
Given(/^I set up some demo data$/) do
#for now, one team, one Objective.
t = Team.create!(name: "The Protons")
g = t.goals<< Goal.create!(team: t, name: "Be massively awesome")
end
=end
When(/^I visit the (?:key result|objective|goal) called "([^"]*)"$/) do |name|
visit goal_path(Goal.find_by(name: name))
end
When(/^I visit the team called "([^"]*)"$/) do |name|
visit team_path(Team.find_by(name: name))
end
Given(/^the objective "([^"]*)" has a key result "([^"]*)"$/) do |obj_name, key_result_name|
g = Goal.find_by(name: obj_name)
g.key_results << Goal.create!(name: key_result_name, team: g.team, end_date: Date.today.end_of_financial_quarter)
end
Given(/^the (?:key result|objective|goal) called "([^"]*)" is linked to the objective "([^"]*)"$/) do |source_name, target_name|
source = Goal.find_by(name: source_name) or raise "Couldn't find goal named '#{source_name}'"
target = Goal.find_by(name: target_name) or raise "Couldn't find goal named '#{target_name}'"
source.linked_goals << target
end
#http://vedanova.com/rails/cucumber/2013/08/02/run-rake-tasks-cucumber-rspec.html
def execute_rake(file, task)
require 'rake'
rake = Rake::Application.new
Rake.application = rake
Rake::Task.define_task(:environment)
load "#{Rails.root}/lib/tasks/#{file}"
rake[task].invoke
end
|
module Friendship
class Friend
attr_accessor :name, :sex, :age
def initialize(name, sex, age)
@name = name
@sex = sex
@age = age
end
def male?
sex == :male
end
def female?
sex == :female
end
def over_eighteen?
age > 18
end
def long_name?
name.length > 10
end
end
class Database
include Enumerable
def initialize
@friends = []
end
def add_friend(name, sex, age)
@friends << Friendship::Friend.new(name, sex, age)
end
def each(&block)
@friends.each(&block)
end
def have_any_friends?
!@friends.count.zero?
end
def find(filter)
return @friends.select { |e| e.name == filter[:name] } if filter[:name]
return @friends.select { |e| e.sex == filter[:sex] } if filter[:sex]
@friends.select(&filter[:filter])
end
def unfriend(filter)
@friends.reject! { |e| e.name == filter[:name] } if filter[:name]
@friends.reject! { |e| e.sex == filter[:sex] } if filter[:sex]
@friends.reject!(&filter[:filter]) if filter[:filter]
end
end
end
|
require 'connection_pool'
require 'fastimage'
require 'thread'
require 'faraday'
require 'faraday_middleware'
require 'base64'
module ProgImage
class Client
IMAGES_ENDPOINT = '/images'.freeze
CONTENT_TYPE = 'application/json'.freeze
def initialize(pool_size: 3, timeout: 5)
self.pool = ConnectionPool.new(size: pool_size, timeout: timeout) do
Faraday.new(url: api_endpoint)
end
end
def upload(urls)
metadata = urls.map do |url|
ProgImage::FileUpload.new(url)
end
metadata.map(&:join)
response = pool.with do |client|
client.post do |request|
request.url IMAGES_ENDPOINT
request.headers['Content-Type'] = CONTENT_TYPE
request.body = JSON.generate(metadata.map(&:attributes))
end
end
handle_response response
end
private
attr_accessor :pool
def api_endpoint
"https://example.com"
end
def queue
@queue ||= Queue.new
end
def handle_response(response)
return JSON.parse(response) if response.success?
end
end
end
|
class PagesController < ApplicationController
expose :page, -> { Page.friendly.find(params[:id]).decorate }
def show; end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.