text stringlengths 10 2.61M |
|---|
# Контроллер страницы подтверждения покупки
class Content::PreorderDoneController < Content::BaseController
layout 'content'
before_action :set_preorder
def show
end
private
def set_preorder
token = cookies['_preorder_done']
@order = Order.find_by_token token
end
end
|
class AddColumnsToCode < ActiveRecord::Migration
def change
add_column :codes, :name, :string
add_column :codes, :difficulty, :string
add_column :codes, :language, :string
add_column :codes, :link, :string
add_column :codes, :github_link, :string
end
end
|
class RenameCategoryIdToGoodCategoryId < ActiveRecord::Migration
def change
rename_column :category_goods, :category_id, :good_category_id
end
end
|
require 'fileutils'
Before do
@terminal = Terminal.new
end
class Terminal
attr_reader :output, :status
attr_accessor :environment_variables, :invoke_heroku_rake_tasks_locally
def initialize
@cwd = FileUtils.pwd
@output = ""
@status = 0
@logger = Logger.new(File.join(TEMP_DIR, 'terminal.log'))
@invoke_heroku_rake_tasks_locally = false
@environment_variables = {
"GEM_HOME" => LOCAL_GEM_ROOT,
"GEM_PATH" => "#{LOCAL_GEM_ROOT}:#{BUILT_GEM_ROOT}",
"PATH" => "#{gem_bin_path}:#{ENV['PATH']}"
}
end
def cd(directory)
@cwd = directory
end
def run(command)
command = optionally_invoke_heroku_rake_tasks_locally(command)
output << "#{command}\n"
FileUtils.cd(@cwd) do
cmdline = "#{environment_settings} #{command} 2>&1"
logger.debug(cmdline)
result = `#{cmdline}`
logger.debug(result)
output << result
end
@status = $?
end
def optionally_invoke_heroku_rake_tasks_locally(command)
if invoke_heroku_rake_tasks_locally
command.sub(/^heroku /, '')
else
command
end
end
def echo(string)
logger.debug(string)
end
def build_and_install_gem(gemspec)
pkg_dir = File.join(TEMP_DIR, 'pkg')
FileUtils.mkdir_p(pkg_dir)
output = `gem build #{gemspec} 2>&1`
gem_file = Dir.glob("*.gem").first
unless gem_file
raise "Gem didn't build:\n#{output}"
end
target = File.join(pkg_dir, gem_file)
FileUtils.mv(gem_file, target)
install_gem_to(BUILT_GEM_ROOT, target)
end
def install_gem(gem)
install_gem_to(LOCAL_GEM_ROOT, gem)
end
def uninstall_gem(gem)
`gem uninstall -i #{BUILT_GEM_ROOT} #{gem}`
end
private
def install_gem_to(root, gem)
`gem install -i #{root} --no-ri --no-rdoc #{gem}`
end
def environment_settings
@environment_variables.map { |key, value| "#{key}=#{value}" }.join(' ')
end
def gem_bin_path
File.join(LOCAL_GEM_ROOT, "bin")
end
attr_reader :logger
end
|
class AddCountToSongs < ActiveRecord::Migration
def change
add_column :songs, :stations_count, :integer, :default => 0
end
end
|
shared_examples_for 'oauth2_controller' do
describe 'using create_from' do
before(:each) do
stub_all_oauth2_requests!
User.sorcery_adapter.delete_all
Authentication.sorcery_adapter.delete_all
end
it 'creates a new user' do
sorcery_model_property_set(:authentications_class, Authentication)
sorcery_controller_external_property_set(:facebook, :user_info_mapping, { username: 'name' })
expect { get :test_create_from_provider, provider: 'facebook' }.to change { User.count }.by 1
expect(User.first.username).to eq 'Noam Ben Ari'
end
it 'supports nested attributes' do
sorcery_model_property_set(:authentications_class, Authentication)
sorcery_controller_external_property_set(:facebook, :user_info_mapping, { username: 'hometown/name' })
expect { get :test_create_from_provider, provider: 'facebook' }.to change { User.count }.by(1)
expect(User.first.username).to eq 'Haifa, Israel'
end
it 'does not crash on missing nested attributes' do
sorcery_model_property_set(:authentications_class, Authentication)
sorcery_controller_external_property_set(:facebook, :user_info_mapping, { username: 'name', created_at: 'does/not/exist' })
expect { get :test_create_from_provider, provider: 'facebook' }.to change { User.count }.by 1
expect(User.first.username).to eq 'Noam Ben Ari'
expect(User.first.created_at).not_to be_nil
end
describe 'with a block' do
before(:each) do
user = User.new(username: 'Noam Ben Ari')
user.save!(validate: false)
user.authentications.create(provider: 'twitter', uid: '456')
end
it 'does not create user' do
sorcery_model_property_set(:authentications_class, Authentication)
sorcery_controller_external_property_set(:facebook, :user_info_mapping, { username: 'name' })
# test_create_from_provider_with_block in controller will check for uniqueness of username
expect { get :test_create_from_provider_with_block, provider: 'facebook' }.not_to change { User.count }
end
end
end
end
|
#!/usr/bin/ruby
$:.unshift File.join(File.dirname(__FILE__), ".", "..", "lib")
require 'EmailHelper'
require 'EnvironmentInfo.rb'
require 'yaml'
# Class to apply various Picard/Custom tools to generate a BAM file and
# calculate alignment stats.
# Author Nirav Shah niravs@bcm.edu
class BAMProcessor
# Constructor
# fcBarcode - LIMS barcode for the flowcell
# isPairedEnd - true if flowcell is paired end, false otherwise
# phixFilter - true if phix reads should be filtered, false otherwise
# samFileName - Name of the sam file
# sortedBAMName - Name of the bam that is coordinate sorted
# finalBAMName - Name of the final BAM file
def initialize(fcBarcode, isPairedEnd, phixFilter, samFileName, sortedBAMName,
finalBAMName)
@fcBarcode = fcBarcode
@samFileName = samFileName
@sortedBam = sortedBAMName
@markedBam = finalBAMName
# Is SAM/BAM fragment or paired end
@isFragment = !isPairedEnd
# Whether to filter out phix reads or not
@filterPhix = phixFilter
# Directory hosting various custom-built jars
@javaDir = File.dirname(File.dirname(__FILE__)) + "/java"
# Read picard parameters from yaml config file
yamlConfigFile = File.dirname(File.dirname(__FILE__)) + "/config/config_params.yml"
@configReader = YAML.load_file(yamlConfigFile)
# Parameters for picard commands
@picardPath = @configReader["picard"]["path"]
puts "Picard path = " + @picardPath
@picardValStr = @configReader["picard"]["stringency"]
puts "Picard validation stringency = " + @picardValStr
@picardTempDir = @configReader["picard"]["tempDir"]
puts "Picard temp dir = " + @picardTempDir
@maxRecordsInRam = @configReader["picard"]["maxRecordsInRAM"]
puts "Max records in ram = " + @maxRecordsInRam.to_s
@heapSize = @configReader["picard"]["maxHeapSize"]
puts "Heap Size = " + @heapSize.to_s
@envInfo = EnvironmentInfo.new()
end
# Apply the series of command to generate a final BAM
def process()
puts "Displaying environment characteristics"
@envInfo.displayEnvironmentInformation(true)
if @isFragment == false
puts "Fixing Mate information"
cmd = fixMateInfoCmd()
runCommand(cmd, "fixMateInformation")
else
puts "Fragment run, sorting BAM"
cmd = sortBamCommand()
runCommand(cmd, "sortBam")
end
puts "Marking Duplicates"
cmd = markDupCommand()
runCommand(cmd, "markDups")
if @filterPhix == true
puts "Filtering out phix reads"
cmd = filterPhixReadsCmd(@markedBam)
runCommand(cmd, "filterPhix")
end
puts "Fixing CIGAR for unmapped reads"
cmd = fixCIGARCmd(@markedBam)
runCommand(cmd, "fixCIGAR")
puts "Calculating mapping stats"
cmd = mappingStatsCmd()
runCommand(cmd, "mappingStats")
end
private
# Sort the BAM by mapping coordinates
def sortBamCommand()
cmd = "java " + @heapSize + " -jar " + @picardPath + "/SortSam.jar I=" + @samFileName +
" O=" + @sortedBam + " SO=coordinate " + @picardTempDir + " " +
@maxRecordsInRam.to_s + " " + @picardValStr + " 1>sortbam.o 2>sortbam.e"
return cmd
end
# Mark duplicates on a sorted BAM
def markDupCommand()
cmd = "java " + @heapSize + " -jar " + @picardPath + "/MarkDuplicates.jar I=" +
@sortedBam + " O=" + @markedBam + " " + @picardTempDir + " " +
@maxRecordsInRam.to_s + " AS=true M=metrics.foo " +
@picardValStr + " 1>markDups.o 2>markDups.e"
return cmd
end
# Filter reads mapping to phix and phix contig from the BAM header
def filterPhixReadsCmd(bamFile)
jarName = @javaDir + "/PhixFilterFromBAM.jar"
cmd = "java " + @heapSize + " -jar " + jarName + " I=" + bamFile +
" 1>phixFilter.o 2>phixFilter.e"
return cmd
end
# Correct the flag describing the strand of the mate
def fixMateInfoCmd()
cmd = "java " + @heapSize + " -jar " + @picardPath + "/FixMateInformation.jar I=" +
@samFileName.to_s + " O=" + @sortedBam + " SO=coordinate " + @picardTempDir + " " +
@maxRecordsInRam.to_s + " " + @picardValStr + " 1>fixMateInfo.o 2>fixMateInfo.e"
return cmd
end
# Correct the unmapped reads. Reset CIGAR to * and mapping quality to zero.
def fixCIGARCmd(bamFile)
jarName = @javaDir + "/FixCIGAR.jar"
cmd = "java " + @heapSize + " -jar " + jarName + " I=" + bamFile +
" 1>fixCIGAR.o 2>fixCIGAR.e"
return cmd
end
# Method to build command to calculate mapping stats
def mappingStatsCmd()
jarName = @javaDir + "/BAMAnalyzer.jar"
cmd = "java " + @heapSize + " -jar " + jarName + " I=" + @markedBam +
" O=BWA_Map_Stats.txt X=BAMAnalysisInfo.xml 1>mappingStats.o 2>mappingStats.e"
return cmd
end
# Method to handle error. Current behavior, print the error stage and abort.
def handleError(commandName)
errorMessage = "Error while processing command : " + commandName.to_s +
" for flowcell : " + @fcBarcode.to_s + " Working Dir : " +
Dir.pwd.to_s + " Hostname : " + @envInfo.getHostName()
# For now keep like this
emailSubject = "Error while mapping : " + @fcBarcode.to_s
obj = EmailHelper.new()
emailFrom = "sol-pipe@bcm.edu"
emailTo = obj.getErrorRecepientEmailList()
emailSubject = "Error during mapping on host " + @envInfo.getHostName()
obj.sendEmail(emailFrom, emailTo, emailSubject, errorMessage)
puts errorMessage.to_s
exit -1
end
# Method to run the specified command
def runCommand(cmd, cmdName)
startTime = Time.now
`#{cmd}`
endTime = Time.now
returnValue = $?
displayExecutionTime(startTime, endTime)
if returnValue != 0
handleError(cmdName)
end
end
# Display execution time as the difference between start time and end time
def displayExecutionTime(startTime, endTime)
timeDiff = (endTime - startTime) / 3600
puts "Execution time : " + timeDiff.to_s + " hours"
end
@isFragment = false # Is read fragment, default is paired (true)
@samFileName = nil # Name of SAM file to generate using BWA
@sortedBam = nil # Name of sorted BAM
@markedBam = nil # Name of BAM with duplicates marked
@picardPath = nil # Picard path
end
fcBarcode = ARGV[0]
fcPairedEnd = ARGV[1]
filterPhixReads = ARGV[2]
samFileName = ARGV[3]
sortedBAMName = ARGV[4]
finalBAMName = ARGV[5]
obj = BAMProcessor.new(fcBarcode, fcPairedEnd, filterPhixReads, samFileName,
sortedBAMName, finalBAMName)
obj.process()
|
class Contact < ActiveRecord::Base
has_many :emails
has_many :users, through: :emails
end
|
require 'rails_helper'
RSpec.describe "traffics/new", type: :view do
before(:each) do
assign(:traffic, Traffic.new(
:phone => false,
:visit => false,
:converted => false,
:qualified => 1,
:user => nil,
:placement => nil,
:note => nil
))
end
it "renders new traffic form" do
render
assert_select "form[action=?][method=?]", traffics_path, "post" do
assert_select "input[name=?]", "traffic[phone]"
assert_select "input[name=?]", "traffic[visit]"
assert_select "input[name=?]", "traffic[converted]"
assert_select "input[name=?]", "traffic[qualified]"
assert_select "input[name=?]", "traffic[user_id]"
assert_select "input[name=?]", "traffic[placement_id]"
assert_select "input[name=?]", "traffic[note_id]"
end
end
end
|
# frozen_string_literal: true
class Food < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to :food_category
belongs_to :user
has_many :food_comments, dependent: :destroy
has_one_attached :image
has_many :food_likes, dependent: :destroy
with_options presence: true do
# カテゴリー選択は1以外
validates :food_category_id, numericality: { other_than: 1 }
# 商品名は40文字以内
validates :title, length: { minimum: 1, maximum: 40 }
# 商品詳細は250文字以内
validates :detail, length: { minimum: 1, maximum: 250 }
# 値段は半角数字
validates :price, numericality: { only_integer: true, less_than: 9_999_999 }, format: { with: /\A[0-9]+\z/ }
# 画像は必須
validates :image
end
end
|
Rails.application.routes.draw do
root to: 'static#home'
get '/home', to: 'static#home', as: 'home'
get '/devs', to: 'static#devs', as: 'devs'
get '/corpo', to: 'static#corpo', as: 'corpo'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
class RespuestaController < ApplicationController
before_action :set_respuestum, only: [:show, :edit, :update, :destroy]
# GET /respuesta
# GET /respuesta.json
def index
@respuesta = Respuestum.all
end
# GET /respuesta/1
# GET /respuesta/1.json
def show
end
# GET /respuesta/new
def new
@respuestum = Respuestum.new
end
# GET /respuesta/1/edit
def edit
end
# POST /respuesta
# POST /respuesta.json
def create
@respuestum = Respuestum.new(respuestum_params)
@acceso = Acceso.find_by(plaza_id: params[:respuestum][:plaza_id])
@plaza = Plaza.find(params[:respuestum][:plaza_id])
#comprobamos que no sean iguales
if params[:respuestum][:a] == params[:respuestum][:b]
redirect_to new_respuestum_path(plaza_id: @plaza.id), notice: 'Las respuestas 1 y 2 no pueden ser iguales.'
else
if params[:respuestum][:a] == params[:respuestum][:c]
redirect_to new_respuestum_path(plaza_id: @plaza.id), notice: 'Las respuestas 1 y 3 no pueden ser iguales.'
else
if params[:respuestum][:b] == params[:respuestum][:c]
redirect_to new_respuestum_path(plaza_id: @plaza.id), notice: 'Las respuestas 2 y 3 no pueden ser iguales.'
else
#ahora comprobar si sean verdaderas
if params[:respuestum][:a] == @acceso.a or params[:respuestum][:a] == @acceso.b or params[:respuestum][:a] == @acceso.c
if params[:respuestum][:b] == @acceso.a or params[:respuestum][:b] == @acceso.b or params[:respuestum][:b] == @acceso.c
if params[:respuestum][:c] == @acceso.a or params[:respuestum][:c] == @acceso.b or params[:respuestum][:c] == @acceso.c
respond_to do |format|
if @respuestum.save
format.html { redirect_to user_plaza_path(user_id: current_user.id, id: @respuestum.plaza_id), notice: 'Enhorabuena, has accedido a la comunidad.' }
format.json { render :show, status: :created, location: @respuestum }
else
format.html { render :new }
format.json { render json: @respuestum.errors, status: :unprocessable_entity }
end
end
else
redirect_to new_respuestum_path(plaza_id: @plaza.id), notice: 'Las respuestas no son correctas.'
end
else
redirect_to new_respuestum_path(plaza_id: @plaza.id), notice: 'Las respuestas no son correctas.'
end
else
redirect_to new_respuestum_path(plaza_id: @plaza.id), notice: 'Las respuestas no son correctas.'
end
end
end
end
end
# PATCH/PUT /respuesta/1
# PATCH/PUT /respuesta/1.json
def update
respond_to do |format|
if @respuestum.update(respuestum_params)
format.html { redirect_to @respuestum, notice: 'Respuestum was successfully updated.' }
format.json { render :show, status: :ok, location: @respuestum }
else
format.html { render :edit }
format.json { render json: @respuestum.errors, status: :unprocessable_entity }
end
end
end
# DELETE /respuesta/1
# DELETE /respuesta/1.json
def destroy
@respuestum.destroy
respond_to do |format|
format.html { redirect_to respuesta_url, notice: 'Respuestum was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_respuestum
@respuestum = Respuestum.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def respuestum_params
params.require(:respuestum).permit(:user_id, :plaza_id, :a, :b, :c)
end
end
|
class Api::V1::OrdersController < Api::V1Controller
rescue_from ActiveRecord::RecordNotFound do |e|
render json: {success: false, error: e.message }, :status => 404 # nothing, redirect or a template
end
before_action :set_order, only: [:add_items, :update, :show, :delete_items, :complete, :select_order]
after_action :set_activity, only: [:add_items, :delete_items]
def index
authorize! :read, Order
@orders = current_user.orders.completed
render json: {success: true, orders: @orders}
end
def show
authorize! :read, @order
render json: {:order=>@order.show_list}
end
def select_order
authorize! :manage, @order
render json: {order: @order.show_order_list.slice(:id, :amount, :name, :qty), items:@order.order_list}
end
def active
hash = {active: 1, ids: {}, items:{}}
@orders = current_user.orders.active
if @orders.empty?
Order.create(:user => current_user)
@orders = current_user.orders.active
end
@orders.each do |order|
hash[:active] = order.id
hash[:ids][order.id] = order.show_order_list.slice(:id, :amount, :name, :qty)
hash[:items] = order.order_list
end
render json: {:orders=> hash}
end
def add_items
authorize! :manage, @order
ids = items_params
@items = Item.where("id IN (?)", ids.keys).select("id")
@old_items = @order.order_list.dup
@items.each do |item|
@order.order_list[item.id.to_s] ? date = @order.order_list[item.id.to_s]['created_at'] : date = DateTime.now.to_i
@order.order_list[item.id] = {'qty'=>ids[item.id.to_s].to_i, 'created_at'=>date}
end
if @order.save
if params[:fullOrder] == 'true'
response = {:order=>@order.show_list}
else
response = {success: true, order: @order.show_order_list.slice(:id,:name,:amount, :qty), items:@order.order_list}
end
render :json => response
end
@new_items = @order.order_list.dup
end
def create
authorize! :create, Order
@order = Order.new(:user=>current_user, :name=>params[:order][:name])
if @order.save
render json: {:order=>@order.show_order_list.slice(:id, :name, :amount, :qty), :items=>{}, :success=>true}
else
render json: {:success=>false}
end
end
def complete
authorize! :manage, @order
if @order.has_items?
@order.comment = params[:comment]
if @order.complete
ForwardingWorker.perform_async(@order.id)
render :json => {status: "success", order: @order}
end
else
render :json => {status: "error"}
end
end
def delete_items
authorize! :manage, @order
@old_items = @order.order_list.dup
ids = params[:items]
ids.each do |id|
@order.order_list.delete(id)
end
if @order.save
if params[:fullOrder] == 'true'
response = {:order=>@order.show_list}
else
response = {success: true, order: @order.show_order_list.slice(:id,:name,:amount, :qty), items:@order.order_list}
end
render :json => response
end
@new_items = @order.order_list.dup
end
private
def set_order
@order = Order.find(params[:id])
end
def order_params
unless ['create', 'show', 'delete_items'].include? action_name
params.require(:order).permit(:id)
end
end
def items_params
params.require(:items).permit!
end
def set_activity
activity_save :controller=>controller_name, :action=>action_name, :old_items=>@old_items, :new_items=>@new_items, :path=>URI(request.referer).path
end
end
|
module TicTacToe
class Board
PLAYER_X = "X"
PLAYER_O = "O"
EMPTY_MARK = "-"
BOARD_SIZE = 9
def initialize(input_grid)
@grid = build_grid(input_grid)
end
def self.empty_board
Board.new("---------")
end
def empty?
remaining_moves.count == BOARD_SIZE
end
def make_move(position, mark)
grid_new = grid.dup
grid_new[position] = mark if valid_move?(position)
Board.new(build_string_grid(grid_new))
end
def position_at(position)
grid[position]
end
def valid_move?(position)
in_valid_range?(position) && empty_at?(position)
end
def remaining_moves
grid.map.with_index do |_, index|
index if empty_at?(index)
end.compact
end
def current_player
remaining_moves.count.odd? ? PLAYER_X : PLAYER_O
end
def other_player
remaining_moves.count.even? ? PLAYER_X : PLAYER_O
end
def game_over?
drawn? || game_won?
end
def game_won?
rows_same? || columns_same? || diagonal_same?
end
def drawn?
return false if game_won?
remaining_moves.count.equal?(0)
end
def winner
if game_won?
other_player
else
EMPTY_MARK
end
end
private
attr_reader :grid
def columns_same?
all_same?([0, 3, 6]) ||
all_same?([1, 4, 7]) ||
all_same?([2, 5, 8])
end
def diagonal_same?
all_same?([0, 4, 8]) ||
all_same?([2, 4, 6])
end
def rows_same?
all_same?([0, 1, 2]) ||
all_same?([3, 4, 5]) ||
all_same?([6, 7 ,8])
end
def all_same?(positions)
return false if any_mark_empty?(positions)
positions.map { |position| grid[position] }.uniq.length == 1
end
def any_mark_empty?(positions_to_check)
positions_to_check
.map { |position| grid[position] }
.any? { |mark| mark.nil? }
end
def in_valid_range?(position)
position < grid.count && position >= 0
end
def empty_at?(position)
grid[position] != PLAYER_X && grid[position] != PLAYER_O
end
def mark_is_player?(mark)
mark == PLAYER_X || mark == PLAYER_O
end
def build_grid(grid)
grid.split("").map do |mark|
mark if mark_is_player? mark
end
end
def build_string_grid(grid_new)
grid_new.map do |cell|
if cell.nil?
EMPTY_MARK
else
cell
end
end.join("")
end
end
end
|
class Investigationinjurylocation < ApplicationRecord
belongs_to :investigation
belongs_to :injurylocation
end
|
class BagesController < ApplicationController
before_action :authenticate_user!
def index
@bages = Bage.all
@user_bages = current_user.bages
end
end
|
require 'test/unit'
require_relative './task'
class Task4 < Test::Unit::TestCase
def test_byr
assert_true valid_byr({ 'byr' => '1921' })
assert_false valid_byr({ 'byr' => '1919' })
assert_false valid_byr({ 'byr' => '1dsf' })
end
def test_hgt
assert_true valid_hgt({ 'hgt' => '60in' })
assert_true valid_hgt({ 'hgt' => '190cm' })
assert_false valid_hgt({ 'hgt' => '9001cm' })
assert_false valid_hgt({ 'hgt' => '190in' })
assert_false valid_hgt({ 'hgt' => '190' })
end
def test_hcl
assert_true valid_hcl({ 'hcl' => '#f23456' })
assert_false valid_hcl({ 'hcl' => '#zzzz42' })
assert_false valid_hcl({ 'meow' => '#f23456' })
end
def test_ecl
assert_true valid_ecl({ 'ecl' => 'grn' })
assert_false valid_ecl({ 'ecl' => 'zzz' })
end
def test_second_valid_passport
assert_true valid_second('pid' => '087499704',
'hgt' => '74in',
'ecl' => 'grn',
'iyr' => '2012',
'eyr' => '2030',
'byr' => '1980',
'hcl' => '#623a2f')
end
end
|
# == Schema Information
#
# Table name: events
#
# id :integer not null, primary key
# env_id :integer indexed
# source :string
# status :integer
# severity :integer
# uuid :string(36) indexed
# data :string
# event_type :integer default("operational")
# deleted_at :datetime indexed
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_events_on_deleted_at (deleted_at)
# index_events_on_env_id (env_id)
# index_events_on_uuid (uuid)
#
describe Event, type: :model do
it { is_expected.to validate_presence_of(:source) }
it { is_expected.to validate_presence_of(:event_type) }
it {
is_expected.to define_enum_for(:event_type)
.with_values(%i[operational performance tests devel])
}
it {
is_expected.to define_enum_for(:status)
.with_values(%i[open closed acked])
}
it {
is_expected.to define_enum_for(:severity)
.with_values(%i[low moderate major critical])
}
it { is_expected.to belong_to(:env) }
describe '.run_action' do
it 'should be accessible and always wrap to array' do
event = Event.create!(source: 'Cluster')
event.run_actions = 'A'
expect(event.run_actions).to eq ['A']
end
it 'should return nil if run_action is not set' do
event = Event.create!(source: 'Cluster')
expect(event.run_actions).to be_nil
end
end
it 'should be immutable afrer create' do
event = Event.create!(source: 'Cluster')
event.source = 'other'
expect { event.save! }.to raise_error ActiveRecord::ReadOnlyRecord
end
it 'should not throw when service does not exists' do
e = Env.first
e.env_actions.create!(name: 'not_exists', data: { run_by_service: 'db_journal' })
expect { Event.create(source: 'Cluster', env: e) }.not_to raise_error
end
it 'should not throw when service throws an error' do
class ThrowErrorService
def initialize(_event)
raise RuntimeError
end
end
e = Env.first
e.env_actions.create!(name: 'throw_error', data: { run_by_service: 'throw_error' })
expect { Event.create(source: 'Cluster', env: e) }.not_to raise_error
end
describe 'services' do
it 'should run db_journal service after create' do
e = Env.first
e.env_actions.create!(name: 'db_journal', data: { run_by_service: 'db_journal' })
Event.create(source: 'Cluster', env: e)
end
describe 'write file' do
let(:path) { '/tmp/event.1' }
after(:each) do
# TODO: check why MemFS is not working here
File.delete(path)
end
it 'should run write_file service after create' do
e = Env.first
e.env_actions.create!(name: 'write_file', data: { run_by_service: 'write_file' })
Event.create(source: 'Cluster', env: e, data: { path: path, content: 'some test content' })
expect(File.exist?(path)).to be true
expect(File.read(path)).to eq 'some test content'
end
end
describe 'external service' do
let(:path) { '/opt/putit/putit-plugins/external/test.txt' }
after(:each) do
# TODO: check why MemFS is not working here
File.delete(path)
end
xit 'should load service from /opt/putit/putit-plugins/external directory' do
expect_any_instance_of(ExternalTestService).to receive(:new).and_call_original
e = Env.first
e.env_actions.create!(name: 'external', data: { run_by_service: 'external_test' })
Event.create(source: 'Cluster', env: e, data: { content: 'external test content' })
expect(File.exist?(path)).to be true
expect(File.read(path)).to eq 'external test content'
end
end
describe 'event can choose which action it will trigger' do
let(:env) do
env = Env.first
env.env_actions.create!(name: 'A', data: { run_by_service: 'A' })
env.env_actions.create!(name: 'B', data: { run_by_service: 'B' })
env.env_actions.create!(name: 'C', data: { run_by_service: 'C' })
env
end
it 'should run one action out of many' do
Event.create(source: 'Cluster', env: env, run_actions: 'B', data: { hostname: 'host-av-1' })
expect(AService.called).to be false
expect(BService.called).to be true
expect(CService.called).to be false
end
it 'should run multiple actions out of many' do
Event.create(source: 'Cluster', env: env, run_actions: %w[B C], data: { hostname: 'host-av-1' })
expect(AService.called).to be false
expect(BService.called).to be true
expect(CService.called).to be true
end
end
end
end
|
class Budget < ApplicationRecord
audited only: %i[value], on: %i[create update]
IATI_TYPES = Codelist.new(type: "budget_type", source: "iati").hash_of_coded_names
IATI_STATUSES = Codelist.new(type: "budget_status", source: "iati").hash_of_coded_names
enum budget_type: {
direct: 0,
other_official: 1
}
belongs_to :parent_activity, class_name: "Activity"
belongs_to :report, optional: true
belongs_to :providing_organisation, class_name: "Organisation", optional: true
before_validation :infer_and_assign_providing_org_attrs
validates_presence_of :report, unless: -> { parent_activity&.organisation&.service_owner? }
validates_presence_of :value,
:currency,
:financial_year,
:budget_type
validates :value, numericality: {other_than: 0, less_than_or_equal_to: 99_999_999_999.00}
validate :ensure_value_changed, on: :update
with_options if: -> { direct? } do |direct_budget|
direct_budget.validate :direct_budget_providing_org_must_be_beis
direct_budget.validates :providing_organisation_id, presence: true
end
with_options if: -> { other_official? } do |external_budget|
external_budget.validates :providing_organisation_name, presence: true
external_budget.validates :providing_organisation_type, presence: true
end
def financial_year
return nil if self[:financial_year].nil?
FinancialYear.new(self[:financial_year])
end
def period_start_date
financial_year&.start_date
end
def period_end_date
financial_year&.end_date
end
def iati_type
return IATI_TYPES.fetch("original") if original?
IATI_TYPES.fetch("revised")
end
def iati_status
IATI_STATUSES.fetch("indicative")
end
def original_revision
audits.find_by(action: "create").revision
end
def any_update_audits?
audits.updates.any?
end
private def original?
return audits.none? || audits.last.version == 1 if live?
audit_version == 1
end
private def live?
# audit_version is only available on revisions. If the object
# is not a revision, we can determine that it is the live Budget.
audit_version.nil?
end
private def ensure_value_changed
errors.add(:value, :not_changed) if audit_comment.present? && !value_changed?
end
private def direct_budget_providing_org_must_be_beis
errors.add(:providing_organisation_name, "Providing organisation for direct funding must be BEIS!") unless providing_organisation.service_owner?
end
private def infer_and_assign_providing_org_attrs
if direct?
self.providing_organisation_id = Organisation.service_owner.id
self.providing_organisation_name = nil
self.providing_organisation_type = nil
self.providing_organisation_reference = nil
else
self.providing_organisation_id = nil
end
end
end
|
class BookingsController < ApplicationController
skip_before_action :authenticate_user!
def create
@user = current_user
@booking = current_user.bookings.build(params.require(:booking))
@new_booking = Booking.new
if @booking.save
flash.now[:notice] = "RSVP saved!"
else
flash.now[:error] = "There was an error saving your RSVP. Please try again later."
end
end
def new
@booking = Booking.new
end
def edit
end
def index
@bookings = Booking.all
end
def show
end
end
|
require 'bigdecimal'
class IntegrateSquare
# precision (number of significant digits)
P = 10
# method names and their description
Methods = {
m1: "sum += dx * (dx * i) ** 2",
m2: "sum += (dx * i) ** 2",
m3: "sum += xi ** 2",
m4: "y_total += y_left + y_right, xi=dx*i",
m5: "y_total += y_left + y_right, xi+=dx",
m6: "simpson",
}
def self.m1(a, b, n)
area = BigDecimal.new('0', P)
a,b,dx = a_b_dx(a,b,n)
1.upto(n) do |i|
area = area.add(dx.mult(dx.mult(i, P).power(2, P), P), P)
end
area
end
def self.m2(a, b, n)
y_total = BigDecimal.new('0', P)
a,b,dx = a_b_dx(a,b,n)
1.upto(n) do |i|
y_total = y_total.add(dx.mult(i, P).power(2, P), P)
end
y_total.mult(dx, P)
end
def self.m3(a, b, n)
y_total = BigDecimal.new('0', P)
a,b,dx = a_b_dx(a,b,n)
xi = a.add(dx, P)
while xi <= b
y_total = y_total.add(xi.power(2, P), P)
xi = xi.add(dx, P)
end
y_total.mult(dx, P)
end
def self.m4(a, b, n)
y_total = BigDecimal.new('0', P)
a,b,dx = a_b_dx(a,b,n)
y_left = a.power(2, P)
1.upto(n) do |i|
xi = dx.mult(i, P)
y_right = xi.power(2, P)
y_total = y_total.add(y_left.add(y_right, P), P)
y_left = y_right
end
y_total.div(2, P).mult(dx, P)
end
def self.m5(a, b, n)
# FIXME: error has peak in n=18,22,24,27,28
y_total = BigDecimal.new('0', P)
a,b,dx = a_b_dx(a,b,n)
y_left = a.power(2, P)
xi = a.add(dx, P)
while xi <= b
y_right = xi.power(2, P)
y_total = y_total.add(y_left.add(y_right, P), P)
y_left = y_right
xi = xi.add(dx, P)
end
y_total.div(2, P).mult(dx, P)
end
def self.m6(a, b, n) # Simpson
raise "n must be even" unless n.even?
y_total = BigDecimal.new('0', P)
a,b,dx = a_b_dx(a,b,n)
y_total = y_total.add(a.power(2, P), P)
y_total = y_total.add(b.power(2, P), P)
y_uneven = BigDecimal.new('0', P)
1.upto(n/2) do |i|
xi = dx.mult(2*i-1, P)
y_uneven = y_uneven.add(xi.power(2, P), P)
end
y_total = y_total.add(y_uneven.mult(4, P), P)
y_even = BigDecimal.new('0', P)
1.upto(n/2-1) do |i|
xi = dx.mult(2*i, P)
y_even = y_even.add(xi.power(2, P), P)
end
y_total = y_total.add(y_even.mult(2, P), P)
y_total.mult(dx, P).div(3, P)
end
private
def self.a_b_dx(a,b,n)
a = BigDecimal.new(a, P)
b = BigDecimal.new(b, P)
dx = b.sub(a, P).div(n, P)
return a,b,dx
end
end
##
# Compare presicions (error) in relation to n and find n where error starts
# growing the first time.
#
ErrorPrecision = 50
Correct = BigDecimal.new(Rational('1/3'), ErrorPrecision)
n_max = 20
a, b = '0', '1' # strings for BigDecimal
puts "a = #{a}, b = #{b}"
puts "correct = #{Correct.to_s("F")}"
puts "n_max = #{n_max}"
puts "precision = #{IntegrateSquare::P}"
puts "error precision = #{ErrorPrecision}"
previous_errors = {}
IntegrateSquare::Methods.keys.each do |method|
previous_error = nil
current_errors = {}
1.upto(n_max) do |n|
begin
result = IntegrateSquare.send(method, a, b, n)
error = -(Correct.sub(result, ErrorPrecision))
current_errors[n] = error
previous_error = previous_errors[n]
factor = previous_error.div(error, ErrorPrecision) if previous_error
puts "%3s(n = %5i): %75s %75s (%+.3f)" % [ method, n, result.to_s("F"), error.to_s("+F"), factor||0 ]
# comment to see errors
break if current_errors[n-1] and current_errors[n-1].abs <= error.abs
rescue
puts "%3s(n = %5i): FAILED" % [ method, n]
end
end
previous_errors = current_errors
puts "-" * 80
end
##
# Find minimum n required to have an error less than the threshold.
#
n_by_method = { }
puts "Finding minimum n required for small error."
threshold = BigDecimal.new('0.001', ErrorPrecision)
n_max = 10_000
a, b = '0', '1' # strings for BigDecimal
IntegrateSquare::Methods.each do |method,description|
puts "trying #{method} ..."
1.upto(n_max) do |n|
begin
result = IntegrateSquare.send(method, a, b, n)
error = Correct.sub(result, ErrorPrecision).abs
# puts error.to_s("F")
if error < threshold
puts "#{method}: #{description}: n_min = #{n}"
n_by_method[method] = n
break
end
rescue
puts "#{method}: #{description}: n_min = #{n} FAILED"
end
end
if not n_by_method.key?(method)
puts "Unable to find n for method #{method}."
end
end
##
# Benchmark times required to find desired precision (with n specific to each
# method from the previous test).
#
require 'benchmark'
m = 1_000
puts "Benchmark to find minimum error for each method (#{m} times each)."
Benchmark.bmbm do |x|
a, b = '0', '1' # strings for BigDecimal
IntegrateSquare::Methods.each do |method,description|
n = n_by_method[method]
if n.nil?
puts "Skipping #{method} because there's no n for it."
next
end
x.report("#{method}: #{description}") do
m.times do
IntegrateSquare.send(method, a, b, n_by_method[method])
end
end
end
end
|
# frozen_string_literal: true
require "support/helpers/context"
require "support/helpers/source_input"
RSpec.describe Openapi3Parser::Context do
include Helpers::Context
include Helpers::SourceInput
describe ".root" do
subject(:context) { described_class.root(input, source) }
let(:input) { {} }
let(:source) do
source_input = Openapi3Parser::SourceInput::Raw.new(input)
document = Openapi3Parser::Document.new(source_input)
document.root_source
end
it "has no reference" do
expect(context.referenced_by).to be_nil
end
it "has an empty pointer" do
expect(context.document_location.pointer.to_s).to eq "#/"
end
end
describe ".next_field" do
subject(:context) { described_class.next_field(parent_context, field) }
let(:input) { { "key" => "value" } }
let(:parent_context) do
create_context(input, document_input: input, pointer_segments: [])
end
let(:field) { "key" }
it "has an input of 'value'" do
expect(context.input).to eq "value"
end
it "has a pointer fragment of '#/key'" do
expect(context.document_location.pointer.to_s).to eq "#/key"
end
end
describe ".reference_field" do
subject(:context) do
described_class.reference_field(referencer_context,
input: reference_input,
source: source,
pointer_segments: pointer_segments)
end
let(:referencer_context) do
create_context({}, pointer_segments: %w[components schemas])
end
let(:reference_input) { { "from" => "reference" } }
let(:source) do
Openapi3Parser::Source.new(Openapi3Parser::SourceInput::Raw.new({}),
referencer_context.document,
referencer_context.document.root_source)
end
let(:pointer_segments) { %w[test pointer] }
it "has the reference_input" do
expect(context.input).to eq reference_input
end
it "is referenced by the previous context" do
expect(context.referenced_by).to be referencer_context
end
it "has the same document location" do
previous_location = referencer_context.document_location
expect(context.document_location).to eq previous_location
end
it "has a source location for the reference" do
reference_source_location = Openapi3Parser::Context::Location.new(
source,
pointer_segments
)
expect(context.source_location).to eq reference_source_location
end
end
describe "#location_summary" do
subject do
described_class.new({},
document_location: document_location,
source_location: source_location)
.location_summary
end
context "when source location and document location are the same" do
let(:document_location) do
create_context_location(create_raw_source_input,
pointer_segments: %w[path to field])
end
let(:source_location) { document_location }
it { is_expected.to eq "#/path/to/field" }
end
context "when source location and document location are different" do
let(:document_location) do
source_input = create_file_source_input(path: "/file.yaml")
create_context_location(source_input,
pointer_segments: %w[path to field])
end
let(:source_location) do
source_input = create_file_source_input(path: "/other-file.yaml")
create_context_location(source_input,
document: document_location.source.document,
pointer_segments: %w[path])
end
it { is_expected.to eq "#/path/to/field (other-file.yaml#/path)" }
end
end
describe "#resolved_input" do
subject(:resolved_input) do
described_class.new({},
document_location: document_location,
is_reference: is_reference)
.resolved_input
end
let(:document_location) do
input = { "openapi" => "3.0.0",
"info" => { "title" => "Test",
"version" => "1.0" },
"paths" => {},
"components" => {
"schemas" => {
"a_reference" => {
"$ref" => "#/components/schemas/not_reference"
},
"not_reference" => { "type" => "object" }
}
} }
create_context_location(Openapi3Parser::SourceInput::Raw.new(input),
pointer_segments: pointer_segments)
end
context "when context is not a reference" do
let(:is_reference) { false }
let(:pointer_segments) { %w[components schemas not_reference type] }
it "returns the data at that location" do
expect(resolved_input).to be "object"
end
end
context "when context is a reference" do
let(:is_reference) { true }
let(:pointer_segments) { %w[components schemas a_reference $ref] }
it "returns the data of the referenced item" do
expect(resolved_input).to match(a_hash_including("type" => "object"))
end
end
end
describe "#node" do
subject(:node) do
described_class.new({},
document_location: document_location,
is_reference: is_reference)
.node
end
let(:document_location) do
input = { "openapi" => "3.0.0",
"info" => { "title" => "Test",
"version" => "1.0" },
"paths" => {},
"components" => {
"schemas" => {
"a_reference" => {
"$ref" => "#/components/schemas/not_reference"
},
"not_reference" => { "type" => "object" }
}
} }
create_context_location(Openapi3Parser::SourceInput::Raw.new(input),
pointer_segments: pointer_segments)
end
context "when context is not a reference" do
let(:is_reference) { false }
let(:pointer_segments) { %w[components schemas not_reference type] }
it "returns the data at that location" do
expect(node).to be "object"
end
end
context "when context is a reference" do
let(:is_reference) { true }
let(:pointer_segments) { %w[components schemas a_reference $ref] }
it "returns the data at the parent item" do
expect(node).to be_a(Openapi3Parser::Node::Schema)
end
end
end
end
|
require 'webmock/rspec'
require 'metriks'
require 'metriks_addons/signalfx_reporter'
describe "Smoke test" do
before(:all) do
stub_request(:any, "http://localhost:4242")
end
before(:each) do
@registry = Metriks::Registry.new
@reporter = MetriksAddons::SignalFxReporter.new(
'http://localhost:4242',
"123456789",
"ABCD",
{:env => "test"},
{ :registry => @registry, :batch_size => 3})
end
after(:each) do
@reporter.stop
@registry.stop
end
it "meter" do
@registry.meter('meter.testing').mark
datapoints = @reporter.get_datapoints
expect(datapoints[:counter].size).to eql(5)
expect(datapoints[:counter][0][:metric]).to eql("meter.testing.count")
expect(datapoints[:counter][0][:value]).to eql(1)
expect(datapoints[:counter][0][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][0][:timestamp]).not_to be_nil
expect(datapoints[:counter][1][:metric]).to eql("meter.testing.one_minute_rate")
expect(datapoints[:counter][1][:value]).not_to be_nil
expect(datapoints[:counter][1][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][1][:timestamp]).not_to be_nil
expect(datapoints[:counter][2][:metric]).to eql("meter.testing.five_minute_rate")
expect(datapoints[:counter][2][:value]).to eql(0.0)
expect(datapoints[:counter][2][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][2][:timestamp]).not_to be_nil
expect(datapoints[:counter][3][:metric]).to eql("meter.testing.fifteen_minute_rate")
expect(datapoints[:counter][3][:value]).to eql(0.0)
expect(datapoints[:counter][3][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][3][:timestamp]).not_to be_nil
expect(datapoints[:counter][4][:metric]).to eql("meter.testing.mean_rate")
expect(datapoints[:counter][4][:value]).not_to be_nil
expect(datapoints[:counter][4][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][4][:timestamp]).not_to be_nil
end
it "counter" do
@registry.counter('counter.testing').increment
datapoints = @reporter.get_datapoints
expect(datapoints[:counter].size).to eql(1)
expect(datapoints[:counter][0][:metric]).to eql("counter.testing.count")
expect(datapoints[:counter][0][:value]).to eql(1)
expect(datapoints[:counter][0][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][0][:timestamp]).not_to be_nil
end
it "timer" do
@registry.timer('timer.testing').update(1.5)
datapoints = @reporter.get_datapoints
expect(datapoints[:counter].size).to eql(11)
expect(datapoints[:counter][0][:metric]).to eql("timer.testing.count")
expect(datapoints[:counter][0][:value]).to eql(1)
expect(datapoints[:counter][0][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][0][:timestamp]).not_to be_nil
expect(datapoints[:counter][1][:metric]).to eql("timer.testing.one_minute_rate")
expect(datapoints[:counter][1][:value]).not_to be_nil
expect(datapoints[:counter][1][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][1][:timestamp]).not_to be_nil
expect(datapoints[:counter][2][:metric]).to eql("timer.testing.five_minute_rate")
expect(datapoints[:counter][2][:value]).to eql(0.0)
expect(datapoints[:counter][2][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][2][:timestamp]).not_to be_nil
expect(datapoints[:counter][3][:metric]).to eql("timer.testing.fifteen_minute_rate")
expect(datapoints[:counter][3][:value]).to eql(0.0)
expect(datapoints[:counter][3][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][3][:timestamp]).not_to be_nil
expect(datapoints[:counter][4][:metric]).to eql("timer.testing.mean_rate")
expect(datapoints[:counter][4][:value]).not_to be_nil
expect(datapoints[:counter][4][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][4][:timestamp]).not_to be_nil
expect(datapoints[:counter][5][:metric]).to eql("timer.testing.min")
expect(datapoints[:counter][5][:value]).not_to be_nil
expect(datapoints[:counter][5][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][5][:timestamp]).not_to be_nil
expect(datapoints[:counter][6][:metric]).to eql("timer.testing.max")
expect(datapoints[:counter][6][:value]).not_to be_nil
expect(datapoints[:counter][6][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][6][:timestamp]).not_to be_nil
expect(datapoints[:counter][7][:metric]).to eql("timer.testing.mean")
expect(datapoints[:counter][7][:value]).not_to be_nil
expect(datapoints[:counter][7][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][7][:timestamp]).not_to be_nil
expect(datapoints[:counter][8][:metric]).to eql("timer.testing.stddev")
expect(datapoints[:counter][8][:value]).not_to be_nil
expect(datapoints[:counter][8][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][8][:timestamp]).not_to be_nil
expect(datapoints[:counter][9][:metric]).to eql("timer.testing.median")
expect(datapoints[:counter][9][:value]).not_to be_nil
expect(datapoints[:counter][9][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][9][:timestamp]).not_to be_nil
expect(datapoints[:counter][10][:metric]).to eql("timer.testing.95th_percentile")
expect(datapoints[:counter][10][:value]).not_to be_nil
expect(datapoints[:counter][10][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][10][:timestamp]).not_to be_nil
end
it "histogram" do
@registry.histogram('histogram.testing').update(1.5)
datapoints = @reporter.get_datapoints
expect(datapoints[:counter].size).to eql(7)
expect(datapoints[:counter][0][:metric]).to eql("histogram.testing.count")
expect(datapoints[:counter][0][:value]).to eql(1)
expect(datapoints[:counter][0][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][0][:timestamp]).not_to be_nil
expect(datapoints[:counter][1][:metric]).to eql("histogram.testing.min")
expect(datapoints[:counter][1][:value]).not_to be_nil
expect(datapoints[:counter][1][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][1][:timestamp]).not_to be_nil
expect(datapoints[:counter][2][:metric]).to eql("histogram.testing.max")
expect(datapoints[:counter][2][:value]).not_to be_nil
expect(datapoints[:counter][2][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][2][:timestamp]).not_to be_nil
expect(datapoints[:counter][3][:metric]).to eql("histogram.testing.mean")
expect(datapoints[:counter][3][:value]).not_to be_nil
expect(datapoints[:counter][3][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][3][:timestamp]).not_to be_nil
expect(datapoints[:counter][4][:metric]).to eql("histogram.testing.stddev")
expect(datapoints[:counter][4][:value]).not_to be_nil
expect(datapoints[:counter][4][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][4][:timestamp]).not_to be_nil
expect(datapoints[:counter][5][:metric]).to eql("histogram.testing.median")
expect(datapoints[:counter][5][:value]).not_to be_nil
expect(datapoints[:counter][5][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][5][:timestamp]).not_to be_nil
expect(datapoints[:counter][6][:metric]).to eql("histogram.testing.95th_percentile")
expect(datapoints[:counter][6][:value]).not_to be_nil
expect(datapoints[:counter][6][:dimensions]).to include(:env => "test")
expect(datapoints[:counter][6][:timestamp]).not_to be_nil
end
it "gauge" do
@registry.gauge('gauge.testing') { 123 }
datapoints = @reporter.get_datapoints
expect(datapoints[:gauge].size).to eql(1)
expect(datapoints[:gauge][0][:metric]).to eql("gauge.testing.value")
expect(datapoints[:gauge][0][:value]).to eql(123)
expect(datapoints[:gauge][0][:dimensions]).to include(:env => "test")
expect(datapoints[:gauge][0][:timestamp]).not_to be_nil
end
end
describe "Rest Client" do
before(:each) do
@registry = Metriks::Registry.new
@reporter = MetriksAddons::SignalFxReporter.new(
'http://localhost:4242/api/datapoint',
"123456789",
"ABCD",
{:env => "test"},
{ :registry => @registry, :batch_size => 3})
stub_request(:post, "http://localhost:4242/api/datapoint?orgid=ABCD").
with(:body => /^\{.*\}$/).
to_return(:status => 200, :body => "", :headers => {})
end
it "Send metricwise" do
for i in 0..2 do
@registry.counter("counter.testing.#{i}").increment
end
@registry.gauge("gauge.testing")
@reporter.submit @reporter.get_datapoints
expect(a_request(:post, "http://localhost:4242/api/datapoint?orgid=ABCD")).to have_been_made
end
end
|
require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper'))
describe BocaGolf::Gist do
describe "safe_module" do
it "creates a module to call methods" do
o = Object.new
o.extend BocaGolf::Gist.new("def foobar(a) a*2; end").safe_module
o.foobar(3).should == 6
end
it "evals code at safe level 4" do
lambda do
BocaGolf::Gist.new(%{
def reverse(a) a.reverse; end;
class ::Object; def foo() end; end
}).safe_module
end.should raise_error(SecurityError)
end
it "calls methods at safe level 4" do
o = Object.new.tap do |o|
o.extend BocaGolf::Gist.new(%{
def foo
::Object.class_eval { def bar() end }
end
}).safe_module
end
lambda { o.foo }.should raise_error(SecurityError)
end
it "allows recursion in solutions" do
o = Object.new.tap do |o|
o.extend BocaGolf::Gist.new(%{
def foo(n)
n > 0 ? foo(n - 1) : :done
end
}).safe_module
end
o.foo(1).should == :done
end
end
describe "load_from_url" do
it "requests the .txt version of gist" do
code = "def a(); end"
FakeWeb.register_uri :get, "https://gist.github.com/746166.txt", :body => code
BocaGolf::Gist.load_from_url("https://gist.github.com/746166").code.should == code
end
end
describe "load_from_file" do
it "reads the file from disk" do
File.should_receive(:read).with("/foo/bar.rb").and_return(code = "def a(); end")
BocaGolf::Gist.load_from_file("/foo/bar.rb").code.should == code
end
end
describe "load_from_location" do
it "loads from url when argument is a valid url" do
code = "def a(); end"
FakeWeb.register_uri :get, "https://gist.github.com/746166.txt", :body => code
BocaGolf::Gist.load_from_location("https://gist.github.com/746166").code.should == code
end
it "loads from file when argument is not a full url" do
File.should_receive(:read).with("/foo/bar.rb").and_return(code = "def a(); end")
BocaGolf::Gist.load_from_location("/foo/bar.rb").code.should == code
end
end
end
|
module Garrison
module Checks
class CheckRedrive < Check
def settings
self.source ||= 'aws-sqs'
self.severity ||= 'critical'
self.family ||= 'infrastructure'
self.type ||= 'compliance'
self.options[:regions] ||= 'all'
end
def key_values
[
{ key: 'datacenter', value: 'aws' },
{ key: 'aws-service', value: 'sqs' },
{ key: 'aws-account', value: AwsHelper.whoami }
]
end
def perform
options[:regions] = AwsHelper.all_regions if options[:regions] == 'all'
options[:regions].each do |region|
Logging.info "Checking region #{region}"
queues = AwsHelper.list_sqs_queues(region, ["RedrivePolicy"])
dead_letter_queue_arns = queues.select { |q| q["RedrivePolicy"] }.map { |q| JSON.parse(q["RedrivePolicy"])["deadLetterTargetArn"] }
no_redrive = queues.reject { |q| dead_letter_queue_arns.include?(q["QueueArn"]) }.select { |q| q["RedrivePolicy"].nil? }
no_redrive.each do |queue|
alert(
name: 'Redrive Policy Violation',
target: queue["QueueArn"],
detail: "SQS queue has no DLQ and isn't acting as one",
finding: queue.to_h.to_json,
finding_id: "aws-sqs-#{queue["QueueArn"]}-redrive",
urls: [
{
name: 'AWS Dashboard',
url: "https://console.aws.amazon.com/sqs/home?region=#{region}#queue-browser:selected=#{queue["QueueUrl"]};noRefresh=true;prefix="
}
],
key_values: [
{
key: 'aws-region',
value: region
}
]
)
end
end
end
end
end
end
|
# ****************************************************************************
#
# Copyright (c) Microsoft Corporation.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the Apache License, Version 2.0, please send an email to
# ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
#
# ****************************************************************************
require "../../Util/simple_test.rb"
describe "inspecting class attributes" do
it "reads the name of a class" do
"bob".class.name.should == "String"
"bob".class.to_s.should == "String"
"bob".class.class.name.should == "Class"
String.name.should == "String"
String.class.name.should == "Class"
end
end
finished
|
class CommentsController < ApplicationController
def add_comment
commentable_type = params[:commentable][:commentable]
commentable_id = params[:commentable][:commentable_id]
# Get the object that you want to comment
commentable = Comment.find_commentable(commentable_type, commentable_id)
# Create a comment with the user submitted content
@comment = Comment.new(params[:comment])
@comment.created_at = Time.now
# Assign this comment to the logged in user
raise "No existe usuario logueado" if (!current_user)
@comment.user = current_user
# Add the comment
commentable.comments << @comment
render :layout=>false
end
end
|
class CreateDocumentEdits < ActiveRecord::Migration[5.1]
def change
create_table :document_edits do |t|
t.string :edit_type
t.string :attribute_path
t.string :value
t.belongs_to :document, index: true
end
end
end
|
module Swine
class AuthConfiguration < Swine::Core::Preferences::Configuration
preference :registration_step, :boolean, :default => true
preference :signout_after_password_change, :boolean, :default => true
preference :confirmable, :boolean, :default => false
end
end
|
# Encoding: UTF-8
# Ruby Hack Night Asteroids by David Andrews and Jason Schweier, 2016
require_relative 'asteroid/base'
require_relative 'asteroid/large'
class Level
def initialize
@round = 0
@last_alien_at = Gosu.milliseconds
end
def complete?
!Asteroid::Base.any?
end
def time_for_new_alien?
@last_alien_at + time_between_aliens < Gosu.milliseconds
end
def alien_added!
@last_alien_at = Gosu.milliseconds
end
def next!
@round += 1
@last_alien_at = Gosu.milliseconds
Asteroid::Large.create(asteroid_count)
end
private
def time_between_aliens
return 999999 if @round < 2
12000 - Math.sqrt(@round) * 1000
end
def asteroid_count
[2 + (@round * 2), 11].min
end
end
|
# If x is less than 10, increment it
if x < 10 # newline separator
x += 1
end
if x < 10 then x += 1 end # then separator
#---------------------------
if x < 10 then
x += 1
end
if data # If the array exists
data << x # then append a value to it.
else # Otherwise...
data = [x] # create a new array that holds the value.
end # This is the end of the conditional.
#---------------------------
if x == 1
name = "one"
elsif x == 2
name = "two"
elsif x == 3 then name = "three"
elsif x == 4; name = "four"
else
name = "many"
end
#--------------------------
name = if x == 1 then "one"
elsif x == 2 then "two"
elsif x == 3 then "three"
elsif x == 4 then "four"
else "many"
end
#---------------------------
puts message if message # Output message, if it is defined
#----------------------------
# Output message if message exists and the output method is defined
puts message if message if defined? puts
#---------------------------
puts message if message and defined? puts
#---------------------------------
# Call the to_s method on object o, unless o is nil
s = unless o.nil? # newline separator
o.to_s
end
s = unless o.nil? then o.to_s end # then separator
#---------------------------
s = o.to_s unless o.nil?
#---------------------------
unless x == 0
puts "x is not 0"
else
unless y == 0
puts "y is not 0"
else
unless z == 0
puts "z is not 0"
else
puts "all are 0"
end
end
end
#---------------------------
name = case
when x == 1 then "one"
when x == 2 then "two"
when x == 3 then "three"
when x == 4 then "four"
else "many"
end
#-----------------------------
case
when x == 1
"one"
when x == 2
"two"
when x == 3
"three"
end
# Compute 2006 U.S. income tax using case and Range objects
tax = case income
when 0..7550
income * 0.1
when 7550..30650
755 + (income-7550)*0.15
when 30650..74200
4220 + (income-30655)*0.25
when 74200..154800
15107.5 + (income-74201)*0.28
when 154800..336550
37675.5 + (income-154800)*0.33
else
97653 + (income-336550)*0.35
end |
require 'helper'
load_all
include ChironSpecHelper
describe 'Chiron command-line interface' do
describe '/help' do
it 'should print help' do
chiron.should =~ /Chiron - Silverlight Dynamic Language Development Utility/
end
end
describe '/webserver' do
it 'should start the webserver on port 2060' do
c = chiron :webserver do |c|
res = http_get('http://localhost:2060', '/')
res.code.should == '200'
res.body.should =~ /test.html/
res.body.should =~ /Chiron\/1.0.0.0/
end
c.split("\n")[1].should == "Chiron serving '#{$DIR.gsub('/', '\\')}' as http://localhost:2060/"
end
it 'should start the webserver on a custom port' do
c = chiron :webserver => 2067 do |c|
res = http_get('http://localhost:2067', '/')
res.code.should == '200'
res.body.should =~ /test.html/
res.body.should =~ /Chiron\/1.0.0.0/
end
c.split("\n")[1].should == "Chiron serving '#{$DIR.gsub('/', '\\')}' as http://localhost:2067/"
end
end
end |
require 'test_helper'
class WelcomeControllerTest < ActionController::TestCase
context "On GET to :index" do
setup do
@en = Factory.create(:language, :id => 1, :short => 'en', :name => 'English')
@ko = Factory.create(:language, :id => 10, :short => 'ko', :name => 'Korean')
@langs, @users, @origs, @posts = [], [], [], []
10.times do
@langs << Factory.create(:language)
user = Factory.create(:user)
@users << user
orig = Factory.create(:orig, :origin_id => @en.id)
@origs << orig
post = Factory.create(:post, :ted_id => @ko.id, :orig_id => orig, :user_id => user.id)
@posts << post
end
Language.expects(:all_ordered).returns(@langs)
Orig.expects(:top).returns(@origs)
Post.expects(:top).returns(@posts)
User.expects(:top).returns(@users)
Orig.any_instance.stubs(:post_count).returns('10')
Post.any_instance.stubs(:post_count).returns('10')
User.any_instance.stubs(:post_count).returns('10')
get :index
end
should_assign_to :languages, :top_posts, :top_origs, :top_users
should_render_template :index
end
context "On GET to :showposts" do
setup do
@en = Factory.create(:language, :id => 1, :short => 'en', :name => 'English')
@posts = []
10.times do
@posts << Factory.create(:post, :ted_id => @en.id)
end
get :allposts
end
should_assign_to :posts
should_render_template :allposts
should "show all posts" do
assert_not_equal 0, @posts.size
end
end
end
|
require 'spec_helper'
describe GapIntelligence::Merchant do
include_examples 'Record'
describe 'attributes' do
subject(:merchant) { described_class.new build(:merchant) }
it 'has name' do
expect(merchant).to respond_to(:name)
end
it 'has merchant_type' do
expect(merchant).to respond_to(:merchant_type)
end
it 'has channel' do
expect(merchant).to respond_to(:channel)
end
it 'has country_code' do
expect(merchant).to respond_to(:country_code)
end
end
end
|
class Remove < ActiveRecord::Migration[6.1]
def change
remove_column :locations, :category, :integer
end
end
|
# BoardsController
class BoardsController < ApplicationController
before_action :set_board, only: %i[show update destroy]
# GET /boards
def index
@boards = Board.all
render json: Resources.new(@boards)
end
# POST /boards
def create
@board = Board.create(board_params)
if @board.valid?
render json: @board, status: :created
else
render json: @board.errors
end
end
# GET /boards/:id
def show
render json: @board
end
# PUT /boards/:id
def update
@board.update!(board_params)
render json: @board
end
# DELETE /boards/:id
def destroy
@board.destroy
head :no_content
end
private
def board_params
params.permit(:title, :description, :color)
end
def set_board
@board = Board.find(params[:id])
end
end
|
def knight_moves(start_position, end_position)
#Build the tree
move_graph = KnightMoveList.new(start_position)
#Search the tree
moves_required = move_graph.find(end_position)
#Give response
p "You made it in #{moves_required.length - 1} moves! Here's your path:"
for move in moves_required do
p move
end
end
class KnightMoveList
attr_reader(:root)
KNIGHTMOVES = [
[1,2],[1,-2],
[2,1],[2,-1],
[-1,2],[-1,-2],
[-2,1],[-2,-2]
]
def initialize(start_position)
@root = build_graph(start_position)
end
def build_graph(start_position)
# start_position must be [0-7,0-7] (on the board)
root_node = Node.new(start_position)
positions_travelled = []
node_queue = [root_node]
while node_queue.length > 0
# Get current node off queue
current_node = node_queue.slice!(0)
# Add to positions travelled
positions_travelled.append(current_node.value)
# For each potention KNIGHTMOVES
for delta_x, delta_y in KNIGHTMOVES do
# Get new position
# If on board
# Create node from position
# Add node to current_node.children
# Add node to node_queue
x, y = current_node.value
new_position = [x + delta_x,y + delta_y]
if on_board?(new_position) && positions_travelled.none?(new_position)
child_node = current_node.insert_child(new_position)
node_queue.append(child_node)
end
end
end
root_node
end
def on_board?(position)
x, y = position
x >= 0 && x < 8 && y >= 0 && y < 8
end
def find(position)
# Assumption that position is within board boundaries, [0-7,0-7]
#
# Because of the assumptions made in my graph builder, there will be only
# one node which has the value of the position I am trying to find
# which means to efficiently traverse this graph a breadth first approach is probably the best
# idea. You could brute force it by running it on each of the children's children's childrens'....
# [Node, positions_travelled]
node_queue = [[@root, []]]
until node_queue.empty?
current_node, positions_travelled = node_queue.slice!(0)
positions_travelled.append(current_node.value)
# Base case, we found our position
return positions_travelled if current_node.value == position
for child in current_node.children do
# Ran into issues of pass by reference vs pass by value here
node_queue.append([child, Array.new(positions_travelled)])
end
end
end
end
class Node
attr_reader(:value, :children)
def initialize(position)
@value = position
@children = []
end
def insert_child(position)
# Create node from position
# Add node to children
# Return node
new_node = Node.new(position)
@children.append(new_node)
new_node
end
# Not sure we would really need this
def remove_child(position)
@children.delete_if {|child| child.value == position}
end
# Check if Node is a leaf
def children?
return false if @children.length == 0
end
end |
RSpec.describe Tessera::Ticket do
describe '.find' do
it 'correctly returns parsed ticket found' do
VCR.use_cassette 'ticket_find_success' do
@ticket = Tessera::Ticket.find(1)
end
expect(@ticket).not_to be_nil
expect(@ticket).to be_kind_of(Tessera::Model::Ticket)
expect(@ticket.age).to eq(72840582)
expect(@ticket.archive_flag).to eq("n")
expect(@ticket.changed).to eq("2017-11-04 08:17:21")
expect(@ticket.changed_by).to eq(nil)
expect(@ticket.create_tim_nix).to eq(1436949030)
expect(@ticket.created).to eq("2015-07-15 08:30:30")
expect(@ticket.created_by).to eq(1)
expect(@ticket.customer_id).to eq(nil)
expect(@ticket.customer_user_id).to eq(nil)
expect(@ticket.escalation_response_time).to eq(0)
expect(@ticket.escalation_solution_time).to eq(0)
expect(@ticket.escalation_time).to eq(0)
expect(@ticket.escalation_update_time).to eq(0)
expect(@ticket.group_id).to eq(1)
expect(@ticket.lock).to eq("unlock")
expect(@ticket.lock_id).to eq(1)
expect(@ticket.owner).to eq("root@localhost")
expect(@ticket.owner_id).to eq(1)
expect(@ticket.priority).to eq("3 normal")
expect(@ticket.priority_id).to eq(3)
expect(@ticket.queue).to eq("Raw")
expect(@ticket.queue_id).to eq(2)
expect(@ticket.real_till_time_not_used).to eq(0)
expect(@ticket.responsible).to eq("root@localhost")
expect(@ticket.responsible_id).to eq(1)
expect(@ticket.service_id).to eq("")
expect(@ticket.slaid).to eq("")
expect(@ticket.state).to eq("new")
expect(@ticket.state_id).to eq(1)
expect(@ticket.state_type).to eq("new")
expect(@ticket.ticket_id).to eq(1)
expect(@ticket.ticket_number).to eq("2015071510123456")
expect(@ticket.title).to eq("Welcome to OTRS!")
expect(@ticket.type).to eq("Unclassified")
expect(@ticket.type_id).to eq(1)
expect(@ticket.unlock_timeout).to eq(0)
expect(@ticket.until_time).to eq(0)
end
it 'correctly returns parsed ticket found' do
expect do
VCR.use_cassette 'ticket_find_failure' do
@ticket = Tessera::Ticket.find(999)
end
end.to raise_error { Tessera::TicketNotFound }
end
it 'correctly returns array of tickets if asked for it' do
VCR.use_cassette 'ticket_array_find_success' do
@tickets = Tessera::Ticket.find([1, 2, 3])
end
expect(@tickets).to be_kind_of(Array)
expect(@tickets.size).to eq(3)
expect(@tickets.first).to be_kind_of(Tessera::Model::Ticket)
expect(@tickets.first.ticket_id).to eq(1)
expect(@tickets.first(2).last.ticket_id).to eq(2)
expect(@tickets.first(3).last.ticket_id).to eq(3)
end
end
describe '.where' do
describe '#ticket_ids' do
it 'returns array of ticket IDs' do
VCR.use_cassette 'ticket_where_ids_success' do
@result = Tessera::Ticket.where(Title: 'Why%')
end
expect(@result.ticket_ids).to contain_exactly(10, 2)
end
end
describe '#tickets' do
it 'returns array of tickets' do
VCR.use_cassette 'ticket_where_tickets_success' do
result = Tessera::Ticket.where(Title: 'Why%')
@tickets = result.tickets
end
expect(@tickets).to be_kind_of(Array)
expect(@tickets.size).to eq(2)
expect(@tickets.first).to be_kind_of(Tessera::Model::Ticket)
expect(@tickets.first.ticket_id).to eq(10)
expect(@tickets.first(2).last.ticket_id).to eq(2)
end
it 'returns array of tickets with different search' do
VCR.use_cassette 'ticket_where_tickets_specific_success' do
result = Tessera::Ticket
.where(Queues: ['Raw'], States: ['new'])
@tickets = result.tickets
end
expect(@tickets).to be_kind_of(Array)
expect(@tickets.size).to eq(4)
expect(@tickets.first).to be_kind_of(Tessera::Model::Ticket)
expect(@tickets.map(&:ticket_number))
.to contain_exactly("2018010410000233", "2018010410000224",
"2018010410000215", "2018010410000206")
end
end
describe '#count' do
it 'returns count of tickets found (Title)' do
VCR.use_cassette 'ticket_where_count_success' do
@result = Tessera::Ticket.where(Title: 'Why%')
end
expect(@result.count).to eq(2)
end
it 'returns count of tickets found (StateType)' do
VCR.use_cassette 'ticket_where_another_count_success' do
@result = Tessera::Ticket.where(StateType: 'new')
end
expect(@result.count).to eq(11)
end
end
end
describe 'create' do
it 'can create ticket form given params' do
params = {
ticket: {
title: 'New ticket',
queue: 2,
state: 'new',
priority: 3,
customer_user: 'andrej',
customer_id: 'aaaaa'
},
article: {
from: 'sender@gmail.com',
subject: 'Hello World!',
body: 'Hello body!',
},
attachment: {
tempfile: Rack::Test::UploadedFile.new('spec/support/files/test.pdf')
}
}
VCR.use_cassette 'ticket_create_success' do
@result = Tessera::Ticket.create(params)
end
expect(@result).to eq({
"ArticleID"=>166,
"TicketID"=>"54",
"TicketNumber"=>"2018010410000251"
})
end
it 'fails creating ticket with OTRS error message (missing params)' do
params = {
ticket: {
title: 'New ticket',
queue: 2,
state: 'new',
priority: 3,
customer_user: nil,
customer_id: 'aaaaa'
},
article: {
from: 'sender@gmail.com',
subject: 'Hello World!',
body: 'Hello body!',
},
attachment: {
tempfile: Rack::Test::UploadedFile.new('spec/support/files/test.pdf')
}
}
VCR.use_cassette 'ticket_create_failure' do
@result = Tessera::Ticket.create(params)
end
expect(@result).to eq({
"Error" => {
"ErrorMessage"=>"TicketCreate: Ticket->CustomerUser parameter is missing!",
"ErrorCode"=>"TicketCreate.MissingParameter"
}
})
end
it 'can create ticket sending article as email to `to` email' do
params = {
ticket: {
title: 'New ticket',
queue: 2,
state: 'new',
priority: 3,
customer_user: 'andrej',
customer_id: 'aaaaa'
},
article: {
from: 'sender@gmail.com',
to: 'receiver@destination.com',
subject: 'Hello World!',
body: 'Hello body!',
article_send: 1
},
attachment: {
tempfile: Rack::Test::UploadedFile.new('spec/support/files/test.pdf')
}
}
VCR.use_cassette 'ticket_create_article_send_success' do
@result = Tessera::Ticket.create(params)
end
expect(@result).to eq({
"ArticleID"=>174,
"TicketID"=>"58",
"TicketNumber"=>"2018010410000297"
})
end
it 'can create ticket sending article as email to multiple `to` email' do
params = {
ticket: {
title: 'New ticket',
queue: 2,
state: 'new',
priority: 3,
customer_user: 'andrej',
customer_id: 'aaaaa'
},
article: {
from: 'sender@gmail.com',
to: 'receiver@destination.com, second@email.com',
subject: 'Hello World!',
body: 'Hello body!',
article_send: 1
}
}
VCR.use_cassette 'ticket_create_article_send_multiple_success' do
@result = Tessera::Ticket.create(params)
end
expect(@result).to eq({
"ArticleID"=>176,
"TicketID"=>"59",
"TicketNumber"=>"2018010410000304"
})
end
it 'can create ticket with multiple attachments' do
params = {
ticket: {
title: 'New ticket',
queue: 2,
state: 'new',
priority: 3,
customer_user: 'andrej',
customer_id: 'aaaaa'
},
article: {
from: 'sender@gmail.com',
subject: 'Hello World!',
body: 'Hello body!',
},
attachment: [
{
tempfile: Rack::Test::UploadedFile.new('spec/support/files/test.pdf')
},
{
tempfile: Rack::Test::UploadedFile.new('spec/support/files/test2.pdf')
}
]
}
VCR.use_cassette 'ticket_create_attachments_success' do
@result = Tessera::Ticket.create(params)
end
expect(@result).to eq({
"ArticleID"=>168,
"TicketID"=>"55",
"TicketNumber"=>"2018010410000261"
})
end
it 'can create ticket without attachment' do
params = {
ticket: {
title: 'New ticket',
queue: 2,
state: 'new',
priority: 3,
customer_user: 'andrej',
customer_id: 'aaaaa'
},
article: {
from: 'sender@gmail.com',
subject: 'Hello World!',
body: 'Hello body!',
}
}
VCR.use_cassette 'ticket_create_no_attachment_success' do
@result = Tessera::Ticket.create(params)
end
expect(@result).to eq({
"ArticleID"=>170,
"TicketID"=>"56",
"TicketNumber"=>"2018010410000279"
})
end
end
end
|
class CreateAggregatedPageViews < ActiveRecord::Migration
def self.up
create_table :aggregated_page_views do |t|
t.column :owner_type, :string, :null => false
t.column :owner_id, :int, :null => false
t.column :period, :string, :null => false
t.column :start_date, :date, :null => false
t.column :views, :int, :null => false
t.column :user_id, :int
end
add_index :aggregated_page_views, [:user_id, :period], :name => 'aggregated_page_views_user_id_period_index'
add_index :aggregated_page_views, :views
end
def self.down
drop_table :aggregated_page_views
end
end
|
module PageObjects
class Application
def initialize
@pages = {}
end
def instagram
@pages[:instagram] ||= PageObjects::Pages::InstagramPage.new
end
def explore_tags
@pages[:explore_tags] ||= PageObjects::Pages::ExploreTagsPage.new
end
end
end |
require 'rails_helper'
describe ContactController do
let(:valid_params) do
{ contact_form: {
email: "valid@email.com",
name: "Customer",
message: "Valid message!"
}
}
end
let(:invalid_params) do
{ contact_form: {
email: "",
name: "",
message: ""
}
}
end
it "#new responds with 200" do
get :new
expect(response).to have_http_status 200
end
context "#send_question with valid params" do
it "redirects to contact_new_path when params are valid" do
post :send_question, params: valid_params
expect(response).to redirect_to thank_you_path
end
it "sends contact e-mail with an instance of contact form" do
expect(ContactMailer).to receive(:contact_email)
.with(an_instance_of(ContactForm))
.and_return(double("mailer", deliver: true))
post :send_question, params: valid_params
end
end
context "#send_question with invalid params" do
it "doesn't send an e-mail" do
expect(ContactMailer).to_not receive(:contact_email)
post :send_question, params: invalid_params
end
end
end
|
# Require the airbrake gem in your App.
# # ---------------------------------------------
# #
# # Rails 3 - In your Gemfile
# # gem 'airbrake'
# #
# # Rails 2 - In environment.rb
# # config.gem 'airbrake'
# #
# # Then add the following to config/initializers/errbit.rb
# # -------------------------------------------------------
#
if Rails.env == 'development'
Airbrake.configure do |config|
config.api_key = '1a8bbd30bd1df1e4a471f031e54222d7'
config.host = '172.16.0.73'
config.port = 3000
config.secure = config.port == 443
config.development_environments = []
end
end
|
require_relative "test_helper"
class W3i::SessionDataTest < Test::Unit::TestCase
def setup
@client_options = {
:device_generation_info => "iPhone4,1",
:os_version => "1.1",
:client_ip => "127.0.0.2",
:udids => {
W3i::IOSUDID => '13112312312312'
},
:app_id => 100,
:api_host => 'api.example.com'
}
end
def test_session_data
data = File.read("#{FIXTURES}/session.json")
FakeWeb.allow_net_connect = 'http://api.example.com'
FakeWeb.register_uri(:post, "http://api.example.com/PublicServices/MobileTrackingApiRestV1.svc/Session/Get", :body => data, :content_type => "application/json")
@client = W3i::Client.new(@client_options)
assert_equal('2791019971', @client.session.session_id)
assert_equal('472658300', @client.session.w3i_device_id)
end
end
|
class MeetingTemplate < ApplicationRecord
has_many :meeting_template_details
has_many :clubs_meeting_templates
end
|
class ParkParticipant
def initialize(participant:, user:)
@participant = participant
@user = user
end
def call
call = create_call
if connect_call_to_conference(call).success?
call.transition_to(:initiated)
Result.success
else
Result.failure("Failed to update call")
end
end
private
attr_reader :participant, :user, :adapter
def connect_call_to_conference(call)
ConnectCallToConference.new(call: call, sids: [participant.sid]).call
end
def create_call
IncomingCall.create(user: user).tap do |call|
call.add_participant(phone_number: participant.phone_number, sid: participant.sid)
end
end
end
|
module ArchService
class Response
attr_reader :message
def initialize(message: "", success: false)
@success = success
@message = message
end
def success?
@success
end
def flash
flash_type = :notice if success?
flash_type ||= :error
flash = { flash_type => @message }
end
end
end |
require 'rails_helper'
RSpec.describe Api::UsersController, type: :controller do
describe 'POST #create' do
context 'with invalid params' do
it "validates the presence of the user's username and password" do
post :create, params: { user: { username: 'Batman@supermansucks.net', password: '' }}
expect(:errors).to be_present
end
end
it 'validates that the password is at least 6 charcters long' do
post :create, params: { user: { username: 'Superman@batmansucks.org', password: 'short'}}
expect(:erros).to be_present
end
end
context 'with valid params' do
it 'logs in the user' do
post :create, params: { user: { username: 'Batman@supermansucks.net', password: 'password'}}
user = User.find_by_username('Batman@supermansucks.net')
expect(session[:session_token]).to eq(user.session_token)
end
end
end
|
module TeamTaskMutations
MUTATION_TARGET = 'team_task'.freeze
PARENTS = ['team'].freeze
module SharedCreateAndUpdateFields
extend ActiveSupport::Concern
included do
argument :label, GraphQL::Types::String, required: true
argument :description, GraphQL::Types::String, required: false
argument :order, GraphQL::Types::Int, required: false
argument :fieldset, GraphQL::Types::String, required: false
argument :required, GraphQL::Types::Boolean, required: false
argument :task_type, GraphQL::Types::String, required: false, camelize: false
argument :json_options, GraphQL::Types::String, required: false, camelize: false
argument :json_schema, GraphQL::Types::String, required: false, camelize: false
argument :keep_completed_tasks, GraphQL::Types::Boolean, required: false, camelize: false
argument :associated_type, GraphQL::Types::String, required: false, camelize: false
argument :show_in_browser_extension, GraphQL::Types::Boolean, required: false, camelize: false
argument :conditional_info, GraphQL::Types::String, required: false, camelize: false
argument :options_diff, JsonStringType, required: false, camelize: false
end
end
class Create < Mutations::CreateMutation
include SharedCreateAndUpdateFields
argument :team_id, GraphQL::Types::Int, required: true, camelize: false
end
class Update < Mutations::UpdateMutation
include SharedCreateAndUpdateFields
end
class Destroy < Mutations::DestroyMutation
argument :keep_completed_tasks, GraphQL::Types::Boolean, required: false, camelize: false
end
end
|
class Participate < ApplicationRecord
belongs_to :user
belongs_to :event
validates :user_id, presence: true
validates :event_id, presence: true
#1ユーザー1回まで
validates_uniqueness_of :event_id, scope: :user_id
end |
# Affiche une chaîne de caractère
puts "On va compter le nombre d'heures de travail à THP"
# Affiche une chaîne de caractère en ajoutant le résultant d'une opération grâce à la combinaison de symbole #{}.
# En l'occurence le nombre d'heures de travail pendant la formation THP : 550
puts "Travail : #{10 * 5 * 11}"
# Idem avec conversion en minutes : 33 000
puts "En minutes ça fait : #{10 * 5 * 11 * 60}"
# Affiche seulement une chaîne de caractère.
puts "Et en secondes ?"
# Affiche le résultat d'une opération : 1980000 secondes de travail au sein de THP.
puts 10 * 5 * 11 * 60 * 60
# Affiche seulement une chaîne de caractère.
puts "Est-ce que c'est vrai que 3 + 2 < 5 - 7 ?"
# Vérifies si 3 + 2 est bien inférieur à 5 - 7. L'interpréteur affiche false car c'est bien évidemment faux. 5 est bien supérieur à -2.
puts 3 + 2 < 5 - 7
# Affiche une chaîne de caractère puis le résultat d'une opération : 5.
puts "Ça fait combien 3 + 2 ? #{3 + 2}"
# Affiche une chaîne de caractère puis le résultat d'une opération : -2.
puts "Ça fait combien 5 - 7 ? #{5 - 7}"
# Affiche une chaîne de caractère qui reprend ce que j'ai dis juste un peu plus haut !
puts "Ok, c'est faux alors !"
# Cétacé dit le crabe. Affiche une chaîne de caractère.
puts "C'est drôle ça, faisons-en plus :"
# Affiche une chaîne de caractère puis le résultat du test : est-ce que 5 est supérieur à -2. Evidemment oui, on observe donc true dans la console.
puts "Est-ce que 5 est plus grand que -2 ? #{5 > -2}"
# Cette fois on test si 5 est supérieur OU bien égal à -2. Le résultat reste vrai.
puts "Est-ce que 5 est supérieur ou égal à -2 ? #{5 >= -2}"
# Dans ce cas on test si 5 est inférieur ou égal à -2. Le résultat est donc faux.
puts "Est-ce que 5 est inférieur ou égal à -2 ? #{5 <= -2}" |
require_relative 'Fenetre'
load 'FenetreChargement.rb'
class FenetreChoixChargement < Fenetre
@boutonPrecedent
attr_reader :boutonPrecedent
public_class_method :new
# Fenetre affichant les boutons de selection d'une reprise de partie du mode edition ou du mode normal.
#
# * *Args* :
# - +tabSave+ -> Matrice ou sont contenue les sauvegardes.
# - +jeu+ -> Session de jeu actuel du joueur
#
def initialize(tabSave,jeu)
super()
@fenetre.set_title("Choix de chargement")
@fenetre.set_window_position(Gtk::Window::POS_CENTER)
@boutonPrecedent = Gtk::Button.new('Precedent')
@boutonNormal = Gtk::Button.new('Charger une grille normale')
@boutonEdition = Gtk::Button.new('Charger une grille du mode Edition')
@boutonPrecedent.set_size_request(-1, 50)
@boutonPrecedent.signal_connect('clicked'){
puts "> Accueil"
EcranAccueil.new(jeu, position())
@fenetre.hide_all()
}
@boutonNormal.signal_connect('clicked'){
FenetreChargement.new(tabSave,jeu,0)
@fenetre.hide_all()
}
@boutonEdition.signal_connect('clicked'){
FenetreChargement.new(tabSave,jeu,1)
@fenetre.hide_all()
}
#A modifier
vBox = Gtk::VBox.new(false, 0)
vBox.set_border_width(5)
vBox.pack_start(@boutonNormal, true, true, 0)
vBox.pack_start(@boutonEdition, true, true, 0)
vBox.pack_start(@boutonPrecedent, true, true, 0)
@fenetre.add(vBox)
@fenetre.show_all
end
end
|
class Item < ApplicationRecord
# 出品品
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to :category
belongs_to :condition
belongs_to :shipping_burden
belongs_to :prefecture
belongs_to :days_to_ship
belongs_to :user
has_one :purchase, dependent: :destroy
has_many_attached :images, dependent: :destroy
# 商品名は40文字まで
validates :name, length: { maximum: 40 }
# 商品説明は1000文字まで
validates :description, length: { maximum: 1000 }
# 選択肢が"---"の時は保存できない
validates :category_id, :condition_id, :shipping_burden_id, :prefecture_id, :days_to_ship_id, numericality: { other_than: 1 }
# priceの数値が半角のみで300以上 9,999,999以下
validates :price, numericality: { greater_than_or_equal_to: 300, less_than_or_equal_to: 9_999_999 }
# 記入必須
with_options presence: true do
validates :name, :description, :category_id, :condition_id, :shipping_burden_id, :prefecture_id, :days_to_ship_id,
:price, :images
end
end
|
require 'spec_helper'
describe ApplicationController do
controller do
def test_signed_in?
signed_in?
end
end
let(:user) { create(:user) }
before do
# Substitute to actually logging in via sign_in_request.
cookies[:remember_token] = user.remember_token
end
describe "#url_options" do
subject { controller.url_options }
it { should have_key(:locale) }
end
describe "#handle_unverified_request" do
let(:signed_in) { controller.test_signed_in? }
context "before session hijack" do
specify "user should be signed in" do
signed_in.should be_true
end
end
context "after session hijack" do
before { controller.handle_unverified_request }
specify "user should be signed out" do
signed_in.should be_false
end
end
end
end |
class Admins::EventSubmissionsController < ApplicationController
before_action :authenticate_user!, only: [:index, :destroy]
before_action :is_admin, only: [:index, :destroy]
def index
@events_submissions = Event.where(validated: nil)
end
def show
@event = Event.find(params[:id])
@admin = User.find(@event.admin.id)
@attendances = Attendance.where(event_id: @event.id)
end
def update
@event = Event.find(params[:id])
@event.update(validated: params[:decision])
redirect_to admins_event_submissions_path
end
private
def is_admin
unless current_user.admin == true
redirect_to root_path
end
end
end
|
#!/usr/bin/env ruby -wKU
# Bilal Syed Hussain
# encoding: utf-8
# Update BookCrawler db from Delicious Library 2's csv
require 'sqlite3'
require "csv"
require "pp"
DB = File.expand_path "~/Desktop/Crawler.sqlite"
csv_file = File.expand_path "~/dl.csv"
db = SQLite3::Database.new( DB )
db.results_as_hash = true
# = for title does not work for some reason
Query =<<-SQL
Select
date('2001-01-01','+' || be.ZCUSTOMDATE || ' second') as RealDate, ZCUSTOMDATE,
ZISBN, ZISBN13,
ZTITLE, ZSERIES,
ZGENRE, ZFORMAT,
ZPRICE,
ZWasRead, ZDateRead,
ZOWN
from ZBOOKEDITION be
join ZBOOK b on b.ZMAINEDITION = be.Z_PK
where b.ZTITLE like ? or be.ZISBN == ? or be.ZISBN like ? or be.ZISBN13 == ?
SQL
def find_missing(db,file)
missing = []
CSV.foreach(file, headers:true ) do |row|
# stmt.bind_params( row['title'],row['i.s.b.n.'],row['i.s.b.n.'])
title = row['title'].to_s.strip
isbn = row['i.s.b.n.'].to_i
# pp title
results = db.execute(Query, [title,isbn,row['i.s.b.n.'], isbn])
if !results || results == []
missing << title
# pp isbn
# pp row['i.s.b.n.']
end
end
return missing
end
# Get row data
def get_results(db,file)
CSV.foreach(file, headers:true ) do |row|
next unless row
title = row['title'].to_s.strip
isbn = row['i.s.b.n.'].to_i
results = db.execute(Query, [title,isbn,row['i.s.b.n.'], isbn])
next if !results || results == []
results = results[0]
yield row, results
end
end
UpdateDates = <<-SQL
Update ZBOOKEDITION
Set ZCUSTOMDATE = ?
WHERE ZISBN == ?
SQL
def update_dates(db,file)
get_results(db,file) do |csv_row, db_results|
str_date = Time.parse(row['purchase date']) - Time.parse('2001-01-01')
results = db.execute(UpdateDates, [str_date.to_i,results['ZISBN']])
puts results
end
end
UpdateGenres = <<-SQL
Update ZBOOK
Set ZGENRE = ?
WHERE ZTITLE == ?
SQL
def update_genres(db,file)
get_results(db,file) do |csv_row, db_results|
results = db.execute(UpdateGenres, [csv_row['genres'],db_results['ZTITLE']])
puts results
end
end
UpdateFormats = <<-SQL
Update ZBOOKEDITION
Set ZFORMAT = ?
WHERE ZISBN == ?
SQL
def update_formats(db,file)
get_results(db,file) do |csv_row, db_results|
results = db.execute(UpdateFormats, [csv_row['format'],db_results['ZISBN']])
puts results
end
end
UpdatePrice = <<-SQL
Update ZBOOKEDITION
Set ZPRICE = ?
WHERE ZISBN == ?
SQL
def update_price(db,file)
get_results(db,file) do |csv_row, db_results|
next unless csv_row['retail price']
price = csv_row['retail price'].gsub(/\W+/, '').to_f/100
results = db.execute(UpdatePrice, [price,db_results['ZISBN']])
puts results
end
end
UpdateRead = <<-SQL
Update ZBOOK
Set ZWasRead = 1,
ZDateRead = '-63114076800'
WHERE ZTITLE == ?
SQL
def update_read(db,file)
get_results(db,file) do |csv_row, db_results|
next unless csv_row['played / read']
read = csv_row['played / read'].to_i
if read == 1 then
results = db.execute(UpdateRead, db_results['ZTITLE'])
puts results
end
end
end
UpdateOwn = <<-SQL
Update ZBOOKEDITION
Set ZOWN = 1
WHERE ZISBN == ?
SQL
def update_own(db,file)
get_results(db,file) do |csv_row, db_results|
next unless db_results
results = db.execute(UpdateOwn, db_results['ZISBN'])
puts results
end
end
# find_missing db, csv_file
# update_dates db, csv_file
# update_genres db, csv_file
# update_formats db, csv_file
# update_price db, csv_file
update_read db, csv_file
update_own db, csv_file |
class UserMailer < ActionMailer::Base
default from: "email@example.com"
def empty_mail
mail to: "eytanfb@gmail.com"
end
end
|
class CreatePurchases < ActiveRecord::Migration[5.1]
def change
create_table :purchases do |t|
t.integer :seller_id #, index: true, foreign_key: true
t.integer :buyer_id #, index: true, foreign_key: true
t.integer :origin_id
t.integer :product_id
t.integer :quantity, default: 1
t.float :total_price
t.integer :buyer_score
t.integer :seller_score
t.boolean :was_shipped, default: false
t.boolean :was_delivered, default: false
t.timestamps
end
end
end |
class AddFirstDateToRepeatingClasses < ActiveRecord::Migration
def change
add_column :repeating_classes, :first_date, :date
end
end
|
class UserMailer < ActionMailer::Base
default from: "GrowBio <shane@grow.bio>"
def signup_email(user)
@user = user
@twitter_message = "Biomaterial kits, tutorials, and more! Excited for #growbio to launch."
mail(:to => user.email, :subject => "Thanks for signing up! | GrowBio")
end
end
|
require "pry"
require_relative "./creatable"
class Deck
include Creatable
attr_reader :cards
def initialize
@cards = create_deck
end
def choose_card
cards.delete_at(rand(cards.length))
end
end
class Card
attr_reader :rank, :suit
def initialize(suit, rank)
@rank = rank
@suit = suit
end
end
|
# frozen_string_literal: true
# This adds Swagger Api Documentation to the controllers.
module Swaggable
extend ActiveSupport::Concern
included do
begin
klass = self.name.split("::").insert(-2, "Swagger").join("::")
self.include klass.constantize
rescue NameError
logger.warn("Documentation error: #{klass} not found for #{self.name}")
end
end
end
|
class AddMessageNumberToMessage < ActiveRecord::Migration[5.2]
def change
add_column :messages, :message_number, :integer
end
end
|
require './helpers/persistence_handler'
require './helpers/file_system_manager'
class Administration_Manager
PATH_REGEX = /^(\/.*?\/)[^\/]*?\.\S/
FILE_REGEX = /^\/.*?\/([^\/]*?\.\S*)/
def initialize
@persistence_handler = PersistenceHandler.new
@filesystem_manager = FileSystemManager.new
end
def add_software(name, command, desc)
@persistence_handler.add_software(name, command, desc)
end
# @return [string]
def hosts?
@persistence_handler.hosts?
end
# @return [string]
def sudo?
@persistence_handler.sudo?
end
# @return [string]
def app_installpath?
@persistence_handler.app_installpath?
end
# @return [string]
def vm_installpath?
@persistence_handler.vm_installpath?
end
# @return [array]
def ansible_config?
@persistence_handler.ansible_config?
end
# @return [array]
def configuration?
@persistence_handler.configuration?
end
# @return [string]
def password?
@persistence_handler.password?
end
# @return [string]
def user?
@persistence_handler.user?
end
# @return [string]
def logfile_path?
@persistence_handler.logfile?
end
def ubuntu64?
@persistence_handler.ubuntu64?
end
def ubuntu32?
@persistence_handler.ubuntu32?
end
def update_ansible_config(hosts, sudo)
@persistence_handler.update_ansible_config(hosts, sudo)
end
def update_vagrant_config(user, password)
@persistence_handler.update_vagrant_config(user, password)
end
def update_general_config(app_path, vm_path)
@persistence_handler.update_general_config(app_path, vm_path)
end
def update_log_config(log)
@persistence_handler.update_log_config(log)
end
def update_standardmachines(ubuntu32, ubuntu64)
@persistence_handler.update_standardmachines_config(ubuntu32, ubuntu64)
end
def create_logfile(path_filename)
if (path_filename.to_s.strip.length != 0)
matching = path_filename.match(PATH_REGEX)
file_path = matching.captures
matching = path_filename.match(FILE_REGEX)
file_name = matching.captures
@filesystem_manager.create_folder(file_path[0].to_s)
@filesystem_manager.create_file(file_path[0].to_s + file_name[0].to_s)
end
end
def write_log(content)
write_option = 'w'
installpath = @persistence_handler.logfile?
open(installpath, write_option) { |i|
i.write(content)
}
end
def log_content?
@filesystem_manager.file_content?(@persistence_handler.logfile?)
end
def delete_log
@filesystem_manager.delete_file_content(@persistence_handler.logfile?.value)
end
end |
FactoryGirl.define do
factory :gem_spec do
sequence :name do |n|
"ruby_spec#{n}"
end
info "SomeInfo"
current_version "1.2.3"
current_version_downloads 22
total_downloads 23
rubygem_uri "SomeURI"
documentation_uri "SomeDocURI"
source_code_uri "source_code_uri"
homepage_uri "homepage_uri"
authors "mr tickle"
end
end
|
require 'oystercard'
describe Oystercard do
let(:entry_station) {double(:entry_station)}
let(:exit) {double(:exit_station)}
describe "balance" do
it "#must have no money on card" do
# card = Oystercard.new
expect(subject.balance).to eq 0
end
end
it "#is able to top" do
expect(subject.top_up(Oystercard::MAX_CAPACITY)).to eq Oystercard::MAX_CAPACITY
end
it "#empty - journeys_history" do
expect(subject.journey_history).to be_empty
end
it "#maximum limit on card is eq 90" do
oyster = Oystercard.new(Oystercard::MAX_CAPACITY)
expect { oyster.top_up(Oystercard::MINIMUM_AMOUNT) }.to raise_error "amount more than #{Oystercard::MAX_CAPACITY}"
end
it "#touch_in" do
subject.top_up(Oystercard::MAX_CAPACITY)
expect(subject.touch_in(entry_station)).to eq "Welcome to #{entry_station}"
end
it "#touch_out" do
expect(subject.touch_out(exit)).to eq "touching out"
end
it "#in_journey" do
subject.top_up(Oystercard::MAX_CAPACITY)
subject.touch_in(entry_station)
expect(subject.in_journey?).to eq true
end
it "#not in_journey" do
subject.touch_out(exit)
expect(subject.in_journey?).to eq false
end
describe "#journey history" do
it "touching in and out" do
subject.top_up(Oystercard::MAX_CAPACITY)
subject.touch_in(entry_station)
subject.touch_out(exit)
expect(subject.journey_history).to eq [{entry: @entry_station, exit: exit}]
end
end
it "#raises error" do
expect {raise 'not enough amount on card'}.to raise_error
end
it "#charging amount " do
expect {subject.touch_out(exit)}.to change{subject.balance}.by (- Oystercard::MINIMUM_AMOUNT)
end
it 'expects card to remember entry station' do
subject = Oystercard.new
subject.top_up(Oystercard::MAX_CAPACITY)
expect(subject.touch_in(entry_station)).to eq "Welcome to #{entry_station}"
end
it "starts with an #empty journey" do
expect(subject.journey_history).to eq []
end
end
|
require_relative "./spec_helper"
describe "Customer" do
describe "invoices" do
it "will return the correct customer invoice" do
customer = Customer.create(id: "15")
invoice = Invoice.create(customer_id: "15")
expect(customer.invoices).to eq([invoice])
end
end
end |
class Feedback < ActiveRecord::Base
belongs_to :user
has_many :comments
has_many :votes
has_many :notifications
has_many :images, dependent: :destroy
attr_accessible :title, :details, :status, :address, :latitude, :longitude, :last_acted_at, :reported_by, :abuse_reason, :abuse_status, :user_id, :created_at
# geocoded_by :address
# after_validation :geocode, :if => :address_changed?
# reverse_geocoded_by :latitude, :longitude
# after_validation :reverse_geocode, :if => :address_changed?
def timestamp
created_at.strftime('%d %B %Y %H:%M:%S')
end
end
|
#! /usr/bin/env ruby
require 'rubygems'
require 'nokogiri'
require 'json'
require 'socket'
require 'uri'
require 'open-uri'
require 'despotlistback/options'
require 'despotlistback/convert'
require 'despotlistback/xspf'
### Despot ## our interface to despotify-gateway
class Despot
attr_accessor :username, :password, :host, :port
attr_accessor :track_cache, :outputdir, :metacache, :metafile
attr_accessor :socket, :playlists, :tracks
def initialize(username, password, host, port, outputdir)
@host = host
@port = port
@username = username
@password = password
@outputdir = outputdir
@metacache = {} # in-memory transient cache for now
@socket = TCPSocket.new(host, port)
@playlists = []
@tracks = {}
@track_cache = {}
end
def init_metacache
end
def album_metadata(aid)
if not @metacache[aid].nil? then
return @metacache[aid]
end
# not cached, we need to look it up from the web API
aid_uri = id2uri(aid)
$stderr.puts "W #{aid} #{aid_uri}"
uri = "http://ws.spotify.com/lookup/1/?uri=spotify:album:#{aid_uri}"
begin
xml_meta = open(uri).read
rescue
$stderr.puts "!! http://ws.spotify.com/lookup/1/?uri=spotify:album:#{aid_uri} #{aid}"
# return nil if we can't read from the API
return nil
end
$stderr.puts xml_meta
aid_meta = {}
aid_meta[:id] = Hash.new()
if not xml_meta.nil? then
xml_dom = Nokogiri::XML(xml_meta)
if xml_dom.nil? then
return nil
end
# I hate having to do this
xml_dom.remove_namespaces!
# collect all the album metadata bits here
xml_dom.search("/album/id").each do |idnode|
id_type = idnode['type']
aid_meta[:id][id_type] = idnode.inner_text.strip
end
else
return nil
end
@metacache[aid] = aid_meta
return aid_meta
end
def cmd(command, *params)
cl = [command, params].flatten.join(' ') + "\n"
$stderr.puts "> #{cl.inspect}"
@socket.send(cl, 0)
response = ""
x = nil
until x == "\n" do
x = @socket.recv(1)
response = response + x
end
$stderr.puts "< #{response.inspect}"
code, length, status, text = response.split(' ', 4)
if code.to_i != 200 then
# raise ArgumentError, text
return [dom, code, length, status, text, payload]
end
payload = nil
dom = nil
if length.to_i > 0 then
payload = @socket.read(length.to_i)
dom = Nokogiri::XML(payload)
if dom.nil? then
# raise ArgumentError, "XML does not parse"
end
end
return [dom, code, length, status, text, payload]
end
def login
r = self.cmd("login", @username, @password)
$stderr.puts r.inspect
end
def load_all_playlists
$stderr.puts("L /pl/all")
dom, junk = self.cmd("playlist", "0000000000000000000000000000000000")
playlist_ids = dom.at("//items").inner_text.strip.split(',').map{|pid| pid.strip}
self.load_playlists(playlist_ids)
end
def load_playlists(playlist_ids)
playlist_ids.each do |p|
$stderr.puts("L /pl/#{p[0..33]}")
pl = self.load_playlist(p[0..33])
if not pl.nil? then
self.write_playlist(pl)
end
end
end
def load_playlist(pid)
dom, junk = self.cmd("playlist", pid)
if dom.nil? then
raise ArgumentError, junk.inspect
end
user = dom.at("//user").inner_text.strip
# if user != @username then
# $stderr.puts "We don't handle subscribed playlists properly yet, sorry!"
# return nil
# end
name = dom.at("//name").inner_text.strip
# need the map/strip because occasional tids have a \n prefix
track_ids = dom.at("//items").inner_text.strip.split(",").map{|tid| tid.strip}
# fetch information about our tracks from the API (or not the API, depending)
tracks = track_ids.map {|tid| self.load_track(tid)}
$stderr.puts "+ playlist #{name}"
x = {:name => name, :pid => pid, :tracks => tracks, :user => user}
@playlists << x
return x
end
def load_track(tid)
if not @track_cache[tid].nil? then
return @track_cache[tid]
end
if tid =~ /^spotify:local/ then
# we can't look this track up remotely
s, l, artist, album, title, duration = tid.split(/:/).map{|i| URI.unescape(i.gsub(/\+/,' '))}
track = {:title => title, :artist => artist, :album => album, :tid => tid, :uri => tid, :duration => (1000*duration.to_i).to_s}
@track_cache[tid] = track
return track
end
if tid =~ /^spotify:track:(.*)/ then
$stderr.puts "TU #{tid}"
end
# trim to 32 hex characters
tid = tid[0..31]
dom, junk = self.cmd("browsetrack", tid)
track = {}
success = dom.at("//total-tracks").inner_text.to_i
if success > 0 then
title = dom.at("//track/title").inner_text.strip
artist = dom.at("//track/artist").inner_text.strip
artist_id = dom.at("//track/artist-id").inner_text.strip
album = dom.at("//track/album").inner_text.strip
album_id = dom.at("//track/album-id").inner_text.strip
index = dom.at("//track/track-number").inner_text.strip
duration = dom.at("//track/length").inner_text.strip
uri = id2uri(tid)
if uri.nil? then
$stderr.puts "!! #{tid} doesn't map to a URI somehow"
uri = "_whoops_#{tid}_"
end
almeta = self.album_metadata(album_id)
track = {:title => title, :artist => artist, :album => album, :tid => tid, :uri => uri, :index => index, :duration => duration, :aid => album_id, :album_meta => almeta, :arid => artist_id}
eid = dom.at("//track/external-ids/external-id")
if not eid.nil? and eid['type'] == 'isrc' then
track[:isrc] = eid['id']
end
$stderr.puts track.inspect
@track_cache[tid] = track
end
return track
end
end
# xspf blindly passes unescaped strings to eval in single quotes. Because ... yes. Why not.
class String
def sq
self.gsub(/'/, "\\\\'")
end
end
username, password = $options[:login].split(':', 2)
dsp = Despot.new(username, password, $options[:host], $options[:port], $options[:output])
dsp.login()
# Has the user specified any playlists to load?
playlists = $options[:playlist].to_s.split(',')
# backward compatibility
playlists << ARGV
# We might have [[]] here which isn't what we want
playlists.flatten!
if playlists.size == 0 then
dsp.load_all_playlists()
else
dsp.load_playlists(playlists.flatten)
end
|
Rails.application.routes.draw do
namespace :woa, :path => WizardOfAwes.config.snippet_route_prefix do
resources :snippets, :except => :show
end unless WizardOfAwes.config.snippet_route_prefix.blank?
end |
require 'date'
class Meetup
DAYS = { first: 0, second: 1, third: 2, fourth: 3, last: -1, teenth: :teenth }
def initialize(month, year)
@days = generate_all_days_of_month(month, year)
end
def day(weekday, descriptor)
if descriptor == :teenth
# select only the days ranging from 13th to 19th of month
@days.to_a[12..18].find { |day| day.send("#{weekday}?") }
else
good_days = @days.select { |day| day.send("#{weekday}?") }
good_days[DAYS[descriptor]]
end
end
private
def generate_all_days_of_month(month, year)
first_day_of_month = Date.new(year, month)
last_day_of_month = Date.new(year, month).next_month - 1
first_day_of_month..last_day_of_month
end
end
module BookKeeping
VERSION = 1
end
|
db_conf = Hash[app.database]
db_conf.delete 'environments'
db_conf['database'] = db_conf.delete 'name'
db_type = db_conf.delete('type').downcase
# create database user
case db_type
when /^postgres/
if %w(localhost 127.0.0.1).include? app.database.host
db_conf.delete 'host'
end
include_recipe 'postgresql::server'
psql_create_user app.user.name
psql_create_database app.database.name do
owner app.user.name
end
else
raise "You must specify a valid database type in your application config"
end
# Ensure monit has a monitor of the DB
template "/etc/monit/conf.d/#{db_type}.conf" do
source "monit/#{db_type}.conf.erb"
owner 'root'
group 'root'
mode 0644
notifies :reload, 'service[monit]', :delayed
end
file "#{app.config_path}/database.yml" do
owner app.user.name
group app.user.group
mode 0600
content YAML.dump(Hash[app.database.environments.map {|env, conf| [env, db_conf.merge(conf).to_hash] }])
end
|
class AddDenominacionIdToVinos < ActiveRecord::Migration
def change
add_column :vinos, :denominacion_id, :integer
end
end
|
require 'spec_helper'
describe 'kerberos::realm', :type => :define do
context 'on a Debian OS' do
let :facts do
{
:osfamily => 'Debian',
:concat_basedir => '/dne',
}
end
let :title do
'example.org'
end
let :pre_condition do
'include kerberos'
end
describe 'with no parameters' do
it { should raise_error(Puppet::Error, /Must pass kdc to Kerberos::Realm\[example.org\]/) }
end
describe 'with the minimum kdc server string' do
let :params do
{
:kdc => 'kerberos.example.org',
}
end
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with(
'target' => 'krb5_config',
'order' => '04exampleorg'
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ EXAMPLE.ORG = \{$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = kerberos.example.org$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').without_content(
%r{^ master_kdc = .*$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').without_content(
%r{^ admin_server = .*$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').without_content(
%r{^ default_domain = .*$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').without_content(
%r{^ kpasswd_server = .*$}
) }
end
describe 'with multiple kdc servers' do
let :params do
{
:kdc => [
'kerberos.example.org',
'another.krb5.example.org:80',
'backup.kerberos.example.org'
]
}
end
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = kerberos.example.org$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = another.krb5.example.org:80$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = backup.kerberos.example.org$}
) }
end
describe 'with a master kdc server' do
let :params do
{
:kdc => 'kerberos.example.org',
:master_kdc => 'master.kerberos.example.org'
}
end
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ master_kdc = master.kerberos.example.org$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = kerberos.example.org$}
) }
end
describe 'with an admin server' do
let :params do
{
:kdc => 'kerberos.example.org',
:admin_server => 'admin.kerberos.example.org'
}
end
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ admin_server = admin.kerberos.example.org$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = kerberos.example.org$}
) }
end
describe 'with a default domain' do
let :params do
{
:kdc => 'kerberos.example.org',
:default_domain => 'example.org'
}
end
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ default_domain = example.org$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = kerberos.example.org$}
) }
end
describe 'with a kpasswd server' do
let :params do
{
:kdc => 'kerberos.example.org',
:kpasswd_server => 'example.org'
}
end
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kpasswd_server = example.org$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = kerberos.example.org$}
) }
end
end
context 'on a RedHat OS' do
let :facts do
{
:osfamily => 'RedHat',
:concat_basedir => '/dne',
}
end
let :title do
'example.org'
end
let :pre_condition do
'include kerberos'
end
describe 'with no parameters' do
it { should raise_error(Puppet::Error, /Must pass kdc to Kerberos::Realm\[example.org\]/) }
end
describe 'with the minimum kdc server string' do
let :params do
{
:kdc => 'kerberos.example.org',
}
end
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with(
'target' => 'krb5_config',
'order' => '04exampleorg'
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ EXAMPLE.ORG = \{$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = kerberos.example.org$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').without_content(
%r{^ master_kdc = .*$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').without_content(
%r{^ admin_server = .*$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').without_content(
%r{^ default_domain = .*$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').without_content(
%r{^ kpasswd_server = .*$}
) }
end
describe 'with multiple kdc servers' do
let :params do
{
:kdc => [
'kerberos.example.org',
'another.krb5.example.org:80',
'backup.kerberos.example.org'
]
}
end
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = kerberos.example.org$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = another.krb5.example.org:80$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = backup.kerberos.example.org$}
) }
end
describe 'with a master kdc server' do
let :params do
{
:kdc => 'kerberos.example.org',
:master_kdc => 'master.kerberos.example.org'
}
end
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ master_kdc = master.kerberos.example.org$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = kerberos.example.org$}
) }
end
describe 'with an admin server' do
let :params do
{
:kdc => 'kerberos.example.org',
:admin_server => 'admin.kerberos.example.org'
}
end
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ admin_server = admin.kerberos.example.org$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = kerberos.example.org$}
) }
end
describe 'with a default domain' do
let :params do
{
:kdc => 'kerberos.example.org',
:default_domain => 'example.org'
}
end
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ default_domain = example.org$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = kerberos.example.org$}
) }
end
describe 'with a kpasswd server' do
let :params do
{
:kdc => 'kerberos.example.org',
:kpasswd_server => 'example.org'
}
end
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kpasswd_server = example.org$}
) }
it {should contain_concat__fragment('krb5_EXAMPLE.ORG_realm').with_content(
%r{^ kdc = kerberos.example.org$}
) }
end
end
end
|
class Admin::ValueFictionsController < ApplicationController
before_action :load_value_fiction, only: :update
def index
@search = ValueFiction.includes(:fiction).ransack(params[:q])
@value_fictions = @search.result.page(params[:page]).per Settings.per_page.admin.value_fictions
end
def show
end
def update
if @value_fiction.update_attributes value_fiction_params
flash[:success] = t "admin.value_fictions.updated_success"
else
flash[:error] = t "admin.value_fictions.updated_fail"
end
redirect_to admin_value_fictions_path
end
def edit
end
private
def value_fiction_params
params.require(:value_fiction).permit :name, :description
end
def load_value_fiction
@value_fiction = ValueFiction.find_by id: params[:id]
return if @value_fiction
flash[:error] = t "not_found_item"
redirect_to :back
end
end
|
class Membership < ActiveRecord::Base
#Associations
belongs_to :house
belongs_to :person
end
|
require 'test_helper'
class StructuresControllerTest < ActionDispatch::IntegrationTest
setup do
@structure = structures(:one)
end
test "should get index" do
get structures_url
assert_response :success
end
test "should get new" do
get new_structure_url
assert_response :success
end
test "should create structure" do
assert_difference('Structure.count') do
post structures_url, params: { structure: { address: @structure.address, city: @structure.city, country: @structure.country, description: @structure.description, email: @structure.email, full_address: @structure.full_address, latitude: @structure.latitude, longitude: @structure.longitude, name: @structure.name, phone: @structure.phone, slogan: @structure.slogan, street: @structure.street, structure_type_id: @structure.structure_type_id, user_id: @structure.user_id, web: @structure.web } }
end
assert_redirected_to structure_url(Structure.last)
end
test "should show structure" do
get structure_url(@structure)
assert_response :success
end
test "should get edit" do
get edit_structure_url(@structure)
assert_response :success
end
test "should update structure" do
patch structure_url(@structure), params: { structure: { address: @structure.address, city: @structure.city, country: @structure.country, description: @structure.description, email: @structure.email, full_address: @structure.full_address, latitude: @structure.latitude, longitude: @structure.longitude, name: @structure.name, phone: @structure.phone, slogan: @structure.slogan, street: @structure.street, structure_type_id: @structure.structure_type_id, user_id: @structure.user_id, web: @structure.web } }
assert_redirected_to structure_url(@structure)
end
test "should destroy structure" do
assert_difference('Structure.count', -1) do
delete structure_url(@structure)
end
assert_redirected_to structures_url
end
end
|
# frozen_string_literal: true
class Person
attr_accessor :name
# attr_reader :name
# attr_writer :name
def initialize(name)
@name = name
end
end
bob = Person.new('Steve')
bob.name = 'Bob'
puts bob.name
|
class AddDescriptionToTask < ActiveRecord::Migration
def change
add_column :tasks, :description, :text, null: false, default: "Altere este texto para a descrição da tarefa"
end
end
|
# frozen_string_literal: true
# Create card
class Card
SUITS = %w[♠ ♥ ♣ ♦].freeze
PICTURES = %i[J Q K A].freeze
SCORES = { J: 10, Q: 10, K: 10, A: 11 }.freeze
attr_reader :suit, :rank
attr_accessor :score
def initialize(suit, rank)
@suit = suit
@rank = rank
end
def price
@score = (2..10).include?(@rank) ? @rank : SCORES[@rank]
end
def face
"#{rank} #{suit}"
end
end
|
class Dog < ApplicationRecord
belongs_to :owner
belongs_to :breed
validates :name, presence: true, length: {minimum: 2}
end
|
json.array!(@r_links) do |r_link|
json.extract! r_link, :link, :properties
json.url r_link_url(r_link, format: :json)
end
|
Rails.application.routes.draw do
get 'zipping_folders/new'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :zipping_folders, only: [:create]
root 'zipping_folders#new'
end
|
class HomesController < ApplicationController
def show
@visits = Visit.all
end
#%B: full month name "January", #%d: Day of Month 01-31, #%Y:2007
def visits_by_day
render json: Visit.group_by_day(:visited_at, format: "%B %d, %Y").count
end
end
|
require "test_helper"
class WeekendsInCookieBeforeLoginTest < ActionDispatch::IntegrationTest
def test_storing_and_recovering_weekend_from_cookie_when_front_user_created
# Creating the Weekend
assert_difference("Weekend.count", 1) do
post(
"/front/weekends",
params: {
weekend: {
body: "This is the body of the weekend"
}
}
)
end
assert_redirected_to :new_front_front_user
weekend = Weekend.last
assert_nil(weekend.front_user)
# Creating the FrontUser
assert_difference("FrontUser.count", 1) do
post(
"/front/front_users",
params: {
front_user: {
name: "Fermin"
}
}
)
end
assert_redirected_to :my_weekends_front_weekends
front_user = FrontUser.last
weekend.reload
assert_equal(front_user, weekend.front_user)
end
end
|
FactoryBot.define do
factory :habilitacao do
pessoa_id { FactoryBot::create(:pessoa).id }
numero { rand(10 ** 10) }
modalidades { ['A','B','C','D','E'].shuffle.zip(['A','B','C','D','E'].shuffle).sample.join(',') }
validade { FFaker::Time.date+FFaker::Random.rand(1..3).year }
end
end |
maintainer "Kevin McCarthy"
maintainer_email "me@kevinmccarthy.org"
description "Installs and configures redis server"
version "0.3"
recipe "redis", "Install and configure redis"
%w{ubuntu debian redhat centos}.each do |os|
supports os
end
attribute "redis",
:display_name => "redis",
:description => "Hash of redis attributes",
:type => "hash"
attribute "redis/databases",
:display_name => "Number of redis databases",
:description => "The number of redis datbases. The default is 16, the max is infinite, but you should keep it below 1024",
:default => "16"
|
require 'spec_helper'
describe SportsDataApi::Mlb::Teams, vcr: {
cassette_name: 'sports_data_api_mlb_teams',
record: :new_episodes,
match_requests_on: [:host, :path]
} do
let(:teams) do
SportsDataApi.set_key(:mlb, api_key(:mlb))
SportsDataApi.set_access_level(:mlb, 't')
SportsDataApi::Mlb.teams
end
let(:url) { 'http://api.sportsdatallc.org/mlb-t4/teams/2014.xml' }
let(:dodgers_xml) do
str = RestClient.get(url, params: { api_key: api_key(:mlb) }).to_s
xml = Nokogiri::XML(str)
xml.remove_namespaces!
xml.xpath('//team[@abbr=\'LA\']')
end
let(:dodgers) { SportsDataApi::Mlb::Team.new(dodgers_xml) }
subject { teams }
its(:count) { should eq 32 }
it { subject[:"ef64da7f-cfaf-4300-87b0-9313386b977c"].should eq dodgers }
end
|
puts "Enter your name: "
name = gets.chomp() #chomp() takes out the \n
puts ("Hello " + name)
puts "Enter the first number: "
n1 = gets.chomp()
puts "Enter the second number: "
n2 = gets.chomp()
puts (n1.to_f + n2.to_f)
# or n1 = gets.chomp().to_f
friends = Array[2, false, "Martha"]
puts friends
puts friends[2]
puts friends[0,2]
flowers = Array.new
flowers[0] = "rose"
flowers[5] = "violet"
puts flowers # >rose violet
puts flowers.include? "rose" #true
puts flowers.reverse() #violet rose
puts flowers.sort()
#HASHES
states = {
:Pennsylvania => "PA",
"New York" => "NY",
"Oregon" => "OR"
}
puts states
puts states["Oregon"]
puts states[:Pennsylvania]
#METHODS
def hi
puts "Hello User"
end
hi
def sayhito(name)
puts ("Hello " + name)
end
sayhito("Bóris")
def Greet(name="John Doe", age = 0)
puts ("Hello " + name + ", you are " + age.to_s)
end
Greet("Bóris")
def cube(num)
num * num * num
end
puts cube(2)
def cube(num)
num * num * num
5
end
puts cube(2) #print 5
def cube(num)
return num * num * num, 70 #ends method
5
end
puts cube(2) # >8 70
puts cube(2)[0] # >8
#if
ismale = true
istall = true
if ismale and istall
puts "Yep, you're male aaaand tall"
elsif ismale and !istall
puts "Nhe, male but not tall"
elsif !ismale and istall
puts "Wow, female and tall"
else
puts "Nop, no male at all, and not tall either"
end
def max(n1, n2, n3)
if n1 >= n2 and n1 >= n3
return n1
elsif n2 >= n1 and n2 >= n3
return n2
else
return n3
end
end
puts max (1,2,3)
def calc(n1, op, n2)
if op == "+"
return n1 + n2
elsif op == "-"
return n1 - n2
elsif op == "*"
return n1 * n2
elsif op == "/"
return n1 / n2
else
"Invalid operator"
end
end
puts "Enter the first number: "
n1 = gets.chomp().to_f
puts "Enter the second number: "
n2 = gets.chomp().to_f
puts "Enter the operator: "
op = gets.chomp()
puts calc(n1, op, n2)
def get_date_name(day)
day_name = ""
case day
when "mon"
day_name = "Monday"
when "tue"
day_name = "Tuesday"
when "wed"
day_name = "Wednesday"
when "thu"
day_name = "Thursday"
when "fri"
day_name = "Friday"
when "sat"
day_name = "Saturday"
when "sun"
day_name = "Sunday"
else
day_name = "Invalid"
end
return day_name
end
day = gets.chomp()
puts get_date_name(day)
index = 1
while index <= 5
puts index
index += 1
end
secret = "Jax"
guess = ""
limit = 3
out_of_guesses = false
guess_count = 0
while guess != secret && !out_of_guesses
puts "Enter ur guess: "
guess = gets.chomp()
guess_count += 1
if guess_count > limit
out_of_guesses = true
end
end
if out_of_guesses
puts "Loser"
else
puts "U won"
end
friends = ["Kevin", "Roger", "Billy", "Merlin", "Silence"]
for friend in friends do
puts friend
end
friends.each do |friend|
puts friend
end
for index in 0..5
puts index #0 1 2 3 4 5
end
6.times do |index|
puts index
end
def pow(base, pow)
result = 1
pow.times do
result = result * base
end
return result
end
File.open("employees.txt", "r") do |file|
puts file.read().include? "Molly"
puts file.readline()
puts file.readchar()
puts file.readlines()[2]
end
file = File.open("employees.txt", "r")
puts file.read
file.close()
File.open("employees.txt", "a") do |file|
file.write("Oscar, Accouting")
end
File.open("employees.txt", "w") do |file|
file.write("Oscar, Accouting")
end
File.open("index.html", "w") do |file|
file.write("<h1>Hello</h1>")
end
File.open("employees.txt ", "r+") do |file|
file.readline()
file.write("Overridenn")
end
lucky_nums = [4, 8, 12, 16, 42]
begin
lucky_nums["dogs"]
rescue
puts "Error"
end
begin
lucky_nums["dogs"]
num = 10/0
rescue ZeroDivisionError
puts "Error by zero"
rescue TypeError => variable
puts variable
end
class Book
attr_accessor :title, :author, :pages
def initialize(title, author, pages)
@title = title
@author = author
@pages = pages
end
end
book1 = Book.new("Harry Potter", "JK Rowling", 273)
book2 = Book.new("The Lord of the Rings", "JRR Tolkien", 455)
class Student
attr_accessor :name, :major, :gpa
def initialize(name, major, gpa)
@name = name
@major = major
@gpa = gpa
end
def has_honors
if @gpa >= 3.5
return true
end
return false
end
end
student1 = Student.new("New", "Business", 2.6)
student2 = Student.new("Bie", "Art", 3.6)
puts student1.has_honors
class Question
attr_accessor :prompt, :answer
def initialize(prompt, answer)
@prompt = prompt
@answer = answer
end
end
p1 = "Whats L name?\na. Lawliet\nb. Ryuzaak\nc. Unknown"
p2 = "Who is this?\na. Jaws\nb.Scream\nc. Halloween"
questions = [
Question.new(p1, "c"),
Question.new(p2, "b")
]
def run_test(questions)
score = 0
answer = ""
for question in questions
puts question.prompt
answer = gets.chomp()
if answer == question.answer
score += 1
end
end
puts ("You got " + score.to_s + "/" + questions.length().to_s)
end
run_test(questions)
class Chef #superclass
def make_chicken
puts "The chef makes chicken"
end
def make_salad
puts "The chef makes salad"
end
def make_special_dish
puts "The chef makes bbq ribs"
end
end
class ItalianChef < Chef #subclass
def make_special_dish
puts "The chef makes eggplant parm"
end
def make_pasta
puts "The chef makes pasta"
end
end
chef = Chef.new()
chef.make_chicken
italian_chef = ItalianChef.new()
module Tools
def say_hi(name)
puts "Hello #{name}"
end
def say_bye(name)
puts "Bye, #{name}"
end
end
include Tools
Tools.say_bye("Nubia")
# in another file
require_relative "File_name.rb"
include Tools
Tools.say_hi("Ernio") |
class ReleaseController < SecureController
helpers Sinatra::Streaming
before '/*' do
pass if params['splat'][0].blank?
name = params['splat'][0].split('/')[0]
logger.debug("Requests for release: \"#{name}\"")
@release = Release.find_by_name(name)
if @release.nil?
request_halt("Release with name \"#{name}\" does not exists.", 404)
end
end
before '/:name/dependent-releases/*' do
subname = params['splat'][0].split('/')[0]
@subrelease = Release.find_by_name(subname)
if @subrelease.nil?
request_halt("Release with name \"#{subname}\" doesn't exists.", 404)
end
end
before '/:name/orders/*' do
release_order_name = params['splat'][0].split('/')[0]
@release_order = @release.release_orders.find_by_name(release_order_name)
if @release_order.nil?
request_halt("Release Order with name \"#{release_order_name}\" does not exists.", 404)
end
end
['/:name/orders/:order_name/applications/*', '/:name/orders/:order_name/status/*', '/:name/orders/:order_name/results/*'].each do |path|
before path do
app_name, version, __, env_name = params['splat'][0].split('/')
@application = Application.find_by_name(app_name)
if @application.nil?
request_halt("Application with name \"#{app_name}\" does not exists.", 404)
end
return if version.nil?
@avw = @application.versions.find_by_version(version)
if @avw.nil?
request_halt("Application has no version: \"#{version}\".", 404)
end
@roavw = @release_order.release_order_application_with_versions.find_by_application_with_version_id(@avw.id)
if @roavw.nil?
request_halt("Application \"#{app_name}\" in version \"#{version}\" hasn't been added to Release Order \"#{@release_order.name}\"", 404)
end
unless env_name.nil?
@app_env = @application.envs.find_by_name(env_name)
if @app_env.nil?
request_halt("Env \"#{env_name}\" hasn't been added to Application \"#{app_name}\"", 404)
end
@env_for_release_order = @roavw.release_order_application_with_version_envs.find_by_env_id(@app_env.id)
if @env_for_release_order.nil?
request_halt("Env \"#{env_name}\" hasn't been added to Application \"#{app_name}\" in version \"#{version}\" in Release Order \"#{@release_order.name}\"", 404)
end
end
end
end
before '/:name/orders/:order_name/results/:application_name/:version/envs/:env/*' do
@result = @release_order.release_order_results.where(release_order_id: @release_order.id, env_id: @env_for_release_order.env.id, application_id: @application.id, application_with_version_id: @avw.id).first
if @result.nil?
request_halt("Results for release order with name \"#{@release_order.name}\" for application: \"#{@application.name}\" in version \"#{@avw.version}\" for env: \"#{@app_env.name}\" does not exists.", 404)
end
end
get '/' do
param :includeClosedReleases, Boolean, required: false, raise: true
if params[:includeClosedReleases] == true
Release.all.to_json
else
Release.open.to_json
end
end
post '/' do
json = JSON.parse(request.body.read, symbolize_names: true)
release = Release.find_by_name(json[:name])
if release.nil?
status 201
Release.create!(json)
else
request_halt("Release with name \"#{json[:name]}\" exists.", 409)
end
end
get '/:name' do |_name|
@release.to_json
end
delete '/:name' do
status 202
@release.destroy
{ status: 'ok' }.to_json
end
get '/:name/status' do |_name|
status 201
@release.status.to_json
end
patch '/:name/status' do |_name|
status 202
s = JSON.parse(request.body.read, symbolize_names: true)
@release.validate_status(s[:status])
@release.update!(status: s[:status])
@release.to_json
end
put '/:name/dependent-releases/:subname' do |_name, _subname|
Subrelease.create!(release_id: @release.id, subrelease_id: @subrelease.id)
status 202
{ status: 'ok' }.to_json
end
delete '/:name/dependent-releases/:subname' do |_name, _subname|
Subrelease.where(release_id: @release.id, subrelease_id: @subrelease.id).destroy_all
status 202
{ status: 'ok' }.to_json
end
get '/:name/orders' do
param :status, String, in: ReleaseOrder.statuses.map(&:first), required: false, raise: true
param :upcoming, Boolean, required: false, raise: true
@release.get_orders(params).to_json
end
post '/:name/orders' do |name|
status 201
json = JSON.parse(request.body.read, symbolize_names: true)
if @release.closed?
request_halt("Release with name \"#{name}\" is closed, can't add change to it.", 403)
else
ro = @release.release_orders.find_by_name(json[:name])
if ro.nil?
@release.release_orders.create!(json)
status 201
else
request_halt("Release Order with name \"#{json[:name]}\" exists.", 409)
end
end
{ status: 'ok' }.to_json
end
get '/:name/orders/:order_name' do |_name, _order_name|
@release_order.to_json
end
delete '/:name/orders/:order_name' do |_name, _order_name|
status 202
@release_order.destroy
{ status: 'ok' }.to_json
end
get '/:name/orders/:order_name/status' do
@release_order.status.to_json
end
get '/:name/orders/:order_name/applications' do |_name, _order_name|
@release_order.application_with_versions.to_json
end
delete '/:name/orders/:order_name/applications/:application_name' do |_name, _order_name, _application_name|
@release_order.application_with_versions.where(application_id: @application.id).each do |avw|
roavw = @release_order.release_order_application_with_versions.find_by_application_with_version_id(avw.id)
roavw.destroy!
end
status 202
{ status: 'ok' }.to_json
end
post '/:name/orders/:order_name/applications' do |_name, order_name|
status 201
applications_with_version = JSON.parse(request.body.read, symbolize_names: true)
applications_with_version.each do |app|
app_name = app[:application_name]
a = Application.find_by_name(app_name)
if a.nil?
request_halt("Application with name #{app_name} does not exists.", 404)
end
version_name = app[:version_name]
avw = ApplicationWithVersion.find_by_application_id_and_version(a.id, version_name)
if avw.nil?
request_halt("Application with name #{app_name} does not have version: #{version_name}", 404)
end
if @release.closed?
request_halt("Cannot add Application \"#{app_name}\" to Release order \"#{order_name}\" which belongs to closed Release \"#{@release.name}\"", 403)
end
ReleaseOrderApplicationWithVersion.find_or_create_by!(release_order_id: @release_order.id, application_with_version_id: avw.id)
end
{ status: 'ok' }.to_json
end
# dry run - only generate
get '/:name/orders/:order_name/generate_deploy_playbook' do |_name, order_name|
logger_data = { current_user: RequestStore.read(:current_user), request_id: RequestStore.read(:request_id) }
envs = params[:envs] || []
o = @release.release_orders.find_by_name(order_name)
begin
MakePlaybookService.new(o, logger_data).make_playbook!
rescue Errno::ENOENT, Errno::ENOSPC, Errno::EACCES => e
log_msg = "Deployment has failed. Unable to generate deployment playbook for change: #{o.name} due to error: #{e.message}."
request_halt(log_msg, 500)
end
end
get '/:name/orders/:order_name/execute' do |_name, order_name|
response.headers['X-Accel-Buffering'] = 'no'
content_type 'application/octet-stream'
param :stream, Boolean, required: false, is: true, raise: true
stream_to_out = params[:stream] || false
# request is ended before streams ends. Below is necessary to pass request_id and current_user into logs from services run in stream block.
logger_data = { current_user: RequestStore.read(:current_user), request_id: RequestStore.read(:request_id) }
envs = params[:envs] || []
o = @release.release_orders.find_by_name(order_name)
begin
MakePlaybookService.new(o, logger_data).make_playbook!
# catch only errors which were not catch inside MakePlaybookService
rescue Errno::ENOENT, Errno::ENOSPC, Errno::EACCES => e
log_msg = "Unable to generate deployment playbook for change: #{o.name} due to error: #{e.message}."
request_halt(log_msg, 500)
else
logger.info("Deployment playbooks for change: #{@release_order.name} generated.")
end
ArchivePlaybookService.new(o, logger_data).run!
# no request object below
stream do |out|
RunPlaybookService.new(o, envs, out, stream_to_out, logger_data).run!
end
end
get '/:name/orders/:order_name/archive' do |name, order_name|
response.headers['content_type'] = 'application/x-gtar'
attachment("#{name}_release_order_#{order_name}_playbook.tar.gz")
response.write(Marshal.load(@release_order.archive))
end
put '/:name/orders/:order_name/productionize' do |_name, _order_name|
if !@release_order.approvals.empty?
if @release_order.valid_approvals?
@release_order.approved!
else
@release_order.waiting_for_approvals!
@release_order.send_approval_emails
end
else
@release_order.approved!
end
status 204
{ status: 'ok' }.to_json
end
post '/:name/orders/:order_name/approvers' do |_name, _order_name|
approvers = JSON.parse(request.body.read, symbolize_names: true)
approvers.each do |a|
u = User.find_by_email(a[:email])
if u.nil?
request_halt("Approver with email \"#{a[:email]}\" does not exists.", 404)
end
@release_order.approvals.create!(user_id: u.id)
end
status 204
{ status: 'ok' }.to_json
end
delete '/:name/orders/:order_name/approvers/:email' do |_name, _order_name, _email|
u = User.find_by_email(params[:email])
request_halt('Approver with email "email" does not exists.', 404) if u.nil?
@release_order.approvals.where(user_id: u.id).delete_all
status 204
{ status: 'ok' }.to_json
end
get '/:name/orders/:order_name/applications/:application_name/:version/envs' do
@roavw.envs.to_json
end
post '/:name/orders/:order_name/applications/:application_name/:version/envs' do
status 201
json = JSON.parse(request.body.read, symbolize_names: true)
Array.wrap(json).each do |e|
env_name = e[:env_name]
env = @application.envs.find_by_name(env_name)
if env.nil?
request_halt("Env \"#{env_name}\" does not exist for application \"#{@application.name}\"", 404)
elsif @roavw.release_order_application_with_version_envs.exists?(env_id: env.id)
request_halt("Env \"#{env_name}\" has been already added into \"#{@release_order.name}\" for application: \"#{@application.name}\"", 409)
else
@roavw.release_order_application_with_version_envs.create(env_id: env.id)
end
end
{ status: 'ok' }.to_json
end
delete '/:name/orders/:order_name/applications/:application_name/:version/envs/:env_name' do
status 202
roavwe = @roavw.release_order_application_with_version_envs.find_by_id(@env_for_release_order.id)
roavwe.destroy
{ status: 'ok' }.to_json
end
put '/:name/orders/:order_name/results/:application_name/:version/envs/:env' do
status 202
json = JSON.parse(request.body.read, symbolize_names: true)
enums = ReleaseOrderResult.statuses.map(&:first)
unless enums.include? json[:status]
raise PutitExceptions::EnumError, "Invalid status: #{json[:status]}, valids are: \"#{enums}\""
end
env_name = @app_env.name
begin
@release_order.release_order_results.create! do |result|
result.env_id = @env_for_release_order.env.id
result.application_id = @application.id
result.application_with_version_id = @avw.id
result.status = json[:status].to_sym
end
rescue ActiveRecord::RecordNotUnique => e
log_msg = "Duplication of deploy result for change: #{@release_order.name} for #{@application.name} in version: #{@avw.version} on env: #{env_name}."
logger.debug(log_msg + 'due to error:' + e.message)
raise PutitExceptions::DuplicateDeploymentResult, log_msg
end
@release_order.deployed!
logger.info("Set status: #{json[:status]} for #{@application.name} in version: #{@avw.version} on env: #{env_name}")
{ status: 'ok' }.to_json
end
get '/:name/orders/:order_name/results/:application_name/:version/envs/:env/status' do
status 200
{ deploy_status: @result.status.to_s }.to_json
end
get '/:name/orders/:order_name/results/:application_name/:version/envs/:env/all' do
status 200
log_url = "#{Settings.putit_core_url}/status/#{@application.url_name}/#{@app_env.name}/#{@result.id}/logs"
{
release: @result.release_order.release.name,
change: @result.release_order.name,
version: @avw.version,
env: @result.env.name,
status: @result.status,
deployment_date: @result.updated_at,
log_url: log_url
}.to_json
end
get '/:name/orders/:order_name/results/:application_name/:version/envs/:env/logs' do
param :as_attachment, Boolean, required: false, raise: true
content_type 'text/plain'
status 200
logs = @result.log
if logs.nil?
request_halt("No logs for release order with name \"#{@release_order.name}\" for application: \"#{@application.name}\" in version \"#{@avw.version}\" for env: \"#{@app_env.name}\" does not exists.", 404)
end
if params[:as_attachment]
attachment "#{@release.name}_#{@release_order.name}_#{@application.name}_#{@avw.version}_#{@app_env.name}.log"
end
logs
end
end
|
require_relative '../encrypt'
# 1. describe the method we're testing (describe)
# 2. say what we're testing (it)
# 3. call the method, and compare the outcome (expect)
describe '#encrypt' do
it 'should return an empty string when given one' do
actual = encrypt('')
expect(actual).to eq('')
end
it 'should return "XYZ" when given "ABC"' do
actual = encrypt('ABC')
expect(actual).to eq('XYZ')
end
it 'should return an encrypted msg when given a long string' do
actual = encrypt('THE QUICK BROWN FOX, JUMPS OVER THE LAZY DOG')
expect(actual).to eq('QEB NRFZH YOLTK CLU, GRJMP LSBO QEB IXWV ALD')
end
end
# encrypt('ABC') == 'XYZ'
# abbreviate('what the french') == 'WTF'
|
# frozen_string_literal: true
module Namarara
VERSION = '0.9.5'
end
|
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
module Recliner
describe Document, '#inspect' do
context "on base class" do
it "should return class name" do
Recliner::Document.inspect.should == 'Recliner::Document'
end
end
context "on subclasses" do
context "without properties" do
define_recliner_document :TestDocument
it "should return class name" do
TestDocument.inspect.should == 'TestDocument()'
end
end
context "with properties" do
define_recliner_document :TestDocument do
property :name, String
property :age, Integer
end
it "should return class name and property definitions" do
TestDocument.inspect.should == 'TestDocument(name: String, age: Integer)'
end
end
end
context "on subclass instances" do
define_recliner_document :TestDocument do
property :name, String
property :age, Integer
end
context "with revision" do
subject { TestDocument.new(:id => 'abc-123', :rev => '1-12345', :name => 'Doc name', :age => 54) }
it "should return class name and property values" do
subject.inspect.should == '#<TestDocument id: abc-123, rev: 1-12345, name: "Doc name", age: 54>'
end
end
context "without revision" do
subject { TestDocument.new(:id => 'abc-123', :name => 'Doc name', :age => 54) }
it "should return class name and property values" do
subject.inspect.should == '#<TestDocument id: abc-123, name: "Doc name", age: 54>'
end
end
end
end
end
|
class CowsController < ApplicationController
def index
@cows = Cow.all
end
def new
@cow = Cow.new
end
def create
byebug
cow = Cow.create(cow_params)
redirect_to cows_path
end
private
def cow_params
params.require(:cow).permit(:name, :number_of_spots, :age)
end
end |
require 'spec_helper'
describe "Employee Login" do
context "when an employee provides the correct login credentials" do
it "they will be directed to their home page" do
employee = FactoryGirl.create(:employee)
visit login_path
fill_in 'Username', :with => employee.username
fill_in 'Password', :with => employee.password
click_button 'Log In'
current_path.should eq(employee_path(employee))
page.should have_content('Logged in.')
end
end
context "when an employee provides the incorrect login credentials" do
it "they will be directed back to the login page to re-submit credentials" do
employee = FactoryGirl.create(:employee, :username => 'jdoe', :password => 'fail')
visit login_path
fill_in 'Username', :with => 'jdoe'
fill_in 'Password', :with => 'incorrect_password'
click_button 'Log In'
current_path.should eq(sessions_path)
page.should have_content('Username or password is invalid.')
end
end
end
|
# ---------------------------------------------------------------------------
# Copyright (c) 2007, 37signals
#
# 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.
# ---------------------------------------------------------------------------
# A wrapper class that quacks like a Time instance, but which remembers its
# local time zone. Most operations work like normal, but some will automatically
# convert the object to utc, like #to_s(:db).
class TzTime
include Comparable
# Like the Time class, the TzTime class is its own factory. You will almost
# never create a TzTime instance via +new+. Instead, you will use something
# like TzTime.now (etc.)
class <<self
# Set and access the "local" time zone. There should be a before_filter
# somewhere in your app that ensures this is set correctly.
attr_accessor :zone
# Clears the current zone setting. This should be called from an after_filter
# to make sure time zones don't leak across requests.
def reset!
self.zone = nil
end
# Return a TzTime instance that represents the current time.
def now
new(zone.utc_to_local(Time.now.utc), zone)
end
# Return a TzTime instance for the given arguments, where the arguments
# are interpreted to be time components in the "local" time zone.
def local(*args)
new(Time.utc(*args), zone)
end
# Return a TzTime instance for the given arguments, where the arguments
# are interpreted to be time components in UTC.
def utc(*args)
new(zone.utc_to_local(Time.utc(*args)), zone)
end
# Given a time instance, return the corresponding TzTime instance. The time
# is interpreted as being in the "local" time zone, regardless of what the
# time's actual time zone value is.
def at(time)
new(time, zone)
end
# Make sure the TzTime class itself responds like the Time class.
def method_missing(sym, *args, &block)
result = Time.send(sym, *args, &block)
result = new(result, zone) if result.is_a?(Time)
result
end
end
attr_reader :time, :zone
alias_method :to_time, :time
# Create a new TzTime instance that wraps the given Time instance. The time
# is considered to be in the time zone indicated by the +zone+ parameter.
def initialize(time, zone)
@time = time.to_time
@zone = zone
end
# Wraps the Time#change method, but returns a TzTime instance for the
# changed time.
def change(options) #:nodoc:
TzTime.new(time.change(options), @zone)
end
# Adds some number of seconds to the time, and returns it wrapped in a new
# TzTime instnace.
def +(seconds)
TzTime.new(time + seconds, @zone)
end
# Subtracts some number of seconds from the time, and returns it wrapped in
# a new TzTime instnace.
def -(seconds)
TzTime.new(time - seconds, @zone)
end
# Returns a Time value, representing the wrapped time in UTC.
def utc
@utc ||= zone.local_to_utc(@time)
end
# Compares this TzTime with a time instance.
def <=>(value)
time.to_time <=> value.to_time
end
# This TzTime object always represents the local time in the associated
# timezone. Thus, #utc? should always return false, unless the zone is the
# UTC zone.
def utc?
zone.name == "UTC"
end
# Returns the underlying TZInfo::TimeZonePeriod instance for the wrapped
# time.
def period
@period ||= zone.tzinfo.period_for_local(time)
end
# Returns true if the current time is adjusted for daylight savings.
def dst?
period.dst?
end
# Returns a string repersentation of the time. For the specific case where
# +mode+ is <tt>:db</tt> or <tt>:rfc822</tt>, this will return the UTC
# representation of the time. All other conversions will use the local time.
def to_s(mode = :normal)
case mode
when :db, :rfc822 then utc.to_s(mode)
else time.to_s(mode)
end
end
# Return a reasonable representation of this TzTime object for inspection.
def inspect
"#{time.strftime("%Y-%m-%d %H:%M:%S")} #{period.abbreviation}"
end
# Because of the method_missing proxy, we want to make sure we report this
# object as responding to a method as long as the method is defined directly
# on TzTime, or if the underlying Time instance responds to the method.
def respond_to?(sym) #:nodoc:
super || @time.respond_to?(sym)
end
# Proxy anything else through to the underlying Time instance.
def method_missing(sym, *args, &block) #:nodoc:
result = @time.send(sym, *args, &block)
result = TzTime.new(result, zone) if result.is_a? Time
result
end
end |
class Admin::CouponsController < AdminController
load_and_authorize_resource
has_scope :by_coupon_offer
after_action :check_coupons_time_limit, only: :index
def index
@coupons = Kaminari.paginate_array(apply_scopes(Coupon).all.order("created_at DESC")).page params[:page]
respond_to do |format|
if !request.xhr?
format.html
format.xls
format.js
elsif request.xhr?
format.json {render json: @coupons}
format.xls
format.js
end
end
end
def new
@user = User.find(params[:user_id])
end
def create
@coupon = Coupon.new(coupon_params)
@coupon.code = @coupon.generate_number
@coupon.status = "nonutilise"
@coupon.time_limit = Time.zone.now + 1.month
if @coupon.save
redirect_to admin_coupons_path
Emailer.send_coupon_email(@coupon, User.find(params[:user_id])).deliver
else
render 'new', user_id: params[:user_id]
end
end
def destroy
@coupon.destroy
if params[:user_id]
redirect_to admin_user_path(params[:user_id])
else
redirect_to admin_coupons_path
end
end
def update
if @coupon.update(coupon_params)
flash[:sucess] = "Coupon mis à jour"
redirect_to admin_user_path(@coupon.user_id)
else
render 'edit'
end
end
def edit
@coupon = Coupon.find(params[:id])
end
private
def coupon_params
params.require(:coupon).permit(:user_id, :benefit_type_id, :price_cents, :status)
end
def check_coupons_time_limit
@coupons.each do |c|
if c.time_limit.present? and c.time_limit < Time.zone.now and c.status == "nonutilise"
c.status = "expire"
c.save
end
end
end
end |
# Copyright (c) 2015 Vault12, Inc.
# MIT License https://opensource.org/licenses/MIT
require 'test_helper'
require 'errors/all'
include Errors
class FileIOTest < ActionController::TestCase
public
test 'file config limits' do
save = Rails.configuration.x.relay.file_store[:max_chunk_size]
Rails.configuration.x.relay.file_store[:max_chunk_size] = MAX_COMMAND_BODY-1000 # slightly less then 1k
assert_raises ConfigError do
fm = FileManager.new
end
Rails.configuration.x.relay.file_store[:max_chunk_size] = save
end
test 'file storage path' do
fm = FileManager.new
assert_not_nil fm
assert_not_nil fm.storage_path
assert_equal Rails.configuration.x.relay.file_store[:root], fm.storage_path
# empty config
save_it = Rails.configuration.x.relay.file_store[:root]
Rails.configuration.x.relay.file_store[:root] = "" # now empty
fm = FileManager.new
assert_not_nil fm
assert_not_nil fm.storage_path
assert_equal "#{Rails.root}/shared/uploads/", fm.storage_path
missing_slash = "#{Rails.root}/shared/uploads"
Rails.configuration.x.relay.file_store[:root]=missing_slash
fm = FileManager.new
assert_not_nil fm
assert_not_nil fm.storage_path
# trailing `/` enforced
assert_not_equal missing_slash, fm.storage_path
assert_equal (missing_slash+'/'), fm.storage_path
Rails.configuration.x.relay.file_store[:root]=save_it # restore it
end
test 'create storage dir' do
# assert_raises(Errors::ZAXError) { fm = FileManager.new }
fm = FileManager.new
# always a storage dir after constructor
assert File.directory?(fm.storage_path)
# move uploads => uploads2
u2 = fm.storage_path.sub(/\/$/,'2/')
FileUtils.rmtree(u2) if File.directory?(u2)
File.rename fm.storage_path,u2
# now there is no storage dir
assert_not File.directory?(fm.storage_path)
fm = FileManager.new
# storage dir recreated
assert File.directory?(fm.storage_path)
# restore old storage dir in case it had any files
FileUtils.rmtree fm.storage_path
File.rename u2,fm.storage_path
end
test 'secret seed' do
# seed exists in config
test = "jEPjU+8lB5XdSOhffS2GHtMXpRpEM12k/HML0SUYMEo"
Rails.configuration.x.relay.file_store[:secret_seed] = test
fm = FileManager.new
assert_equal fm.seed, test
# seed exists in file
Rails.configuration.x.relay.file_store[:secret_seed] = ""
fm = FileManager.new
seed_path = fm.storage_path+"secret_seed.txt"
file_seed = File.open(seed_path, 'r') { |f| f.read() }
assert_equal file_seed,fm.seed
seed_path2 = fm.storage_path+"secret_seed2.txt"
# seed created if there is no config, no file
Rails.configuration.x.relay.file_store[:secret_seed] = ""
FileUtils.mv seed_path,seed_path2 if File.exists?(seed_path)
assert_not File.exists?(seed_path)
fm = FileManager.new
assert_not_nil fm.seed
assert fm.seed.length>32
if File.exists?(seed_path2)
FileUtils.rm seed_path
FileUtils.mv seed_path2,seed_path
end
Rails.configuration.x.relay.file_store[:secret_seed] = nil
end
test 'storage name' do
hpk_from = h2(RbNaCl::PrivateKey.generate.public_key)
hpk_to = h2(RbNaCl::PrivateKey.generate.public_key)
fm = FileManager.new
nonce = rand_bytes NONCE_LEN
uID = h2(hpk_from+hpk_to+nonce+fm.seed)
token = fm.create_storage_token(hpk_from,hpk_to,nonce,0)
assert_equal token[:uploadID], uID
Rails.configuration.x.relay.file_store[:secret_seed] = "bgi5UzAYLEjfHvWxFEbxUE3tVOElydt63Pv3Hs99avw"
fm = FileManager.new
# this works with bad hpks because name is derived from hash
assert_equal "orn4mxjceonlkemkctmtzcbizs72ab63sjeizjdpqoy2cvetaxyq", fm.create_storage_token("hpk1","hpk2","123",0)[:storage_name]
end
end
|
class Category < ApplicationRecord
include NameMatches
belongs_to :parent, class_name: "Category", optional: true
has_many :children, class_name: "Category", foreign_key: "parent_id"
scope :roots, -> { where(parent: nil)}
def is_root?
parent.blank?
end
def parents_place_holder
return '' if is_root?
@parent_holder = ''
_get_parent_place_holder(parent)
@parent_holder
end
def prefix
parents_place_holder + place_holder
end
def to_s
name
end
def next_id(leng, standard)
_id = (prefix + '%0' + (leng - prefix.length - 2).to_s + 'd' + standard) % next_number
update(next_number: next_number + 1)
_id
end
private
def _get_parent_place_holder(parent)
@parent_holder.insert(0, parent.place_holder)
return if parent.is_root?
_get_parent_place_holder(parent.parent)
end
end
|
class GoogleGeocodeService
def self.get_coordinates(address)
self.get_json(address)
end
private
def self.connection(address)
Faraday.new(url: 'https://maps.googleapis.com/maps/api/geocode/json') do |f|
f.params[:address] = address
f.params[:key] = ENV['GOOGLE_API_KEY']
f.adapter Faraday.default_adapter
end
end
def self.get_json(address)
response = self.connection(address).get
JSON.parse(response.body, symbolize_names: true)
end
end
|
require 'spec_helper'
require 'raven/instance'
RSpec.describe Raven::Instance do
let(:event) { Raven::Event.new(id: "event_id", configuration: configuration, context: Raven.context, breadcrumbs: Raven.breadcrumbs) }
let(:options) { { :key => "value" } }
let(:event_options) { options.merge(:context => subject.context, :configuration => configuration, breadcrumbs: Raven.breadcrumbs) }
let(:context) { nil }
let(:configuration) do
config = Raven::Configuration.new
config.dsn = "dummy://12345:67890@sentry.localdomain:3000/sentry/42"
config.logger = Logger.new(nil)
config
end
subject { described_class.new(context, configuration) }
before do
allow(subject).to receive(:send_event)
allow(Raven::Event).to receive(:from_message) { event }
allow(Raven::Event).to receive(:from_exception) { event }
end
describe '#context' do
it 'is Raven.context by default' do
expect(subject.context).to equal(Raven.context)
end
context 'initialized with a context' do
let(:context) { :explicit }
it 'is not Raven.context' do
expect(subject.context).to_not equal(Raven.context)
end
end
end
describe '#capture_type' do
describe 'as #capture_message' do
before do
expect(Raven::Event).to receive(:from_message).with(message, event_options)
expect(subject).to receive(:send_event).with(event, :exception => nil, :message => message)
end
let(:message) { "Test message" }
it 'sends the result of Event.capture_message' do
subject.capture_type(message, options)
end
it 'yields the event to a passed block' do
expect { |b| subject.capture_type(message, options, &b) }.to yield_with_args(event)
end
end
describe 'as #capture_message when async' do
let(:message) { "Test message" }
around do |example|
prior_async = subject.configuration.async
subject.configuration.async = proc { :ok }
example.run
subject.configuration.async = prior_async
end
it 'sends the result of Event.capture_type' do
expect(Raven::Event).to receive(:from_message).with(message, event_options)
expect(subject).not_to receive(:send_event).with(event)
expect(subject.configuration.async).to receive(:call).with(event.to_json_compatible)
subject.capture_message(message, options)
end
it 'returns the generated event' do
returned = subject.capture_message(message, options)
expect(returned).to eq(event)
end
end
describe 'as #capture_exception' do
let(:exception) { build_exception }
it 'sends the result of Event.capture_exception' do
expect(Raven::Event).to receive(:from_exception).with(exception, event_options)
expect(subject).to receive(:send_event).with(event, :exception => exception, :message => nil)
subject.capture_exception(exception, options)
end
it 'has an alias' do
expect(Raven::Event).to receive(:from_exception).with(exception, event_options)
expect(subject).to receive(:send_event).with(event, :exception => exception, :message => nil)
subject.capture_exception(exception, options)
end
end
describe 'as #capture_exception when async' do
let(:exception) { build_exception }
context "when async" do
around do |example|
prior_async = subject.configuration.async
subject.configuration.async = proc { :ok }
example.run
subject.configuration.async = prior_async
end
it 'sends the result of Event.capture_exception' do
expect(Raven::Event).to receive(:from_exception).with(exception, event_options)
expect(subject).not_to receive(:send_event).with(event)
expect(subject.configuration.async).to receive(:call).with(event.to_json_compatible)
subject.capture_exception(exception, options)
end
it 'returns the generated event' do
returned = subject.capture_exception(exception, options)
expect(returned).to eq(event)
end
end
context "when async raises an exception" do
around do |example|
prior_async = subject.configuration.async
subject.configuration.async = proc { raise TypeError }
example.run
subject.configuration.async = prior_async
end
it 'sends the result of Event.capture_exception via fallback' do
expect(Raven::Event).to receive(:from_exception).with(exception, event_options)
expect(subject.configuration.async).to receive(:call).with(event.to_json_compatible)
subject.capture_exception(exception, options)
end
end
end
describe 'as #capture_exception with a should_capture callback' do
let(:exception) { build_exception }
it 'sends the result of Event.capture_exception according to the result of should_capture' do
expect(subject).not_to receive(:send_event).with(event)
subject.configuration.should_capture = proc { false }
expect(subject.configuration.should_capture).to receive(:call).with(exception)
expect(subject.capture_exception(exception, options)).to be false
end
end
end
describe '#capture' do
context 'given a block' do
it 'yields to the given block' do
expect { |b| subject.capture(&b) }.to yield_with_no_args
end
end
it 'does not install an at_exit hook' do
expect(Kernel).not_to receive(:at_exit)
subject.capture {}
end
end
describe '#annotate_exception' do
let(:exception) { build_exception }
def ivars(object)
object.instance_variables.map(&:to_s)
end
it 'adds an annotation to the exception' do
expect(ivars(exception)).not_to include("@__raven_context")
subject.annotate_exception(exception, {})
expect(ivars(exception)).to include("@__raven_context")
expect(exception.instance_variable_get(:@__raven_context)).to \
be_kind_of Hash
end
context 'when the exception already has context' do
it 'does a deep merge of options' do
subject.annotate_exception(exception, :extra => { :language => "ruby" })
subject.annotate_exception(exception, :extra => { :job_title => "engineer" })
expected_hash = { :extra => { :language => "ruby", :job_title => "engineer" } }
expect(exception.instance_variable_get(:@__raven_context)).to \
eq expected_hash
end
end
end
describe '#report_status' do
let(:ready_message) do
"Raven #{Raven::VERSION} ready to catch errors"
end
let(:not_ready_message) do
"Raven #{Raven::VERSION} configured not to capture errors: DSN not set"
end
context "when current environment is included in environments" do
before do
subject.configuration.silence_ready = false
subject.configuration.environments = ["default"]
end
it 'logs a ready message when configured' do
expect(subject.logger).to receive(:info).with(ready_message)
subject.report_status
end
it 'logs a warning message when not properly configured' do
# dsn not set
subject.configuration = Raven::Configuration.new
expect(subject.logger).to receive(:info).with(not_ready_message)
subject.report_status
end
it 'logs nothing if "silence_ready" configuration is true' do
subject.configuration.silence_ready = true
expect(subject.logger).not_to receive(:info)
subject.report_status
end
end
context "when current environment is not included in environments" do
it "doesn't log any message" do
subject.configuration.silence_ready = false
subject.configuration.environments = ["production"]
expect(subject.logger).not_to receive(:info)
subject.report_status
end
end
end
describe '.last_event_id' do
let(:message) { "Test message" }
it 'sends the result of Event.capture_type' do
expect(subject).to receive(:send_event).with(event, :exception => nil, :message => message)
subject.capture_type("Test message", options)
expect(subject.last_event_id).to eq(event.id)
end
end
describe "#user_context" do
context "without a block" do
it "doesn't override previous data" do
subject.user_context(id: 1)
subject.user_context(email: "test@example.com")
expect(subject.context.user).to eq({ id: 1, email: "test@example.com" })
end
it "empties the user context when called without options" do
subject.context.user = { id: 1 }
expect(subject.user_context).to eq({})
end
it "empties the user context when called with nil" do
subject.context.user = { id: 1 }
expect(subject.user_context(nil)).to eq({})
end
it "doesn't empty the user context when called with {}" do
subject.context.user = { id: 1 }
expect(subject.user_context({})).to eq({ id: 1 })
end
it "returns the user context when set" do
expected = { id: 1 }
expect(subject.user_context(expected)).to eq(expected)
end
end
context "with a block" do
it "returns the user context when set" do
expected = { id: 1 }
user_context = subject.user_context(expected) do
# do nothing
end
expect(user_context).to eq expected
end
it "sets user context only in the block" do
subject.context.user = { id: 9999 }
subject.user_context(id: 1) do
expect(subject.context.user).to eq(id: 1)
end
expect(subject.context.user).to eq(id: 9999)
end
it "resets with nested blocks" do
subject.context.user = {}
subject.user_context(id: 9999) do
subject.user_context(email: 'foo@bar.com') do
expect(subject.context.user).to eq(id: 9999, email: 'foo@bar.com')
end
expect(subject.context.user).to eq(id: 9999)
end
expect(subject.context.user).to eq({})
end
end
end
describe "#tags_context" do
let(:default) { { :foo => :bar } }
let(:additional) { { :baz => :qux } }
before do
subject.context.tags = default
end
it "returns the tags" do
expect(subject.tags_context).to eq default
end
it "returns the tags" do
expect(subject.tags_context(additional)).to eq default.merge(additional)
end
it "doesn't set anything if the tags is empty" do
subject.tags_context({})
expect(subject.context.tags).to eq default
end
it "adds tags" do
subject.tags_context(additional)
expect(subject.context.tags).to eq default.merge(additional)
end
context 'when block given' do
it "returns the tags" do
tags = subject.tags_context(additional) do
# do nothing
end
expect(tags).to eq default
end
it "adds tags only in the block" do
subject.tags_context(additional) do
expect(subject.context.tags).to eq default.merge(additional)
end
expect(subject.context.tags).to eq default
end
end
end
describe "#extra_context" do
let(:default) { { :foo => :bar } }
let(:additional) { { :baz => :qux } }
before do
subject.context.extra = default
end
it "returns the extra" do
expect(subject.extra_context).to eq default
end
it "returns the extra" do
expect(subject.extra_context(additional)).to eq default.merge(additional)
end
it "doesn't set anything if the extra is empty" do
subject.extra_context({})
expect(subject.context.extra).to eq default
end
it "adds extra" do
subject.extra_context(additional)
expect(subject.context.extra).to eq default.merge(additional)
end
context 'when block given' do
it "returns the extra" do
extra = subject.extra_context(additional) do
# do nothing
end
expect(extra).to eq default
end
it "adds extra only in the block" do
subject.extra_context(additional) do
expect(subject.context.extra).to eq default.merge(additional)
end
expect(subject.context.extra).to eq default
end
end
end
describe "#rack_context" do
it "doesn't set anything if the context is empty" do
subject.rack_context({})
expect(subject.context.rack_env).to be_nil
end
it "sets arbitrary rack context" do
subject.rack_context(:foo => :bar)
expect(subject.context.rack_env[:foo]).to eq(:bar)
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.