text stringlengths 10 2.61M |
|---|
require 'benchmark'
require_relative 'selection_sort.rb'
require_relative 'insertion_sort.rb'
require_relative 'bubble_sort.rb'
require_relative 'merge_sort.rb'
require_relative 'quick_sort.rb'
require_relative 'heap_sort.rb'
require_relative 'bucket_sort.rb'
collection = Array.new(50) { rand(0..100) }
Benchmark.bm(50) do |x|
x.report("selection") {
selection_sort(collection)
}
x.report("insertion") {
insertion_sort(collection)
}
x.report("bubble") {
bubble_sort(collection)
}
x.report("merge") {
merge_sort(collection)
}
x.report("quick") {
quick_sort(collection, 0, collection.length-1)
}
x.report("heap") {
heap_sort(collection)
}
x.report("bucket") {
bucket_sort(collection)
}
end
|
# frozen_string_literal: true
unless ENV['CI']
require 'simplecov'
require 'dotenv'
SimpleCov.start
Dotenv.load('.env')
end
require 'capybara'
require 'capybara/dsl'
require 'capybara/cucumber'
require 'selenium-webdriver'
$LOAD_PATH << './test_site'
$LOAD_PATH << './lib'
require 'site_prism'
require 'test_site'
require 'sections/people'
require 'sections/no_element_within_section'
require 'sections/container_with_element'
require 'sections/child'
require 'sections/parent'
require 'sections/search_result'
require 'pages/my_iframe'
require 'pages/home'
require 'pages/home_with_expected_elements'
require 'pages/dynamic_page'
require 'pages/no_title'
require 'pages/page_with_people'
require 'pages/redirect'
require 'pages/section_experiments'
Capybara.configure do |config|
config.default_driver = :selenium
config.default_max_wait_time = 5
config.app_host = 'file://' + File.dirname(__FILE__) + '/../../test_site/html'
config.ignore_hidden_elements = false
end
SitePrism.configure do |config|
config.use_implicit_waits = false
end
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, browser: browser)
end
private
def browser
@browser ||= ENV.fetch('browser', 'firefox').to_sym
end
|
# frozen_string_literal: true
require 'net/http/request'
RSpec.describe Api::V1::Constraints do
let(:constraints) { described_class.new(version: 1, default: false) }
let(:req) { double }
it "doesn't match when non-default and missing headers" do
expect(constraints).not_to be_matches(req)
end
it 'matches when the proper headers are included' do
allow(req).to receive(:respond_to?).and_return(true)
allow(req).to receive(:headers).and_return('Accept' => 'application/vnd.kiosks.v1')
expect(constraints).to be_matches(req)
end
end
|
class ContentInformation < ApplicationRecord
self.table_name = "files"
validates_uniqueness_of :content_guid, scope: :content_type
def self.get_not_uploaded_books_list
path = ENV['HOST_URL'] + "/api/ops/content_request/" + "request_not_uploaded_books?key=" + ENV['TOKEN']
response = open(path,:read_timeout => 300).read
book_asset_info = JSON.parse(response)["book_asset_info"]
content_ids = []
book_asset_info.each do |ba_info|
content_ids << file_model_before_upload(ba_info)
end
get_book_content
end
def self.get_book_content
download_content_list = ContentInformation.where(download_status:"failed")
download_content_list.each do |ba_info|
ba_info.update_attribute(:download_status,"in_delayed_job")
ba_info.get_book_content_process
end
end
def get_book_content_process
self.update_attribute(:download_status, "in_progress")
books_md5_hash = {}
dir_path = self.create_required_directory(self.content_id, self.content_type, self.url)
if self.content_type == "book"
saved_file_dest_path = self.fetch_book_encrypted_file(self.content_id, dir_path)
elsif self.content_type == "book_info"
saved_file_dest_path = self.fetch_book_info_file(self.content_id, dir_path)
else
saved_file_dest_path = self.fetch_content_file(self.url, self.filename, dir_path)
end
puts "#{saved_file_dest_path}"
#---------------------------------------------------------------------#
unless self.content_type == "book_info"
md5_hash = self.calculate_md5_hash(saved_file_dest_path)
# books_md5[ba_info[-4]] = md5_hash
books_md5_hash[self.content_guid] = md5_hash
puts books_md5_hash.to_json
download_status = self.send_books_md5_hash(books_md5_hash.to_json)
puts download_status
self.file_model_after_upload(self.url, saved_file_dest_path.gsub(ENV['CONTENT_DIR'],""), download_status)
else
download_status = "success"
self.file_model_after_upload(self.url, saved_file_dest_path.gsub(ENV['CONTENT_DIR'],""), download_status)
end
end
handle_asynchronously :get_book_content_process
def create_required_directory(content_id, type, url)
if type == "book"
dir_path = ENV['CONTENT_DIR'] + "/ibook_assets/" + "#{content_id}" + "/encrypted_content"
elsif type == "book_info"
dir_path = ENV['CONTENT_DIR'] + "/ibook_assets/" + "#{content_id}" + "/info_files"
elsif type == "asset"
dir_path = ENV['CONTENT_DIR'] + "/system/user_assets/attachments/" + "#{content_id}"
elsif type == "quiz"
f_url = url.split("/")
f_url.pop
#dir_path = "/home/rahul/work/cachefiles" + "/public" + f_url.inject(""){|s,x| s+ "/" + x} #"/messages/44572/1489495957"
dir_path = ENV['CONTENT_DIR'] + f_url.inject(""){|s,x| s+ "/" + x} #"/messages/44572/1489495957"
end
dir_create = self.directory_create(dir_path)
puts "destination directory created"
return dir_path
end
#since FileUtlis is now onlyy supported for ruby 2.5 and above anf all prev versions have been yanked
def directory_create(path)
recursive = path.split('/')
directory = ''
recursive.each do |sub_directory|
directory += sub_directory + '/'
Dir.mkdir(directory) unless (File.directory? directory)
end
end
def fetch_book_encrypted_file(book_id, dir_path)
path = ENV['HOST_URL'] + "/api/ops/content_request/" + "send_ibook_file?key=" + ENV['TOKEN'] + "&book_id=#{book_id}"
filename = "encrypted.zip"
dest_path = dir_path + "/#{filename}"
response = open(path,:read_timeout => 300)
dest_file = IO.copy_stream(response, dest_path)
puts "file saved to directory"
return dest_path
end
def fetch_book_info_file(book_id, dir_path)
path = ENV['HOST_URL'] + "/api/ops/content_request/" + "send_ibook_info_file?key=" + ENV['TOKEN'] + "&book_id=#{book_id}"
filename = "info.zip"
dest_path = dir_path + "/#{filename}"
response = open(path,:read_timeout => 300)
dest_file = IO.copy_stream(response, dest_path)
puts "info_file saved to directory"
return dest_path
end
def fetch_content_file(hit_url, filename, dir_path)
content_url = ENV['HOST_URL'] + "/#{hit_url}"
response = open(content_url, :read_timeout => 300)
dest_path = dir_path + "/#{filename}"
dest_file = IO.copy_stream(response, dest_path)
puts "asset saved in the dirrr"
return dest_path
end
def calculate_md5_hash(content_url)
md5_hash = Digest::MD5.file content_url
md5_digest = md5_hash.hexdigest
puts "md5 hash calculated"
return md5_digest
end
def send_books_md5_hash(books_md5_hash)
path = ENV['HOST_URL'] + "/api/ops/content_request/" + "update_cdn_content_status?key=" + ENV['TOKEN']
url = URI.parse(path)
resp, data = Net::HTTP.post_form(url,book_md5:books_md5_hash)
puts resp
puts resp.body
puts data
status = JSON.parse(resp.body)["status"][0]
return status
end
def self.file_model_before_upload(info_arr)
@content_info = ContentInformation.where(content_guid: info_arr[7], content_type:info_arr[9]).first
if (@content_info.present? and @content_info.download_status == "success")
@content_info.update_attributes(is_sync:"n", download_status:"failed") unless @content_info.nil?
end
if @content_info.nil?
@content_info = ContentInformation.new
@content_info.url = info_arr[0]
@content_info.filename = info_arr[1]
@content_info.relativefilepath = info_arr[2]
@content_info.file_md5 = info_arr[3]
@content_info.url_md5 = info_arr[4]
@content_info.is_sync = info_arr[5]
@content_info.date_created = info_arr[6].to_time
@content_info.content_type = info_arr[-2]
@content_info.content_guid = info_arr[7]
@content_info.download_status = info_arr[8]
@content_info.content_id = info_arr[-1]
@content_info.save
end
return @content_info.url
end
def file_model_after_upload(info_id, relativefilepath, download_status)
c_info = ContentInformation.find(info_id)
download_status == "success" ? c_info.update_attributes(is_sync:"y", download_status:download_status, relativefilepath: relativefilepath) : c_info.update_attributes(is_sync:"n", download_status:download_status, relativefilepath: relativefilepath)
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
def ensure_shelf_visible(shelf)
visible = BookShelf.for(current_user).include? shelf
not_found unless visible
end
def ensure_book_on_shelf(book, shelf)
on_shelf = shelf.books.include? book
not_found unless on_shelf
end
def not_found
render file: 'public/404', status: :not_found and return
end
end
|
# frozen_string_literal: true
# == Schema Information
#
# Table name: requirements
#
# id :bigint(8) not null, primary key
# shift_id :bigint(8)
# mandatory :integer
# optional :integer
# created_at :datetime not null
# updated_at :datetime not null
# event_id :bigint(8)
# team_id :bigint(8)
#
class Requirement < ApplicationRecord
belongs_to :shift
belongs_to :team
belongs_to :event, optional: true
end
|
class CommentsController < ApplicationController
before_action :authenticate_user!, only: %i[new create edit update]
def new
set_commentable
set_comment_full_path
@comment = @commentable.comments.new
end
def create
set_commentable
set_comment_full_path
@comment = @commentable.comments.new(comment_params.merge(user: current_user))
if @comment.save
respond_to do |format|
format.html do
flash[:success] = 'Comment was successfully added'
redirect_to after_create_path
end
format.js { flash.now[:success] = 'Comment was successfully added' }
end
else
respond_to do |format|
format.html { render :new }
format.js { render template: 'comments/new_error.js.erb' }
end
end
end
def edit
set_comment
end
def update
set_comment
if @comment.update(comment_params)
flash[:success] = 'Comment was successfully updated'
redirect_to commentable_path
else
render :edit
end
end
def destroy
set_comment
if @comment.destroy
flash[:success] = 'Comment was successfully deleted'
else
flash[:notice] = 'Something went wrong'
end
redirect_to commentable_path
end
private
def comment_params
params.require(:comment).permit(:body)
end
def set_comment
@comment = Comment.find(params[:id])
end
def after_create_path
raise 'Please implement `after_create_path`'
end
def commentable_path
[@comment.commentable.reviewable, @comment.commentable]
end
end
|
class Api::V1::PhotosController < ApplicationController
protect_from_forgery unless: -> { request.format.json? }
def index
render json: Photo.all
end
def show
render json: Photo.find(params[:id])
end
def create
photo = Photo.new(post_id: Post.last.id, photo_url: params[:photo_url])
if photo.save
render json: photo
else
render json: { error: photo.errors.full_messages }, status: :unprocessable_entity
end
end
private
def photo_params
params.permit(:photo_url, Post.last.id)
end
end
|
require 'shellwords'
module RuboCop
module Git
# ref. https://github.com/thoughtbot/hound/blob/d2f3933/app/services/build_runner.rb
class Runner
def run(options)
options = Options.new(options) unless options.is_a?(Options)
@options = options
@files = DiffParser.parse(git_diff(options))
display_violations($stdout)
exit(1) if violations.any?
end
private
def violations
@violations ||= style_checker.violations
end
def style_checker
StyleChecker.new(pull_request.pull_request_files,
@options.rubocop,
@options.config_file,
pull_request.config)
end
def pull_request
@pull_request ||= PseudoPullRequest.new(@files, @options)
end
def git_diff(options)
args = %w(diff --diff-filter=AMCR --find-renames --find-copies)
args << '--cached' if options.cached
args << options.commit_first.shellescape if options.commit_first
args << options.commit_last.shellescape if options.commit_last
`git #{args.join(' ')}`
end
def display_violations(io)
formatter = RuboCop::Formatter::ClangStyleFormatter.new(io)
formatter.started(nil)
violations.map do |violation|
offenses = violation.offenses
offenses = offenses.reject(&:disabled?) if offenses.first.respond_to?(:disabled?)
formatter.file_finished(
violation.filename,
offenses.compact.sort.freeze
)
end
formatter.finished(@files.map(&:filename).freeze)
end
end
end
end
|
# frozen_string_literal: true
ActiveSupport.on_load(:active_record) do
module ActiveRecord
class Base
def self.rails_admin(&block)
RailsAdmin.config(self, &block)
end
def rails_admin_default_object_label_method
new_record? ? "new #{self.class}" : "#{self.class} ##{id}"
end
def safe_send(value)
if has_attribute?(value)
read_attribute(value)
else
send(value)
end
end
end
end
if defined?(CompositePrimaryKeys)
# Apply patch until the fix is released:
# https://github.com/composite-primary-keys/composite_primary_keys/pull/572
CompositePrimaryKeys::CompositeKeys.class_eval do
alias_method :to_param, :to_s
end
CompositePrimaryKeys::CollectionAssociation.prepend(Module.new do
def ids_writer(ids)
if reflection.association_primary_key.is_a? Array
ids = CompositePrimaryKeys.normalize(Array(ids).reject(&:blank?), reflection.association_primary_key.size)
reflection.association_primary_key.each_with_index do |primary_key, i|
pk_type = klass.type_for_attribute(primary_key)
ids.each do |id|
id[i] = pk_type.cast(id[i]) if id.is_a? Array
end
end
end
super ids
end
end)
end
end
|
# frozen_string_literal: true
Sequel.migration do
change do
alter_table(:dynflow_delayed_plans) do
long_text_type = @db.database_type == :mysql ? :mediumtext : String
add_column :serialized_args, long_text_type
end
end
end
|
require "base.rb"
require "help.rb"
require "lod.rb"
require "ramrun.rb"
require "scanf"
require "benchmark.rb"
module FastPf
NOBOOTSECTORFASTPF = 0
BOOTSECTORFASTPF = 1
FULLFASTPF = 2
USE_FLASHPROG_FPCBUFFERSIZE = 1
begin
@@C = CH__flash_programmer_globals
# @@intensiveVerify holds the RAM checking verify during fastpf.
@@fastpfIntensiveVerify = false
rescue
puts "*** WARNING!! The flash programmer globals could not be loaded. This plugin won't work without the flash programmer xmd! ***"
end
@@fpcBufferSize = @@C::FPC_BUFFER_SIZE
@@eraseSectorList = nil
class FlashProgrammerNotReady < Exception
end
class FlashCommandUnacknowledged < Exception
end
class FlashCommandTriggeredError < Exception
end
class FastpfVerifyFailed < Exception
end
class FastpfRAMVerifyFailed < FastpfVerifyFailed
end
class FastpfFLASHVerifyFailed < FastpfVerifyFailed
end
class FastpfVersionCheckError < Exception
end
def PACK32(uint32)
[(uint32)&0xFF,(uint32>>8)&0xFF,(uint32>>16)&0xFF,(uint32>>24)&0xFF]
end
public
def waitCommandResult(connection,cmdsRunning,currentCmd,timeout=5)
if(cmdsRunning[currentCmd])
result = connection.waitMutlipleEvents([@@C::EVENT_FLASH_PROG_READY+currentCmd, @@C::EVENT_FLASH_PROG_ERROR+currentCmd, @@C::EVENT_FLASH_PROG_UNKNOWN+currentCmd],timeout)
if(!result)
raise FlashCommandUnacknowledged,"Event aknowledging end of command never received!"
elsif(result==@@C::EVENT_FLASH_PROG_ERROR+currentCmd)
raise FlashCommandTriggeredError, ("Received error event 0x%02x from target for command 0x%02x" % [result, @@C::EVENT_FLASH_PROG_READY+currentCmd] )
elsif(result==@@C::EVENT_FLASH_PROG_UNKNOWN+currentCmd)
raise FlashCommandTriggeredError, ("Received unknown command event 0x%02x from target for command 0x%02x" % [result, @@C::EVENT_FLASH_PROG_READY+currentCmd] )
end
#else it's ok.
end
end
def filterLodPackets(codeFileLodPackets,writeBootSector)
# When fastpfing over USB, remove boot sector in flash list.
case writeBootSector
when NOBOOTSECTORFASTPF
c1 = codeFileLodPackets.size
codeFileLodPackets.reject!{ |i| i.address==$CS0.address}
puts "Rejected boot sector (%d data packets)." % (c1 - codeFileLodPackets.size)
when BOOTSECTORFASTPF
codeFileLodPackets.reject!{ |i| i.address!=$CS0.address}
puts "Warning: erasing the boot sector! (and discarding all other data, %d sectors to burn)." % (codeFileLodPackets.size)
else # FULLFASTPF
# Do nothing.
=begin
# Tell a warning message if the boot sector is changed.
codeFileLodPackets.each { |i|
if (i.address==$CS0.address)
puts "Warning: erasing the boot sector!"
end
}
=end
end
end
def sendFastpfCommand(connection,cmdStruct,ramAddr,size,flashAddr,fcs,cmd)
#Prepare command structure locally
cmdStruct.ramAddr.setl ramAddr
cmdStruct.size.setl size
cmdStruct.flashAddr.setl flashAddr
cmdStruct.cmd.setl @@C::FPC_NONE
cmdStruct.fcs.setl fcs
#Write the CMD structure in just one Write Block
connection.writeBlock(cmdStruct.address, cmdStruct.memgetl)
cmdStruct.cmd.write(connection, cmd)
end
def checkHostCRCStatus(connection)
crcstatus = $INT_REG_DBG_HOST.CRC.CRC.read(connection)
if(crcstatus != 0)
return " ERROR!! The Host reported some transfer errors! Check your cable."
else
return " INFORMATION : No transfer errors were reported by the Host."
end
end
def getFPCBufferSize(connection,flashProgAccess)
if (USE_FLASHPROG_FPCBUFFERSIZE == 0)
@@fpcBufferSize = @@C::FPC_BUFFER_SIZE
# Checking that the FPC buffer sizes of the script and of the
# flash programmer are the same.
begin
fpcSizeFlashProg = flashProgAccess.fpcSize.read(connection)
if !((fpcSizeFlashProg == 32*1024) || (fpcSizeFlashProg == 4*1024))
puts "You are not using the latest version of the flash programmer."
# Assume that the FPC buffer of the flash programmer is the same as the script one.
fpcSizeFlashProg = @@fpcBufferSize
end
rescue
puts "You are not using the latest version of the XMD."
# Assume that the FPC buffer of the flash programmer is the same as the script one.
fpcSizeFlashProg = @@fpcBufferSize
end
# (When the new version of the flash programmer will be in use,
# we will be able to use fpcSizeFlashProg in the script, instead
# of @@C::FPC_BUFFER_SIZE.)
if (@@fpcBufferSize != fpcSizeFlashProg)
sleep(0.5)
crestart(connection, false)
raise "FPC buffer size mismatch: script=%d, fp=%d" % [@@fpcBufferSize, fpcSizeFlashPro]
end
else
# Getting the FPC buffer sizes from the flash programmer.
begin
@@fpcBufferSize = flashProgAccess.fpcSize.read(connection)
rescue
sleep(0.5)
crestart(connection, false)
raise "Failed to get the FPC buffer size from the flash programmer!"
end
if ((@@fpcBufferSize & 0x3) != 0)
raise "FPC buffer size should be aligned in 4-byte boundary: %d !" % @@fpcBufferSize
end
puts "Got FPC buffer size: %d" % @@fpcBufferSize
end
end
def patchLodPacket(p,address,word)
#Patches a lod packet with a 32-bit word
if(p.address <= address && address < (p.address+p.data.size))
offset = (address - p.address)
p.data[4*offset] = word & 0xFF
p.data[4*offset+1] = (word>>8) & 0xFF
p.data[4*offset+2] = (word>>16) & 0xFF
p.data[4*offset+3] = (word>>24) & 0xFF
#Recalculate FCS
p.rehash
return true
end
return false
end
def dosetFastpfIntensiveVerify(enabled)
@@fastpfIntensiveVerify = enabled
end
def dofastpfXfer(connection, flash_programmer_filename, lod_filename, writeBootSector, verify)
#We want the events
connection.enableEvents(true)
#A bit of cleaning is always welcomed
connection.flushEvents()
#######################################
##### RAMRUN #####
#######################################
flashProgrammerLodPackets = LOD_Read( flash_programmer_filename )
#Ramrun the flash programmer
puts "Ramrunning the flash programmer..."
ramrunXfer(connection, flashProgrammerLodPackets, false)
puts Benchmark.measure{
if(!connection.waitEvent(@@C::EVENT_FLASH_PROG_READY, 15))
raise FlashProgrammerNotReady, "The flash programmer has not sent his READY event!"
end
}
#Store an image of the 2 cmds in memory
flashProgAccess = $map_table.>(connection).flash_prog_access.>(connection)
cmdClass = flashProgAccess.commandDescr[0].class
cmd0addr = flashProgAccess.commandDescr[0].address
cmd1addr = flashProgAccess.commandDescr[1].address
cmds = [cmdClass.new(cmd0addr),cmdClass.new(cmd1addr)]
#Read embedded versions of the protocol
major = flashProgAccess.protocolVersion.major.read(connection)
minor = flashProgAccess.protocolVersion.minor.read(connection)
#Check versions
if(major != @@C::FPC_PROTOCOL_MAJOR || minor != @@C::FPC_PROTOCOL_MINOR)
raise FastpfVersionCheckError, "Version mismatch between XMD and embedded flash programmer! (embedded version: %x.%x vs script version: %x.%x)" % [major, minor, @@C::FPC_PROTOCOL_MAJOR, @@C::FPC_PROTOCOL_MINOR]
end
puts "Verify enabled: " + verify.to_s
puts "Fastpf Protocol Version: %d.%d" % [@@C::FPC_PROTOCOL_MAJOR & 0xFF,@@C::FPC_PROTOCOL_MINOR & 0xFF]
getFPCBufferSize(connection,flashProgAccess)
if (lod_filename == nil)
raise "Sector list cannot be nil for erasion" if (@@eraseSectorList == nil)
# Array of LODPackets representing the sectors to erase.
codeFileLodPackets = [];
@@eraseSectorList.each { |sectorAddress|
p = LODPacket.new
p.address = sectorAddress.to_i
p.data = []
p.fcsChunkSize = @@fpcBufferSize
p.rehash
codeFileLodPackets << p
}
else
codeFileLodPackets = LOD_Read( lod_filename, @@fpcBufferSize )
end
# Filter lod packets depending of the writeBootSector mode
filterLodPackets(codeFileLodPackets,writeBootSector)
totaldata = 0
codeFileLodPackets.each { |p|
totaldata += p.data.size
}
#Store the 2 cmds running states (initially, it's false, then it will always be true)
cmdsRunning = [false,false]
#Store the buffer addresses, we will rotate on all of these
buffers = [flashProgAccess.dataBufferA.read(connection),
flashProgAccess.dataBufferB.read(connection),
flashProgAccess.dataBufferC.read(connection)]
currentCmd = 0
currentBuffer = 0
datadone = 0
#######################################
##### BURN #####
#######################################
puts "Fastpfing..."
puts Benchmark.measure {
codeFileLodPackets.each { |packet|
#Wait for the cmd slot to be free
waitCommandResult(connection, cmdsRunning,currentCmd)
CRVERBOSE("Sector : 0x%08X (cmd:%d)" % [(packet.address - $CS0.address), currentCmd],2)
# Send the ERASE SECTOR command
# Address used by the flash programmer, relative to the flash base.
# addresses stored in .lod files are absolute address (ie start with 0x01 ...)
# so here we remove the address base of the Flash chip Select
sendFastpfCommand(connection,cmds[currentCmd],
0,
0,
packet.address - $CS0.address,
0,
@@C::FPC_ERASE_SECTOR)
#Switch command
cmdsRunning[currentCmd] = true
currentCmd = (currentCmd + 1 )%2
dataStart = 0
fcsNum = 0
while( dataStart < packet.data.size )
#'slice' will take care of uncomplete data packets
data = packet.data.slice(dataStart,@@fpcBufferSize)
CRVERBOSE("Writing at 0x%08X (cmd:%d)" % [(packet.address-$CS0.address+dataStart), currentCmd], 2)
#write packet in RAM
connection.writeBlock(buffers[currentBuffer], data)
begin
waitCommandResult(connection, cmdsRunning, currentCmd) # Wait for cmd slot to be free
rescue FlashCommandTriggeredError => e
# Don't look further if we're not in intensive verify
raise e if(!(@@fastpfIntensiveVerify && verify))
# Else, investigate
status = cmds[currentCmd].cmd.read(connection)
if(status == @@C::FPC_FCS_ERROR)
errmsg = "RAM verify failed during fastpf operation with intensive verify procedure!"
errmsg += checkHostCRCStatus(connection)
raise FastpfRAMVerifyFailed, errmsg
elsif(status == @@C::FPC_FLASH_NOT_AT_FF)
errmsg = "FLASH is not in proper state before writing inside. Not all bytes were at 0xFF!"
errmsg += checkHostCRCStatus(connection)
raise FastpfFLASHVerifyFailed, errmsg
else
#puts status
errmsg = "FLASH DRIVER ERROR: " + e.message
raise e.class, errmsg
end
end
# Slot is free. Send command.
sendFastpfCommand(connection,cmds[currentCmd],
buffers[currentBuffer],
data.size,
packet.address-$CS0.address+dataStart,
packet.hashes[fcsNum] | ( (@@fastpfIntensiveVerify & verify)?(0x8000_0000):(0) ),
@@C::FPC_PROGRAM)
# Update progress. Call progress bar in given code block
datadone += data.size
yield(datadone*1.0/totaldata) if(block_given?())
cmdsRunning[currentCmd] = true # Set Command is in pipe.
currentCmd = (currentCmd + 1 )%2 # Switch command
currentBuffer = (currentBuffer + 1)%3 # Switch buffer
dataStart += @@fpcBufferSize
fcsNum += 1
end
}
} #Bench
#######################################
##### VERIFY #####
#######################################
if(verify)
#Wait for the next command to be free
waitCommandResult(connection, cmdsRunning, currentCmd) # Wait for cmd slot to be free
puts Benchmark.measure {
# Do the verify
verifyList = []
codeFileLodPackets.each{ |p|
datadone = 0
datalen = 0
i = 0
while(datadone < p.data.size)
#Cut into packets of 32K (because some flashes do not support bigger sectors)
datalen = (p.data.size - datadone>@@fpcBufferSize)?(@@fpcBufferSize):(p.data.size - datadone)
verifyList << (p.address+datadone-$CS0.address)
verifyList << (datalen)
verifyList << (p.hashes[i])
i += 1
datadone += datalen
end
}
blockCount = (verifyList.length)/3
puts "Verifying (%d blocks)..." % blockCount
#write verifyList in RAM
connection.writeBlock(buffers[currentBuffer], verifyList.from32to8bits())
#Launch check command
sendFastpfCommand(connection,cmds[currentCmd],
buffers[currentBuffer],
blockCount,
0,
0,
@@C::FPC_CHECK_FCS)
cmdsRunning[currentCmd] = true # Set Command is in pipe.
#Wait for the other command to be finished
currentCmd = (currentCmd + 1 )%2 # Switch command (since we executed one command)
waitCommandResult(connection, cmdsRunning, currentCmd) # Wait for cmd slot to be free
cmdsRunning[currentCmd] = false # Set Command is NOT in pipe.
#Go back to verify command, wait for the result
currentCmd = (currentCmd + 1 )%2 # Switch command
begin
waitCommandResult(connection, cmdsRunning,currentCmd,5) # Set Command is in pipe.
rescue FlashCommandTriggeredError
failedBlock = cmds[currentCmd].ramAddr.read(connection)
puts "First Failed Block : %d" % failedBlock
failedSAdd = verifyList[3*failedBlock]
failedSize = verifyList[3*failedBlock+1]
failedEAdd = failedSAdd + failedSize
errmsg = "Fastpf Verify Failed between 0x%08X and 0x%08X! If you need more information, run the fastpfVerify command." % [failedSAdd, failedEAdd]
errmsg += checkHostCRCStatus(connection)
raise FastpfFLASHVerifyFailed, errmsg
end
#Go to the other command
cmdsRunning[currentCmd] = false # Set Command is NOT in pipe.
currentCmd = (currentCmd + 1 )%2 # Switch command (since we executed one command)
puts "Verify succeeded."
} #Bench
end
#######################################
##### FINALIZE #####
#######################################
# Wait for the two commands in the pipe to be finished
# (if we went through the verify, this is already done,
# the waitCommandResult will return immediately)
waitCommandResult(connection, cmdsRunning, currentCmd) # Wait for cmd slot to be free
cmdsRunning[currentCmd] = false # Set Command is NOT in pipe.
currentCmd = (currentCmd + 1 )%2 # Switch command
waitCommandResult(connection, cmdsRunning, currentCmd) # Wait for cmd slot to be free
cmdsRunning[currentCmd] = false # Set Command is NOT in pipe.
currentCmd = (currentCmd + 1 )%2 # Switch command
puts "Finalizing..."
sendFastpfCommand(connection,cmds[currentCmd],
0,
0,
0,
0,
@@C::FPC_END)
#######################################
##### RESTART #####
#######################################
cmdsRunning[currentCmd] = true # Set Command is in pipe.
waitCommandResult(connection, cmdsRunning, currentCmd) # Wait for cmd slot to be free
cmdsRunning[currentCmd] = false # Set Command is NOT in pipe.
currentCmd = (currentCmd + 1 )%2 # Switch command
puts "Resetting the chip..."
sendFastpfCommand(connection,cmds[currentCmd],
0,
0,
0,
0,
@@C::FPC_RESTART)
cmdsRunning[currentCmd] = true # Set Command is NOT in pipe.
currentCmd = (currentCmd + 1 )%2 # Switch command
waitCommandResult(connection, cmdsRunning, currentCmd) # Wait for cmd slot to be free
cmdsRunning[currentCmd] = false # Set Command is NOT in pipe.
currentCmd = (currentCmd + 1 )%2 # Switch command
waitCommandResult(connection, cmdsRunning, currentCmd) # Wait for cmd slot to be free
puts "Fastpf done."
end
def dofastpfVerifyOnlyXfer(connection, flash_programmer_filename, lod_filename, writeBootSector, indepth)
#We want the events
connection.enableEvents(true)
#A bit of cleaning is always welcomed
connection.flushEvents()
#######################################
##### RAMRUN #####
#######################################
flashProgrammerLodPackets = LOD_Read( flash_programmer_filename )
#Ramrun the flash programmer
puts "Ramrunning the flash programmer..."
ramrunXfer(connection, flashProgrammerLodPackets, false)
if(!connection.waitEvent(@@C::EVENT_FLASH_PROG_READY, 15))
raise FlashProgrammerNotReady, "The flash programmer has not sent his READY event!"
end
#Store an image of the 2 cmds in memory
flashProgAccess = $map_table.>(connection).flash_prog_access.>(connection)
cmdClass = flashProgAccess.commandDescr[0].class
cmd0addr = flashProgAccess.commandDescr[0].address
cmd1addr = flashProgAccess.commandDescr[1].address
cmds = [cmdClass.new(cmd0addr),cmdClass.new(cmd1addr)]
#Read embedded versions of the protocol
major = flashProgAccess.protocolVersion.major.read(connection)
minor = flashProgAccess.protocolVersion.minor.read(connection)
#Check versions
if(major != @@C::FPC_PROTOCOL_MAJOR || minor != @@C::FPC_PROTOCOL_MINOR)
raise FastpfVersionCheckError, "Version mismatch between XMD and embedded flash programmer! (embedded version: %x.%x vs script version: %x.%x)" % [major, minor, @@C::FPC_PROTOCOL_MAJOR, @@C::FPC_PROTOCOL_MINOR]
end
puts "Fastpf Protocol Version: %d.%d" % [@@C::FPC_PROTOCOL_MAJOR & 0xFF,@@C::FPC_PROTOCOL_MINOR & 0xFF]
getFPCBufferSize(connection,flashProgAccess)
if (lod_filename == nil)
raise "LOD file name must be specified for verification!"
else
codeFileLodPackets = LOD_Read( lod_filename, @@fpcBufferSize )
end
# Filter lod packets depending of the writeBootSector mode
filterLodPackets(codeFileLodPackets,writeBootSector)
totaldata = 0
codeFileLodPackets.each { |p|
totaldata += p.data.size
}
#Store the 2 cmds running states (initially, it's false, then it will always be true)
cmdsRunning = [false,false]
#Store the buffer addresses, we will rotate on all of these
buffers = [flashProgAccess.dataBufferA.read(connection),
flashProgAccess.dataBufferB.read(connection),
flashProgAccess.dataBufferC.read(connection)]
currentCmd = 0
currentBuffer = 0
datadone = 0
#######################################
##### VERIFY #####
#######################################
puts Benchmark.measure {
#Start to retrieve FINALIZE information
puts "Retrieving finalize information..."
sendFastpfCommand(connection, cmds[currentCmd],
buffers[currentBuffer],
0,
0,
0,
@@C::FPC_GET_FINALIZE_INFO)
cmdsRunning[currentCmd] = true # Set Command is in pipe.
#Wait for the result.
waitCommandResult(connection, cmdsRunning,currentCmd,5)
magicSectorCount = cmds[currentCmd].size.read(connection)
puts "Magic sector count found: %d" % magicSectorCount
#Read info which is (address,magic)*magicSectorCount = (2*4)*magicSectorCount
magicSectorInfo = connection.readBlock(buffers[currentBuffer],magicSectorCount*2*4).from8to32bits()
#Patch the packets with the finalize information
codeFileLodPackets.each{ |p|
0.step(magicSectorInfo.size-1,2) { |m|
if(patchLodPacket(p,magicSectorInfo[m]+$CS0.address,magicSectorInfo[m+1]))
puts "Patching LOD at %08X with finalize magic number %08X" % [magicSectorInfo[m],magicSectorInfo[m+1]]
end
}
}
cmdsRunning[currentCmd] = false # Command has been treated
currentCmd = (currentCmd + 1 )%2 # Switch command
currentBuffer = (currentBuffer + 1)%3 # Switch buffer
# Do the verify
verifyList = []
codeFileLodPackets.each{ |p|
datadone = 0
datalen = 0
i = 0
while(datadone < p.data.size)
#Cut into packets of 32K (because some flashes do not support bigger sectors)
datalen = (p.data.size - datadone>@@fpcBufferSize)?(@@fpcBufferSize):(p.data.size - datadone)
verifyList << (p.address+datadone-$CS0.address)
verifyList << (datalen)
verifyList << (p.hashes[i])
i += 1
datadone += datalen
end
}
blockCount = (verifyList.length)/3
puts "Verifying (%d blocks)..." % blockCount
#write verifyList in RAM
connection.writeBlock(buffers[currentBuffer], verifyList.from32to8bits() )
#Launch check command
sendFastpfCommand(connection,cmds[currentCmd],
buffers[currentBuffer],
blockCount,
0,
0,
@@C::FPC_CHECK_FCS)
cmdsRunning[currentCmd] = true # Set Command is in pipe.
verifyBadBlocks = []
begin
waitCommandResult(connection, cmdsRunning,currentCmd,5) # Set Command is in pipe.
rescue FlashCommandTriggeredError
# Reread ram buffer.
puts "Hardware detected some errors!"
verifyListValidated = connection.readBlock(buffers[currentBuffer], blockCount * 3 * 4).from8to32bits()
blockCount.times { |i|
if( verifyListValidated[3*i + 2] != verifyList[3*i + 2])
failedSAdd = verifyList[3*i]
failedSize = verifyList[3*i+1]
failedEAdd = failedSAdd + failedSize
puts "Verify failed for block %d from address: 0x%08X to address: 0x%08X" % [i,failedSAdd,failedEAdd]
verifyBadBlocks << i
end
}
end
if(indepth && verifyBadBlocks.size()>0)
puts "Doing in-depth check..."
block = 0
codeFileLodPackets.each{ |p|
datadone = 0
datalen = 0
while(datadone < p.data.size)
#Cut into packets of 32K (because some flashes do not support bigger sectors)
datalen = (p.data.size - datadone>@@fpcBufferSize)?(@@fpcBufferSize):(p.data.size - datadone)
if(verifyBadBlocks.index(block))
#Uh oh this block was marked as bad. Do a complete verify.
puts "Looking deeply into block %d :" % block
dataontarget = connection.readBlock(p.address+datadone,datalen).from8to32bits()
dataonpc = p.data[datadone..datadone+datalen-1].from8to32bits()
i = 0
dataonpc.each{ |e|
if(dataontarget[i] != e)
puts "Data at %08X is %08X and should be %08X" % [p.address+datadone-$CS0.address+4*i,dataontarget[i],e]
end
i += 1
}
end
datadone += datalen
block += 1
end
}
end
if(verifyBadBlocks.size() == 0)
puts "html><font color=green>[VERIFY OK]</font>"
else
puts "html><font color=red>[VERIFY CONTAINED SOME ERRORS]</font>"
end
puts "Verify terminated."
} #Bench
end
def dofastpf(flash_programmer_filename, lod_filename, writeBootSector, verify)
if ($CURRENTCONNECTION.implementsUsb)
puts "html><b>Fastpf V2 over USB</b>"
else
puts "html><b>Fastpf V2 over Host</b>"
end
puts "html>Loading the lod files: <br><i>%s</i>" %File.basename(lod_filename)
puts "html>Using flash programmer: <br><i>%s</i>" %File.basename(flash_programmer_filename)
begin
#Don't use directly the $CURRENTCONNECTION, it could polute other apps
connection = $CURRENTCONNECTION.copyConnection()
connection.open(false)
dofastpfXfer(connection, flash_programmer_filename, lod_filename, writeBootSector, verify) { |prog|
yield(prog) if(block_given?())
}
ensure
connection.close()
end
end
def dofastpfVerifyOnly( flash_programmer_filename , lod_filename, writeBootSector, indepth )
if ($CURRENTCONNECTION.implementsUsb)
puts "html><b>Fastpf verify V2 over USB</b>"
else
puts "html><b>Fastpf verify V2 over Host</b>"
end
puts "html>Loading the lod files: <br><i>%s</i>" %File.basename(lod_filename)
puts "html>Using flash programmer: <br><i>%s</i>" %File.basename(flash_programmer_filename)
begin
#Don't use directly the $CURRENTCONNECTION, it could polute other apps
connection = $CURRENTCONNECTION.copyConnection()
connection.open(false)
dofastpfVerifyOnlyXfer(connection, flash_programmer_filename, lod_filename, writeBootSector, indepth)
ensure
connection.close()
end
end
end
def fastpfProgress(prog)
begin
cwSetProgress(prog*100,100,"%p% (burning)")
rescue Exception
puts( prog*100 )
end
end
addHelpEntry("fastpf", "setFastpfIntensiveVerify", "true_or_false","", "Changes the behaviour of fastpf by enabling/disabling the RAM checking step just after writing each block into RAM.")
def setFastpfIntensiveVerify(enabled)
include FastPf
dosetFastpfIntensiveVerify(enabled)
end
addHelpEntry("fastpf", "fastpfXfer", "connection, flash_programmer_filename, lod_filename, writeBootSector, verify","", "Low level fastpf, its purpose is to be integrated into script, and not launched in an interpreter. The 'connection' parameter should be a CHHostConnection or any heir of this class (see 'rbbase.rb'). 'flashProgrammerPackets' are LODPackets, and should be loaded with the 'LOD_Read()' function, as so as 'codeFilePackets'. They are respectively ruby objects representing the LOD files of the flashprogrammer, and the code to be fastpfed. If writeBootSector is 'true', the boot sector will be squashed. Else, it will be preserved.")
def fastpfXfer(connection, flash_programmer_filename, lod_filename, writeBootSector, verify)
include FastPf
FastPf.dofastpfXfer(connection, flash_programmer_filename, lod_filename, writeBootSector, verify) { |prog|
yield(prog) if(block_given?())
}
end
addHelpEntry("fastpf", "fastpf", "flash_programmer_filename, writeBootsector=FastPf::FULLFASTPF, verify=true, disable_event_sniffer=true","", "Do a fastpf from files. 'flash_programmer_filename' is the path of the compiled flash programmer (compiled as a ramrun for the particular flash type you are going to use). 'lod_filename' is the path to the compiled source code to be 'fastpfed'. Possible values for writeBootSector are FastPf::NOBOOTSECTORFASTPF, FastPf::BOOTSECTORFASTPF, and FastPf::FULLFASTPF.")
def fastpf(flash_programmer_filename, lod_filename, writeBootsector=FastPf::FULLFASTPF , verify=true, disable_event_sniffer=true )
include FastPf
begin
enforce{ cwDisableAutoPoll}
# The event sniffer is a coolwatcher feature only
enforce{ dontSniffEvents if(disable_event_sniffer) }
dofastpf(flash_programmer_filename, lod_filename, writeBootsector, verify) { |prog|
if(block_given?())
yield(prog)
else
fastpfProgress(prog)
end
}
ensure
enforce{ flushEvents() }
enforce{ sniffEvents() }
end
end
addHelpEntry("fastpf", "fastpfVerify", "flash_programmer_filename, lod_filename, writeBootsector=FastPf::FULLFASTPF, indepth=true, disable_event_sniffer = true","", "Do a fastpf verify with a specified flash programmer and lod file.")
def fastpfVerify( flash_programmer_filename, lod_filename, writeBootsector=FastPf::FULLFASTPF, indepth=true, disable_event_sniffer = true )
include FastPf
begin
enforce{ cwDisableAutoPoll}
# The event sniffer is a coolwatcher feature only
enforce{ dontSniffEvents if(disable_event_sniffer) }
dofastpfVerifyOnly(flash_programmer_filename, lod_filename, writeBootsector, indepth)
ensure
enforce{ flushEvents() }
enforce{ sniffEvents() }
end
end
addHelpEntry("fastpf", "fastSectorEraser", "flash_programmer_filename, sector_list, disable_event_sniffer = true","", "Do a fastpf to erase all the sectors whose address present in the integer array 'sector_list'.")
def fastSectorEraser( flash_programmer_filename, sector_list, disable_event_sniffer = true )
@@eraseSectorList = sector_list
fastpf(flash_programmer_filename, nil, FastPf::FULLFASTPF, disable_event_sniffer) { |prog|
yield(prog) if(block_given?())
}
@@eraseSectorList = nil
end
#########################################################
# FOR DEBUGGING PURPOSE #
#########################################################
def fastpfHeavyTest( flash_prog, lod_file, trycount )
succ = 0
fail = 0
trycount.times{ |i|
begin
puts "Launching fastpf number: %d." % i
fastpf(flash_prog, lod_file)
succ += 1
rescue Exception => e
puts "Woops, that one failed. Detail:"
puts e
puts e.backtrace
fail += 1
end
}
puts "Succeeded: %d. Failed: %d." % [succ,fail]
end
|
class User
attr_writer :name
end
class Something
attr_accessor :person
end
class Person < Something
attr_accessor :name
def initialize(n)
@name = n
person = User.new
end
def change_name(n)
person.name = n
end
end
bob = Person.new("Bob")
bob.change_name("Robert")
puts bob.name |
class AddIsDeletedToItemOptionAddon < ActiveRecord::Migration
def self.up
ItemOptionAddon.reset_column_information
unless ItemOptionAddon.column_names.include?('is_deleted')
add_column :item_option_addons, :is_deleted, :integer, :default => 0
end
end
def self.down
ItemOptionAddon.reset_column_information
if ItemOptionAddon.column_names.include?('is_deleted')
remove_column(:item_option_addons, :is_deleted)
end
end
end
|
class ChangePaidAndReceiptFromOrder < ActiveRecord::Migration
def up
rename_column :orders, :paid, :is_paid
rename_column :orders, :receipt, :receipt_no
remove_column :orders, :price
end
def down
end
end
|
require "set"
require "ruby_parser"
require "sexp_processor"
module Deathnote
class MethodProcessor < MethodBasedSexpProcessor
attr_reader :known
def initialize
super
@known = {}
end
def run(file_paths)
file_paths.each do |file_path|
exp = \
begin
file = File.binread(file_path)
rp = RubyParser.for_current_ruby rescue RubyParser.new
rp.process(file, file_path)
rescue Racc::ParseError, RegexpError => e
warn "Parse Error parsing #{file_path}. Skipping."
warn " #{e.message}"
end
process(exp)
end
@known
end
SINGLETON_METHOD_DELIMITER = /^::/
def recognize(target_klass_name, method_name)
if @known[target_klass_name].nil?
@known[target_klass_name] = Set.new
end
fixed_method_name = method_name.sub(SINGLETON_METHOD_DELIMITER, ".")
if @known[target_klass_name].member?(fixed_method_name)
warn "Ignore '#{target_klass_name}#{fixed_method_name}' is already known. It seems to be declared more than once."
else
@known[target_klass_name].add(fixed_method_name)
end
end
def klass_name
super.to_s
end
def process_defn(sexp)
super do
recognize(klass_name, method_name)
process_until_empty(sexp)
end
end
def process_defs(sexp)
super do
recognize(klass_name, method_name)
process_until_empty(sexp)
end
end
end
end
|
# == Schema Information
#
# Table name: appearances
#
# id :integer not null, primary key
# title :string
# description :text
# header_logo :string
# logo :string
# created_at :datetime not null
# updated_at :datetime not null
#
class Appearance < ActiveRecord::Base
validates :title, presence: true
validates :description, presence: true
validates :logo, file_size: { maximum: 1.megabyte }
validates :header_logo, file_size: { maximum: 1.megabyte }
mount_uploader :logo, AttachmentUploader
mount_uploader :header_logo, AttachmentUploader
end
|
require 'rails_helper'
RSpec.describe TestMailer, type: :mailer do
describe 'notify' do
let(:mail) { PurchaseMailer.notify }
it 'renders the headers' do
expect(mail.subject).to eq('テストメール')
expect(mail.to).to eq(['example@example.com'])
end
end
end
|
# frozen_string_literal: true
Dado 'o portfólio possui um bloco de Empresas para esconder perfil' do
create(:block, kind: :hide_companies, side: :right, portfolio_id: @portfolio.id)
end
Quando 'adiciona uma nova Empresa para esconder portfólio' do
@hide_company = attributes_for(:hide_company)
fill_in 'hide-company-name', with: @hide_company[:name]
find('#add-hide-company').click
wait_for_ajax
end
Então 'a Empresa é adicionada ao Portfólio' do
@portfolio.reload
expect(@portfolio.hide_companies.count).to eq 1
expect(page).to have_css('.resource-hide-company', count: 1)
end
Dado 'o portfólio possui 1 empresa para esconder portfólio' do
create(:block, kind: :hide_companies, side: :right, portfolio_id: @portfolio.id)
@skill = create(:hide_company, portfolio_id: @portfolio.id)
end
Quando 'remove a Empresa' do
find('.remove-hide-company').click
wait_for_ajax
end
Então 'a Empresa é removida do Portfólio' do
@portfolio.reload
expect(@portfolio.hide_companies.count).to eq 0
expect(page).to_not have_css('.resource-hide-company')
end
|
require 'spec_helper'
describe PatientsController do
describe "GET #show" do
before :each do
@patient = FactoryGirl.create(:patient, :id => 2)
get :show, {:id => 2}, {}
end
it "renders the show template" do
should render_template('show')
end
it "should have Patient with same id of params" do
expect(@patient.id).to be 2
end
end
end |
require_relative "card"
class EmptyDeckError < StandardError
end
class Deck
attr_reader :cards
def self.new_deck
cards = []
Card::SUITS.each do |suit|
Card::VALUES.keys.each do |value|
cards << Card.new(suit, value)
end
end
Deck.new(cards)
end
def initialize(cards)
@cards = cards
end
def deal( num = 1)
raise EmptyDeckError if num > cards.length
dealt_cards = []
num.times do
dealt_cards << @cards.shift
end
dealt_cards
end
def shuffle
cards.shuffle!
end
def return_cards(cards_array)
cards.concat(cards_array)
end
private
attr_writer :cards
end
|
module Abroaders::Controller
module Onboarding
extend ActiveSupport::Concern
def redirect_if_not_onboarded!
return if current_account.onboarded?
redirect_to onboarding_survey_path
true
end
def onboarding_survey_path
case current_account.onboarding_state
when "home_airports" then survey_home_airports_path
when "travel_plan" then new_travel_plan_path
when "regions_of_interest" then survey_interest_regions_path
when "account_type" then type_account_path
when "eligibility" then survey_eligibility_path
when "award_wallet" then integrations_award_wallet_survey_path
when "owner_cards" then survey_person_cards_path(current_account.owner)
when "owner_balances" then survey_person_balances_path(current_account.owner)
when "companion_cards" then survey_person_cards_path(current_account.companion)
when "companion_balances" then survey_person_balances_path(current_account.companion)
when "spending" then survey_spending_info_path
when "readiness" then survey_readiness_path
when "phone_number" then new_phone_number_path
when "complete" then root_path
end
end
def redirect_if_onboarding_wrong_person_type!
state = current_account.onboarding_state
return unless state =~ /\A(owner|companion)_/ && Regexp.last_match(1) != @person.type
redirect_to onboarding_survey_path
end
module ClassMethods
# if you call this more than once in the same controller, things
# break. So right now there's no way to specify that some actions in the
# same controller are revisitable but others aren't. (See the commit that
# added this comment)
def onboard(*states_and_opts)
opts = states_and_opts.extract_options!
states = states_and_opts
actions = opts.fetch(:with)
skip_before_action :redirect_if_not_onboarded!, only: actions
before_action :redirect_if_on_wrong_onboarding_page!, only: actions
define_method :redirect_if_on_wrong_onboarding_page! do
return if current_account.onboarded? && opts[:revisitable]
return if states.include?(current_account.onboarding_state.to_sym)
redirect_to onboarding_survey_path
end
end
end
end
end
|
class Comment < ApplicationRecord
belongs_to :user
belongs_to :dish
scope :lastest, ->{order updated_at: :desc}
validates :content, presence: true, length: {maximum: Settings.max_comment}
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :ensure_login
helper_method :logged_in?, :current_user
rescue_from ActionController::RoutingError, :with => :rescue404
def not_found
raise ActionController::RoutingError.new('Not Found')
end
#render :file => 'public/404.html', :status => :not_found, :layout => false
protected
def ensure_login
redirect_to login_path unless session[:user_id]
end
def logged_in?
session[:user_id]
end
def current_user
@current_user ||= User.find(session[:user_id])
end
end
|
=begin
Description :
Calculate my age(28) in seconds
Assumption :
Calcualtion does not factor in leap years in calulation
=end
#constants
SECONDS_IN_HOUR = 3600
HOURS_IN_DAY = 24
#variables
days_in_year = 365
seconds_in_year = SECONDS_IN_HOUR * HOURS_IN_DAY * days_in_year
my_age = 28
second_in_my_age = my_age * seconds_in_year
puts "There are #{second_in_my_age} seconds in my age, #{my_age}."
|
module Backseat
module Wrappers
class ElementWrapper < AbstractWrapper
def attribute(name)
@element.getAttribute(name.to_s)
end
def_chainable_delegator :@element, :clear
def_chainable_delegator :@element, :click
def_chainable_delegator :@element, :submit
def_chainable_delegator :@element, :toggle
def_chainable_delegator :@element, :setSelected, :select
def_delegator :@element, :getText, :text
def_delegator :@element, :getValue, :value
def_delegator :@element, :isSelected, :selected?
def_delegator :@element, :isEnabled, :enabled?
def_delegator :@element, :isDisplayed, :displayed?
end
end
end |
# frozen_string_literal: true
# rubocop:todo all
require 'spec_helper'
describe Mongo::Server::Description::Features do
let(:features) do
described_class.new(wire_versions, default_address)
end
describe '#initialize' do
context 'when the server wire version range is the same' do
let(:wire_versions) do
0..3
end
it 'sets the server wire version range' do
expect(features.server_wire_versions).to eq(0..3)
end
end
context 'when the server wire version range min is higher' do
let(:wire_versions) do
described_class::DRIVER_WIRE_VERSIONS.max+1..described_class::DRIVER_WIRE_VERSIONS.max+2
end
it 'raises an exception' do
expect {
features.check_driver_support!
}.to raise_error(Mongo::Error::UnsupportedFeatures)
end
end
context 'when the server wire version range max is higher' do
let(:wire_versions) do
0..4
end
it 'sets the server wire version range' do
expect(features.server_wire_versions).to eq(0..4)
end
end
context 'when the server wire version range max is lower' do
let(:wire_versions) do
described_class::DRIVER_WIRE_VERSIONS.min-2..described_class::DRIVER_WIRE_VERSIONS.min-1
end
it 'raises an exception' do
expect {
features.check_driver_support!
}.to raise_error(Mongo::Error::UnsupportedFeatures)
end
end
context 'when the server wire version range max is lower' do
let(:wire_versions) do
0..2
end
it 'sets the server wire version range' do
expect(features.server_wire_versions).to eq(0..2)
end
end
end
describe '#collation_enabled?' do
context 'when the wire range includes 5' do
let(:wire_versions) do
0..5
end
it 'returns true' do
expect(features).to be_collation_enabled
end
end
context 'when the wire range does not include 5' do
let(:wire_versions) do
0..2
end
it 'returns false' do
expect(features).to_not be_collation_enabled
end
end
end
describe '#max_staleness_enabled?' do
context 'when the wire range includes 5' do
let(:wire_versions) do
0..5
end
it 'returns true' do
expect(features).to be_max_staleness_enabled
end
end
context 'when the wire range does not include 5' do
let(:wire_versions) do
0..2
end
it 'returns false' do
expect(features).to_not be_max_staleness_enabled
end
end
end
describe '#find_command_enabled?' do
context 'when the wire range includes 4' do
let(:wire_versions) do
0..4
end
it 'returns true' do
expect(features).to be_find_command_enabled
end
end
context 'when the wire range does not include 4' do
let(:wire_versions) do
0..2
end
it 'returns false' do
expect(features).to_not be_find_command_enabled
end
end
end
describe '#list_collections_enabled?' do
context 'when the wire range includes 3' do
let(:wire_versions) do
0..3
end
it 'returns true' do
expect(features).to be_list_collections_enabled
end
end
context 'when the wire range does not include 3' do
let(:wire_versions) do
0..2
end
it 'returns false' do
expect(features).to_not be_list_collections_enabled
end
end
end
describe '#list_indexes_enabled?' do
context 'when the wire range includes 3' do
let(:wire_versions) do
0..3
end
it 'returns true' do
expect(features).to be_list_indexes_enabled
end
end
context 'when the wire range does not include 3' do
let(:wire_versions) do
0..2
end
it 'returns false' do
expect(features).to_not be_list_indexes_enabled
end
end
end
describe '#write_command_enabled?' do
context 'when the wire range includes 2' do
let(:wire_versions) do
0..3
end
it 'returns true' do
expect(features).to be_write_command_enabled
end
end
context 'when the wire range does not include 2' do
let(:wire_versions) do
0..1
end
it 'returns false' do
expect {
features.check_driver_support!
}.to raise_exception(Mongo::Error::UnsupportedFeatures)
end
end
end
describe '#scram_sha_1_enabled?' do
context 'when the wire range includes 3' do
let(:wire_versions) do
0..3
end
it 'returns true' do
expect(features).to be_scram_sha_1_enabled
end
end
context 'when the wire range does not include 3' do
let(:wire_versions) do
0..2
end
it 'returns false' do
expect(features).to_not be_scram_sha_1_enabled
end
end
end
describe '#get_more_comment_enabled?' do
context 'when the wire range includes 9' do
let(:wire_versions) do
0..9
end
it 'returns true' do
expect(features).to be_get_more_comment_enabled
end
end
context 'when the wire range does not include 9' do
let(:wire_versions) do
0..8
end
it 'returns false' do
expect(features).to_not be_get_more_comment_enabled
end
end
end
end
|
# -*- coding: utf-8 -*-
module Mushikago
# Hotaruへのアクセスを行うモジュール
module Hotaru
autoload :Client, 'mushikago/hotaru/client'
# domain
autoload :DomainCreateRequest, 'mushikago/hotaru/domain_create_request'
autoload :DomainInfoRequest, 'mushikago/hotaru/domain_info_request'
autoload :DomainListRequest, 'mushikago/hotaru/domain_list_request'
autoload :DomainDeleteRequest, 'mushikago/hotaru/domain_delete_request'
# text
autoload :TextListRequest, 'mushikago/hotaru/text_list_request'
autoload :TextPutRequest, 'mushikago/hotaru/text_put_request'
autoload :TextDeleteRequest, 'mushikago/hotaru/text_delete_request'
autoload :TextTagsetRequest, 'mushikago/hotaru/text_tagset_request'
autoload :TextGetRequest, 'mushikago/hotaru/text_get_request'
# classifier
autoload :ClassifierJudgeRequest, 'mushikago/hotaru/classifier_judge_request'
# collocation
autoload :CollocationListRequest, 'mushikago/hotaru/collocation_list_request'
autoload :CollocationDeleteRequest, 'mushikago/hotaru/collocation_delete_request'
autoload :CollocationGetRequest, 'mushikago/hotaru/collocation_get_request'
autoload :CollocationCreateRequest, 'mushikago/hotaru/collocation_create_request'
autoload :CollocationDownloadRequest, 'mushikago/hotaru/collocation_download_request'
autoload :CollocationWordlistRequest, 'mushikago/hotaru/collocation_wordlist_request'
# tag
autoload :TagPutRequest, 'mushikago/hotaru/tag_put_request'
autoload :TagDeleteRequest, 'mushikago/hotaru/tag_delete_request'
autoload :TagListRequest, 'mushikago/hotaru/tag_list_request'
# word
autoload :WordListRequest, 'mushikago/hotaru/word_list_request'
autoload :WordGetRequest, 'mushikago/hotaru/word_get_request'
# dictionary
autoload :DictionaryPutRequest, 'mushikago/hotaru/dictionary_put_request'
autoload :DictionaryListRequest, 'mushikago/hotaru/dictionary_list_request'
autoload :DictionaryDeleteRequest, 'mushikago/hotaru/dictionary_delete_request'
end
end
|
class AddCcToToReplyAction < ActiveRecord::Migration
def change
add_column :reply_actions, :cc_to, :text, :default => nil
end
end
|
require 'spec_helper'
require_relative '../../lib/right_branch/commands/change_pull_request_target'
describe RightBranch::Commands::ChangePullRequestTarget do
subject { described_class.new(StringIO.new) }
describe '#run!' do
let(:updater) { double }
before do
allow(subject).to receive(:build_options).and_return({})
end
it 'aborts on not found error' do
allow(updater).to receive(:run!).and_raise \
::Octokit::NotFound
allow(subject).to receive(:updater).and_return updater
expect { subject.run! }.to raise_error SystemExit,
'Pull request not found'
end
it 'aborts on unauthorized error' do
allow(updater).to receive(:run!).and_raise \
::Octokit::Unauthorized
allow(subject).to receive(:updater).and_return updater
expect { subject.run! }.to raise_error SystemExit,
'Invalid credentials to update pull request'
end
it 'aborts on invalid branch error' do
allow(updater).to receive(:run!).and_raise \
::Octokit::UnprocessableEntity
allow(subject).to receive(:updater).and_return updater
expect { subject.run! }.to raise_error SystemExit,
'Invalid branch'
end
end
describe '#missing_required_keys' do
before do
stub_const("#{described_class}::REQUIRED_OPTIONS", [:a, :b])
end
it 'returns not provided keys' do
actual = subject.missing_opt_keys b: 'foo'
expect(actual).to eq([:a])
end
it 'returns blank keys' do
actual = subject.missing_opt_keys a: 'foo', b: ''
expect(actual).to eq([:b])
end
it 'returns empty array if all provided' do
actual = subject.missing_opt_keys a: 'foo', b: 'bar'
expect(actual).to eq([])
end
end
describe '#build_options' do
it 'aborts when keys are missing' do
allow(subject).to receive(:missing_opt_keys).and_return [:a, :b]
allow(subject).to receive(:build_opt_parser)
.and_return double(parse!: true, to_s: 'wow')
expect { subject.build_options }.to raise_error SystemExit,
"Missing required options: a, b\n\nwow"
end
end
describe '#build_credentials' do
it 'returns access token if present' do
actual = subject.send :build_credentials,
access_token: 'omg', username: 'doge', password: 'wow'
expect(actual).to eq({ access_token: 'omg'})
end
it 'returns username and password if no access token is present' do
actual = subject.send :build_credentials,
username: 'doge', password: 'wow'
expect(actual).to eq({ login: 'doge', password: 'wow' })
end
end
end
|
class BloggersController < ApplicationController
def new
@blogger = Blogger.new
end
def create
@blogger = Blogger.create(blogger_params)
if @blogger.valid?
redirect_to blogger_path(@blogger)
else
render :new
end
end
def show
@blogger = Blogger.find(params[:id])
end
private
def blogger_params
params.require(:blogger).permit(:name,:bio,:age)
end
end |
require 'rails_helper'
RSpec.describe Game do
let(:x_player) {Player.create(:email => "test")}
let(:game) {GamesService.create_game(x_player.id)}
describe "#new_game?" do
context "game with no moves" do
it "returns true" do
expect(game.new_game?).to be true
end
end
context "game with moves" do
before do
Move.create!(:player_id => x_player.id, :game_id => game.id, :position => 0)
end
it "return false" do
expect(game.new_game?).to be false
end
end
end
end
|
require 'csv'
module GhBbAudit
class UsersList
def initialize(path_to_csv_file)
@user_csv_file_path = path_to_csv_file
end
def all_users
#Not rescuing here, as we should crash if we can not get userlist
@users ||= ::CSV.read(@user_csv_file_path).flatten.uniq
end
end
end |
json.array!(@bill_orders) do |bill_order|
json.extract! bill_order, :id, :folio, :issued, :status
json.url bill_order_url(bill_order, format: :json)
end
|
module ApplicationHelper
def badge_image_for(user)
unless user.badges.empty?
image_tag "#{user.badges.last.name}_red.svg"
end
end
def badge_title_for(user)
unless user.badges.empty?
"#{user.badges.last.name.split('_').join(" ").titleize}"
end
end
def student_progress_percentage(user)
pontuation_information = user.next_badge?(:student)
100.0 * (pontuation_information[:next_badge_points] - pontuation_information[:points]) / pontuation_information[:next_badge_points]
end
def student_progress(user)
pontuation_information = user.next_badge?(:student)
pontuation_information[:points]
end
end
|
CheckUp::Application.routes.draw do
devise_for :users
get '/routines/get_event', to: 'events#show', as: 'event_show'
post '/routines/tag_event', to: 'tags#tag_event', as: 'tag_event'
patch '/setup/tag', to: 'tags#update', as: 'update_tag'
post '/setup/tag', to: 'tags#create', as: 'new_tag'
patch '/setup/category', to: 'categories#update', as: 'update_category'
post '/setup/category', to: 'categories#create', as: 'new_category'
patch '/setup/save_routine', to: 'tags#save_routine', as: 'save_routine'
get '/setup/color', to: 'pages#get_color', as: 'get_color'
get '/setup', to: 'pages#setup_page', as: 'setup'
get '/events', to: 'pages#events_page', as: 'events', defaults: { events: true }
get '/routines', to: 'pages#routines_page', as: 'routines'
root 'static_pages#home'
end
|
require File.dirname(__FILE__) + '/../../spec_helper'
describe Admin::EventsController do
dataset :users
integrate_views
before(:each) do
login_as :existing
end
def mock_event
mock_model(Event, {
:name => "Happy Fun Time",
:scheduled_at => Time.now
})
end
context 'index' do
before(:each) do
Event.stub!(:find).and_return(@events = [mock_event])
end
it 'should render the index template' do
get 'index'
response.should be_success
response.should render_template('index')
end
end
context 'new' do
it 'should render the edit template' do
get 'new'
response.should be_success
response.should render_template('edit')
end
end
context 'create' do
before(:each) do
Event.stub!(:new).and_return(@event = mock_event)
end
it 'should create a new event and redirect' do
@event.should_receive(:save).and_return(true)
post 'create', :event => { :name => 'new name' }
response.should be_redirect
response.should redirect_to(admin_events_path)
end
it 'should re-render the edit template if save fails' do
@event.should_receive(:save).and_return(false)
post 'create', :event => { :name => 'new name' }
response.should be_success
response.should render_template('edit')
flash[:error].should_not be_nil
end
end
context 'edit' do
before(:each) do
Event.stub!(:find).and_return(@event = mock_event)
end
it 'should render the edit template' do
get 'edit', :id => 1
response.should be_success
response.should render_template('edit')
end
end
context 'update' do
before(:each) do
Event.stub!(:find).and_return(@event = mock_event)
end
it 'should update the program and redirect' do
@event.should_receive(:update_attributes).and_return(true)
put 'update', :id => 1, :event => { :name => 'new name' }
response.should be_redirect
response.should redirect_to(admin_events_path)
end
it 'should re-render the edit template if update fails' do
@event.should_receive(:update_attributes).and_return(false)
put 'update', :id => 1, :event => { :name => 'new name' }
response.should be_success
response.should render_template('edit')
flash[:error].should_not be_nil
end
end
context 'destroy' do
before(:each) do
Event.stub!(:find).and_return(@event = mock_event)
end
it 'should destroy the program and redirect' do
@event.should_receive(:destroy).and_return(true)
delete 'destroy', :id => 1
response.should be_redirect
response.should redirect_to(admin_events_path)
end
end
end
|
class ProPublicaService
def initialize
@conn = Faraday.new(url: "https://api.propublica.org") do |faraday|
faraday.headers["X-API-KEY"] = ENV["propublica_key"]
faraday.adapter Faraday.default_adapter
end
end
def filter_by_state(state)
response = get_response(state)
parse_response(response)
end
def get_response(state)
conn.get("/congress/v1/members/house/#{state}/current.json")
end
def parse_response(response)
JSON.parse(response.body, symbolize_names: true)[:results]
end
private
attr_reader :conn
end
|
require 'jsonapi/formatter'
module JSONAPI
class Configuration
attr_reader :json_key_format,
:link_format,
:key_formatter,
:link_formatter
def initialize
# :underscored, :camelized, :dasherized, or custom
self.json_key_format = :dasherized
# :underscored, :camelized, :dasherized, or custom
self.link_format = :dasherized
end
def json_key_format=(format)
@json_key_format = format
@key_formatter = JSONAPI::Formatter.formatter_for(format)
end
def link_format=(format)
@link_format = format
@link_formatter = JSONAPI::Formatter.formatter_for(format)
end
end
class << self
attr_accessor :configuration
end
@configuration ||= Configuration.new
def self.configure
yield(@configuration)
end
end
|
class Api::V2::LecturesController < ApplicationController
before_action :set_lecture, only: [:show, :edit, :update, :destroy]
@LECTURE_UPDATE_TIME = "com.planningdev.kyutech.update"
def allLectures
@campus_id = params[:campus_id]
@server_time = params[:server_time]
if @campus_id == nil
@lectures = Lecture.all
else
@lectures = Lecture.where("campus_id = ?", @campus_id)
end
@SYLLABUS_UPDATE_TIME = "com.planningdev.kyutech.lecture.update"
@cache_time = (Rails.cache.read @SYLLABUS_UPDATE_TIME)
if @server_time == nil || @cache_time == nil
render json: { "data" => @lectures, "server_time" => @cache_time}
else
if @server_time.to_i == @cache_time.to_i
render json: { "data" => Array.new, "server_time" => @cache_time}
else
render json: { "data" => @lectures, "server_time" => @cache_time}
end
end
end
def lecture
@id = params[:id]
render json: Lecture.find_by(:id => @id)
end
end
|
require 'spec_helper'
describe 'assignments/edit' do
it "contains a form" do
stub_template 'assignments/_form' => "<form></form>"
render
expect(page).to have_selector 'form'
end
end
|
module ReportsKit
module Reports
module Data
class PopulateTwoDimensions
attr_accessor :serieses, :dimension, :second_dimension, :sparse_serieses_dimension_keys_values
def initialize(sparse_serieses_dimension_keys_values)
self.serieses = sparse_serieses_dimension_keys_values.keys
self.dimension = serieses.first.dimensions[0]
self.second_dimension = serieses.first.dimensions[1]
self.sparse_serieses_dimension_keys_values = sparse_serieses_dimension_keys_values
end
def perform
serieses_populated_dimension_keys_values
end
private
def serieses_populated_dimension_keys_values
serieses_dimension_keys_values = {}
secondary_keys_sums = Hash.new(0)
serieses_populated_primary_keys_secondary_keys_values.each do |series, primary_keys_secondary_keys_values|
primary_keys_secondary_keys_values.each do |primary_key, secondary_keys_values|
secondary_keys_values.each do |secondary_key, value|
secondary_keys_sums[secondary_key] += value
end
end
end
sorted_secondary_keys = secondary_keys_sums.sort_by(&:last).reverse.map(&:first)
serieses_populated_primary_keys_secondary_keys_values.each do |series, primary_key_secondary_keys_values|
serieses_dimension_keys_values[series] = {}
primary_key_secondary_keys_values.each do |primary_key, secondary_keys_values|
secondary_keys_values = secondary_keys_values.sort_by { |key, _| sorted_secondary_keys.index(key) }
secondary_keys_values.each do |secondary_key, value|
dimension_key = [primary_key, secondary_key]
serieses_dimension_keys_values[series][dimension_key] = value
secondary_keys_sums[secondary_key] += value
end
end
end
serieses_dimension_keys_values
end
def serieses_populated_primary_keys_secondary_keys_values
@populated_dimension_keys_values ||= begin
serieses_populated_primary_keys_secondary_keys_values = {}
serieses.each do |series|
serieses_populated_primary_keys_secondary_keys_values[series] = {}
primary_keys.each do |primary_key|
serieses_populated_primary_keys_secondary_keys_values[series][primary_key] = {}
secondary_keys.each do |secondary_key|
value = serieses_primary_keys_secondary_keys_values[series][primary_key].try(:[], secondary_key) || 0
serieses_populated_primary_keys_secondary_keys_values[series][primary_key][secondary_key] = value
end
end
end
serieses_populated_primary_keys_secondary_keys_values
end
end
def serieses_primary_keys_secondary_keys_values
@serieses_primary_keys_secondary_keys_values ||= begin
serieses_primary_keys_secondary_keys_values = {}
sparse_serieses_dimension_keys_values.each do |series, dimension_keys_values|
serieses_primary_keys_secondary_keys_values[series] = {}
dimension_keys_values.each do |(primary_key, secondary_key), value|
primary_key = primary_key.to_date if primary_key.is_a?(Time)
secondary_key = secondary_key.to_date if secondary_key.is_a?(Time)
serieses_primary_keys_secondary_keys_values[series][primary_key] ||= {}
serieses_primary_keys_secondary_keys_values[series][primary_key][secondary_key] = value
end
end
serieses_primary_keys_secondary_keys_values
end
end
def dimension_keys
@dimension_keys ||= sparse_serieses_dimension_keys_values.values.map(&:keys).reduce(&:+).uniq
end
def primary_keys
@primary_keys ||= begin
keys = Utils.populate_sparse_keys(dimension_keys.map(&:first).uniq, dimension: dimension)
unless dimension.configured_by_time?
limit = dimension.dimension_instances_limit
keys = keys.first(limit) if limit
end
keys
end
end
def secondary_keys
@secondary_keys ||= begin
keys = Utils.populate_sparse_keys(dimension_keys.map(&:last).uniq, dimension: second_dimension)
limit = second_dimension.dimension_instances_limit
keys = keys.first(limit) if limit
keys
end
end
end
end
end
end
|
class Incollection < ActiveRecord::Base
has_many :publications, through: :publication_incollections
validates :author, :title, :booktitle, :publisher, :year, presence: true
def required_fields
%w(author title publisher year booktitle)
end
def self.required_fields
%w(author title publisher year booktitle)
end
end
|
unless File.exist?('./Gemfile')
raise <<-MESSAGE
Could not find a Gemfile. Please run any of:
thor rails:use 3-0-stable
thor rails:use master
thor rails:use VERSION (where VERSION is any released version)
MESSAGE
end
require "bundler"
Bundler.setup
#Bundler::GemHelper.install_tasks
require 'rake'
require 'yaml'
require 'cucumber/rake/task'
require 'rubygems'
begin
Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
require 'rake'
require 'jeweler'
Jeweler::Tasks.new do |gem|
# gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
gem.version = "0.1.0"
gem.name = "rspec-rails-extra-routing"
gem.homepage = "http://github.com/HugoLnx/rspec-rails-extra-routing"
gem.license = "MIT"
gem.summary = %Q{Extension to rspec-rails that allows some shortcuts in routing tests}
gem.description = <<STRING
Extension to rspec-rails that allows some shortcuts in routing tests.\n
With it, this:\n
describe "users routes" do\n
describe "GET /" do\n
it{{:get => '/'}.should route_to "users#index"}\n
end\n
\n
describe "POST /" do\n
it{{:post => '/'}.should be_routable}\n
end\n
end\n
\n
can be written like this:\n
\n
describe "users routes" do\n
get('/').should route_to "users#index"\n
post('/').should be_routable\n
end\n
STRING
gem.email = "hugo.roque@caelum.com.br"
gem.authors = ["Hugo Roque (a.k.a HugoLnx)"]
# Include your dependencies below. Runtime dependencies are required when using your gem,
# and development dependencies are only needed for development (ie running rake tasks, tests, etc)
gem.add_dependency 'rspec-rails', '>= 2.5.0'
# gem.add_development_dependency 'rspec', '> 1.2.3'
gem.files = FileList['lib/**/*.rb'].to_a
end
Jeweler::RubygemsDotOrgTasks.new
require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.libs << 'lib' << 'test'
test.pattern = 'test/**/test_*.rb'
test.verbose = true
end
require 'rcov/rcovtask'
Rcov::RcovTask.new do |test|
test.libs << 'test'
test.pattern = 'test/**/test_*.rb'
test.verbose = true
end
task :default => :test
require 'rake/rdoctask'
Rake::RDocTask.new do |rdoc|
version = File.exist?('VERSION') ? File.read('VERSION') : ""
rdoc.rdoc_dir = 'rdoc'
rdoc.title = "rspec-rails-extra-routing #{version}"
rdoc.rdoc_files.include('README*')
rdoc.rdoc_files.include('lib/**/*.rb')
end
Cucumber::Rake::Task.new(:cucumber)
namespace :generate do
desc "generate a fresh app with rspec installed"
task :app do |t|
unless File.directory?('./tmp/example_app')
sh "bundle exec rails new ./tmp/example_app"
sh "cp ./templates/Gemfile-base ./tmp/example_app/"
sh "cp ./templates/Gemfile ./tmp/example_app/"
sh "cp ./templates/Gemfile.lock ./tmp/example_app/"
end
end
desc "generate a bunch of stuff with generators"
task :stuff do
in_example_app "rake rails:template LOCATION='../../templates/generate_stuff.rb'"
end
end
def in_example_app(command)
Dir.chdir("./tmp/example_app/") do
Bundler.with_clean_env do
sh command
end
end
end
namespace :db do
task :migrate do
in_example_app "rake db:migrate"
end
namespace :test do
task :prepare do
in_example_app "rake db:test:prepare"
end
end
end
desc "run a variety of specs against the generated app"
task :smoke do
in_example_app "rake rails:template --trace LOCATION='../../templates/run_specs.rb'"
end
desc 'clobber generated files'
task :clobber do
rm_rf "pkg"
rm_rf "tmp"
rm "Gemfile.lock" if File.exist?("Gemfile.lock")
end
namespace :clobber do
desc "clobber the generated app"
task :app do
rm_rf "tmp/example_app"
end
end
desc "Push docs/cukes to relishapp using the relish-client-gem"
task :relish, :version do |t, args|
raise "rake relish[VERSION]" unless args[:version]
sh "relish push rspec/rspec-rails:#{args[:version]}"
end
task :default => [:spec, "clobber:app", "generate:app", "generate:stuff", :smoke, :cucumber]
|
module MTMD
module FamilyCookBook
class MenuItem < Sequel::Model(:menu_items)
SLOTS = %w'empty MTMD::FamilyCookBook::Slot::Breakfast MTMD::FamilyCookBook::Slot::Lunch MTMD::FamilyCookBook::Slot::Dinner'
plugin :timestamps, :update_on_create => true
many_to_many :menus,
:class => 'MTMD::FamilyCookBook::Menu',
:left_key => :menu_items_id,
:right_key => :menu_id
many_to_many :recipes,
:class => 'MTMD::FamilyCookBook::Recipe',
:left_key => :menu_items_id,
:right_key => :recipe_id
many_to_one :shopping_lists,
:class => 'MTMD::FamilyCookBook::ShoppingList',
:key => :id,
:primary_key => :menu_item_id
plugin :association_dependencies,
:menus => :nullify,
:recipes => :nullify
def before_save
super
order_slots
end
def order_slots
return 0 unless SLOTS.include?(slot)
self.slot_order = 1 if slot == 'MTMD::FamilyCookBook::Slot::Breakfast'
self.slot_order = 2 if slot == 'MTMD::FamilyCookBook::Slot::Lunch'
self.slot_order = 3 if slot == 'MTMD::FamilyCookBook::Slot::Dinner'
end
end
end
end
|
require_relative 'traac'
require_relative 'raac'
module Parameters
TIME_STEPS = 500
RUNS = 10
# how many data owners to use and evaluate
OWNER_COUNT = 200
# experimental condition (RAAC classes)
MODELS = [Raac,TraacSTOnly,TraacSTOT]
# settings for the data owners, data objects and policies
# in the paper, we have owners coming back and reassessing undefined
# sharing at a later time. We don't want to do this so we define two
# undefined zones, representing the user's post-sharing preferences,
# and allow the trust model to immediately update. This is
# equivalent to the data owner classifying a sharing action as good
# or bad immediately after the sharing (into undefined) has been
# done.
ZONES = [:share, :read, :deny, :undefined_good, :undefined_bad]
RISK_DOMAINS = {
d1: [0.0,0.2],
d2: [0.2,0.6],
d3: [0.6,1.0]
}
SENSITIVITY_TO_LOSS = {
low: 0.2,
med: 0.5,
high: 1
# low: 0.5,
# med: 0.5,
# high: 0.5
}
# this is the ID of the risk domain that constitutes a rejection of the request
REJECT_DOMAIN = :d3
OBLIGATIONS = [
:system_log_request,
:user_send_email,
:fill_form,
:none
]
MITIGATION_STRATEGIES = {
ms1:
{
d1: :none,
d2: :user_send_email,
d3: :none,
},
ms2:
{
d1: :none,
d2: :user_send_email,
d3: :none,
},
ms3:
{
d1: :none,
d2: :user_send_email,
d3: :none,
},
}
SENSITIVITY_TO_STRATEGIES = {
high: :ms1,
med: :ms2,
low: :ms3
}
# PARAMETERS SPECIFIC TO RAAC
# Probability of one of an agent's obligations hitting a deadline in
# any time step - thus permanent decrease of risk budget (easier
# than implementing TTL... although might be more rigorous)
OBLIGATION_TIMEOUT_PROB = 0.1
INITIAL_BUDGET = 15
BUDGET_DECREMENT = 1
# PARAMETERS SPECIFIC TO TRAAC
ST_PRIOR = 0
OT_PRIOR = 1
# we will use 'g' to mean good (trustworthy) and b to mean bad, for sharing trust and obligation trust respectively
TYPES = {
gg: { sharing: 0.8, obligation: 0.5, count: 10 },
gb: { sharing: 0.8, obligation: 0.1, count: 10 },
bg: { sharing: 0.2, obligation: 0.5, count: 10 },
bb: { sharing: 0.2, obligation: 0.1, count: 10 }
}
end
|
module RestoreAgent::Handler
class Agent
require 'restore_agent/object/base'
require 'restore_agent/object/root'
require 'restore_agent/object/filesystem'
require 'restore_agent/object/file'
require 'restore_agent/object/directory'
require 'restore_agent/object/mysql_server'
require 'restore_agent/object_db'
attr_reader :root
def initialize(server)
@server = server
@root = RestoreAgent::Object::Root.new
@snapshots = {}
end
def list_objects(path)
puts "query for path: #{path}"
if o = @root.find_object(path)
return o.list_objects
end
return []
end
def new_snapshot(id, objects)
puts "new snapshot: #{id}"
# XXX check for its existence
@snapshots[id] = RestoreAgent::Handler::Snapshot.new(@server, id, objects)
@server.add_handler("snapshot.#{id}", @snapshots[id])
return "OK"
end
# XXX only for testing
def get_file(path)
return File.new(path)
end
end
end |
module LookerSDK
# Authentication methods for {LookerSDK::Client}
module Authentication
attr_accessor :access_token_type, :access_token_expires_at
# This is called automatically by 'request'
def ensure_logged_in
authenticate unless token_authenticated? || @skip_authenticate
end
def without_authentication
begin
old_skip = @skip_authenticate || false
@skip_authenticate = true
yield
ensure
@skip_authenticate = old_skip
end
end
# Authenticate to the server and get an access_token for use in future calls.
def authenticate
raise "client_id and client_secret required" unless application_credentials?
set_access_token_from_params(nil)
without_authentication do
post('/login', {}, :query => application_credentials)
raise "login failure #{last_response.status}" unless last_response.status == 200
set_access_token_from_params(last_response.data)
end
end
def set_access_token_from_params(params)
reset_agent
if params
@access_token = params[:access_token]
@access_token_type = params[:token_type]
@access_token_expires_at = Time.now + params[:expires_in]
else
@access_token = @access_token_type = @access_token_expires_at = nil
end
end
def logout
without_authentication do
result = !!@access_token && ((delete('/logout') ; delete_succeeded?) rescue false)
set_access_token_from_params(nil)
result
end
end
# Indicates if the client has OAuth Application
# client_id and client_secret credentials
#
# @see look TODO docs link
# @return Boolean
def application_credentials?
!!application_credentials
end
# Indicates if the client has an OAuth
# access token
#
# @see look TODO docs link
# @return [Boolean]
def token_authenticated?
!!(@access_token && (@access_token_expires_at.nil? || @access_token_expires_at > Time.now))
end
private
def application_credentials
if @client_id && @client_secret
{
:client_id => @client_id,
:client_secret => @client_secret
}
end
end
def load_credentials_from_netrc
return unless netrc?
require 'netrc'
info = Netrc.read File.expand_path(netrc_file)
netrc_host = URI.parse(api_endpoint).host
creds = info[netrc_host]
if creds.nil?
# creds will be nil if there is no netrc for this end point
looker_warn "Error loading credentials from netrc file for #{api_endpoint}"
else
self.client_id = creds[0]
self.client_secret = creds[1]
end
rescue LoadError
looker_warn "Please install netrc gem for .netrc support"
end
end
end
|
class Api::UsersController < ApplicationController
before_action :ensure_authorization, only: [:update]
def show
@user = User.find(params[:id])
render 'api/users/show'
end
def create
@user = User.new(user_params)
demo_id = User.find_by(username: "Guest").id
if @user.save
Follow.create(following_id: @user.id, follower_id: demo_id)
Follow.create(following_id: demo_id, follower_id: @user.id)
login(@user)
render 'api/users/show'
else
render json: { authForm: @user.errors.full_messages }, status: 422
end
end
def update
@user = User.find(params[:id])
@user.update(user_params)
render 'api/users/show'
end
private
def user_params
params
.require(:user)
.permit(:username, :password, :bio, :cover_url, :profile_url)
end
def ensure_authorization
current_user.id == params[:id]
end
end
|
#
# Exodus::SeatTable
#
# 席の位置と苗字のデータを持ったテキストエントリをGtk::Tableに格納する
$:.unshift File.dirname(__FILE__)
require 'rubygems'
require 'gtk2'
require './lib/new_seat_generator'
require './gui/exit_button'
module Exodus
class SeatTable
def initialize(width, height, target_name)
@width = width
@height = height
@target_name = target_name
end
def attach_some_entries
seat_table = Gtk::Table.new(@width, @height, true)
generator = Exodus::NewSeatGenerator.new
entry_object_array = generator.generate(Time::now.nsec, @target_name)
generator.save_new_seat(generator.name_array.shuffle!)
w = 0
h = 0
entry_object_array.each do |entry|
seat_table.attach(entry, w, w+1, h, h+1, xop = Gtk::FILL|Gtk::EXPAND, yop = Gtk::FILL|Gtk::EXPAND, 5, 5)
w += 1
if w >= @width then
h += 1
w = 0
end
end
return seat_table
end
def assemble_sub_window_layout
win = Gtk::Window.new("New Seat Table")
win.border_width = 15
win.signal_connect("destroy") { win.destroy }
label = Gtk::Label.new("Front" ,use_underline = nil)
label.set_justify(Gtk::JUSTIFY_CENTER)
sub_window_layout = Gtk::VBox.new(false,10)
exit_button = Exodus::ExitButton.new.exit_button(win)
button_positioning_box = Gtk::HBox.new(true,0)
button_positioning_box.pack_start(exit_button,false,false,200)
seat_table = attach_some_entries
sub_window_layout.pack_end(button_positioning_box, true, false, 10)
sub_window_layout.pack_end(seat_table, true, false, 5)
sub_window_layout.pack_end(label, false, false, 5)
sub_window_layout.pack_end(exit_button, false, false)
win.add(sub_window_layout)
end
def show_sub_window
win = assemble_sub_window_layout
win.show_all
end
end
end
|
WIN_COMBINATIONS = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
]
def move(board, index, current_player)
board[index] = current_player
end
def valid_move?(board, index)
index.between?(0, 8) && !position_taken?(board, index)
end
def turn(board)
puts "Please enter 1-9:"
input = gets.strip
index = input_to_index(input)
if valid_move?(board, index)
move(board, index, current_player(board))
display_board(board)
else
turn(board)
end
end
def turn_count(board)
count_plays = Proc.new { |cell| cell == "O" || cell == "X" }
board.filter(&count_plays).length
end
def current_player(board)
turns = turn_count(board)
if turns == 0
"X"
else
turns % 2 == 0 ? "X" : "O"
end
end
def position_taken?(board, index)
!board[index].is_a? Integer
end
def won?(board)
winning_combo = WIN_COMBINATIONS
.filter { |combo|
combo.all? { |index| position_taken?(board, index) }
}
.filter { |combo|
combo.map { |index| board[index] }.uniq.length == 1
}
winning_combo.empty? ? nil : winning_combo.first
end
def full?(board)
(0..8).to_a.map { |i| position_taken?(board, i) }.all?
end
def draw?(board)
full?(board) && !won?(board)
end
def over?(board)
draw?(board) || won?(board)
end
def winner(board)
if !won?(board) then return nil end
winning_combo = WIN_COMBINATIONS
.filter { |combo|
combo.all? { |index| position_taken?(board, index) }
}
.filter { |combo|
combo.map { |index| board[index] }.uniq.length == 1
}
.first
.map { |i| board[i] }
.uniq
.first
end
|
Rails.application.routes.draw do
devise_for :users
root to: 'pages#home'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :restaurants do
resources :dishes, only: [ :index, :show]
end
resources :offers, only: [ :new, :create, :show ]
resources :users, only: [ :show ]
resource :profil, only: [ :show, :edit, :update ]
end
|
RSpec.feature 'Rich Editor Settings', :js do
stub_authorization!
context '#edit' do
scenario 'have default elements' do
visit spree.edit_admin_editor_settings_path
within('legend') do
expect(page).to have_text 'Rich Editor'
end
expect(page).to have_field 'ids', with: 'product_description page_body'
end
end
context 'when changing editors' do
given(:product) { create(:product) }
context 'tinymce' do
background do
# We must copy the tinymce.yml file into the dummy app to use TinyMCE.
@destination_root = File.expand_path('../../../dummy', __FILE__)
FileUtils.rm_rf(@destination_root + '/config/tinymce.yml')
FileUtils.cp(File.expand_path('../../../../lib/templates/config/tinymce.yml', __FILE__), @destination_root + '/config/tinymce.yml')
end
scenario 'will be applied when used' do
visit spree.edit_admin_editor_settings_path
select2 'TinyMCE', from: 'Rich Editor engine'
click_button 'Update'
visit spree.edit_admin_product_path(product)
expect(page).to have_css '.mce-tinymce', match: :one
end
end
context 'ckeditor' do
scenario 'will be applied when used' do
visit spree.edit_admin_editor_settings_path
select2 'CKEditor', from: 'Rich Editor engine'
click_button 'Update'
visit spree.edit_admin_product_path(product)
expect(page).to have_css '.cke_editor_product_description', match: :one
end
end
end
end
|
module Call::Operation
class Create < Trailblazer::Operation
class Present < Trailblazer::Operation
pass :populate_errors
step :build_model
step Contract::Build(constant: Call::Contract::Form)
def populate_errors(ctx, **)
ctx[:errors] = []
end
def build_model(ctx, **)
ctx[:model] = Call.new
ctx[:model].build_customer
end
end
step Subprocess(Present)
step Contract::Validate(key: :call)
step :prepopulate
step Contract::Persist()
fail :log_errors
def prepopulate(ctx, current_user:, **)
ctx['contract.default'].prepopulate!(user_id: current_user.id)
end
def log_errors(ctx, model:, **)
contract = ctx['contract.default']
ctx[:errors] << contract.errors.full_messages.presence || contract.model.errors.full_messages
ctx[:errors] = ctx[:errors].compact.flatten
end
end
end
|
# encoding: utf-8
class RedactorRailsDocumentUploader < CarrierWave::Uploader::Base
include RedactorRails::Backend::CarrierWave
if Rails.env.test? || Rails.env.development?
storage :file
else
storage :fog
end
def store_dir
"#{Rails.env}/system/redactor_assets/documents/#{model.id}"
end
def extension_white_list
RedactorRails.document_file_types
end
end
|
# Write a method that takes a positive integer as an argument and returns that
# number with its digits reversed.
def reversed_number(num)
new_num = num.to_s.split('')
result = []
loop do
break if new_num.length.zero?
result << new_num.pop
end
p result.join.to_i
end
p reversed_number(12345) == 54321
p reversed_number(12213) == 31221
p reversed_number(456) == 654
p reversed_number(12000) == 21 # No leading zeros in return value!
p reversed_number(12003) == 30021
p reversed_number(1) == 1
|
class RemoveProviderColumnFromPlayers < ActiveRecord::Migration
def change
remove_column :players, :provider
end
end
|
class ChangeCompletedAtTodoItems < ActiveRecord::Migration
def change
#missing the 'l' needed to re migrate
remove_column :todo_items, :competed_at, :datetime
add_column :todo_items, :completed_at, :datetime
end
end
|
class Order
def initialize(config, order_hash)
@order_hash = order_hash
@config = config
end
def address
address_type = @config['twilio_address_type'] || "billing"
@order_hash["#{address_type}_address"]
end
def customer_phone
address['phone']
end
def number
@order_hash['number'] || @order_hash['id']
end
def customer_name
address['firstname']
end
end
|
module Api
module V1
class AuthController < ApplicationController
def create
user = User.find_by( username: user_params[:username] )
if user.blank?
render json: { error: 'Invalid username' }, status: :unauthorized
elsif user.authenticate( user_params[:password] )
access_token = JWT.encode({
id: user.id
}, Rails.application.secrets.secret_key_base)
render json: {
id: user.id,
username: user.username,
nombre_completo: "#{user.nombre} #{user.apellidos}",
access_token: access_token
}
else
render json: { message: "Wrong password!" }, status: :unauthorized
end
end
private
def user_params
params.require(:user).permit(:username, :password)
end
end
end
end
|
require 'spec_helper'
require 'immutable/vector'
describe Immutable::Vector do
let(:v) { V[1, 2, V[3, 4]] }
describe '#dig' do
it 'returns value at the index with one argument' do
expect(v.dig(0)).to eq(1)
end
it 'returns value at index in nested arrays' do
expect(v.dig(2, 0)).to eq(3)
end
# This is different from Hash#dig, but it matches the behavior of Ruby's
# built-in Array#dig (except that Array#dig raises a TypeError)
it 'raises an error when indexing deeper than possible' do
expect { (v.dig(0, 0)) }.to raise_error(NoMethodError)
end
it 'returns nil if you index past the end of an array' do
expect(v.dig(5)).to eq(nil)
end
it "raises an error when indexing with a key vectors don't understand" do
expect { v.dig(:foo) }.to raise_error(ArgumentError)
end
end
end
|
module ApplicationHelper
def isUserAdmin?(group_id)
current_user == Group.find(group_id).admin.user
end
end
|
class CreateParticipants < ActiveRecord::Migration
def change
create_table :participants do |t|
t.string :sex
t.string :fname
t.string :mname
t.string :lname
t.decimal :age
t.string :occupation
t.string :introducer
t.string :guarantor
t.string :address
t.string :tel
t.string :missionary
t.string :remark
t.decimal :donation
t.integer :batch_id
t.integer :blessing_id
t.boolean :is_finalized
t.timestamps
end
end
end
|
module FeatureBox
class Suggestion < ActiveRecord::Base
attr_accessible :title, :description, :status
belongs_to :user, :class_name=>"FeatureBox::User"
belongs_to :category
has_many :votes, :dependent => :destroy
has_many :comments, :dependent => :destroy
validates :title, :presence => true, :length => {
:maximum => Settings.max_suggestion_header_chars
}
validates :description, :presence => true, :length => {
:maximum => Settings.max_suggestion_description_chars
}
validates :user, :presence => true
validates :category, :presence => true
validates_inclusion_of :status, :in => [:default, :in_progress, :complete]
after_save :add_first_vote
def status
read_attribute(:status).to_sym
end
def status= (value)
write_attribute(:status, value.to_s)
end
def user_votes(user)
Vote.where(:suggestion_id=>id,:user_id=>user.id).size()
end
def vote(user)
if user.votes_left > 0 && user.can_vote?(self)
v=Vote.new
v.user=user
v.suggestion=self
v.save
end
end
def self.find_those_with hash
category = hash[:category]
order_type = hash[:order_type]
limit = hash[:limit]
offset = hash[:offset]
category_filter = if category.id then Suggestion.where(:category_id => category.id) else Suggestion end
case order_type
when :most_popular
where_part = "WHERE status <> 'complete' "
if category.id!=nil then
where_part += "AND #{self.table_name}.category_id = #{category.id.to_s}"
end
suggestions = Suggestion.find_by_sql(
"SELECT COUNT(*) AS count_all, #{self.table_name}.*
FROM #{self.table_name}
INNER JOIN #{Vote.table_name}
ON #{Vote.table_name}.suggestion_id = #{self.table_name}.id
#{where_part}
GROUP BY #{self.table_name}.id
ORDER BY count_All DESC
LIMIT #{limit.to_s} OFFSET #{offset.to_s}")
total = category_filter.where("status <> ?", :complete).size
when :in_progress, :complete
suggestions = category_filter.where(:status => order_type).order("created_at DESC").limit(limit).offset(offset)
total = category_filter.where(:status => order_type).size
when :newest
suggestions = category_filter.where("status <> ?", :complete).order("created_at DESC").limit(limit).offset(offset)
total = category_filter.where("status <> ?", :complete).size
else
raise ArgumentError.new("Unknown order_type")
end
return suggestions, total
end
def self.find_my type_of_impact, hash
user = hash[:user]
limit = hash[:limit]
offset = hash[:offset]
case type_of_impact
when :suggestions
suggestions = user.suggestions.order("created_at DESC").limit(limit).offset(offset)
total = user.suggestions.size
when :votes, :comments
impact_table_name = eval("FeatureBox::"+type_of_impact.to_s.capitalize.chomp("s")).table_name
suggestions = Suggestion.joins(type_of_impact).where("#{impact_table_name}.user_id = ?",user.id).order("created_at DESC").uniq.limit(limit).offset(offset)
total = Suggestion.count_by_sql(["SELECT COUNT(DISTINCT #{self.table_name}.id) FROM #{self.table_name} INNER JOIN #{impact_table_name} ON #{impact_table_name}.suggestion_id = #{self.table_name}.id WHERE #{self.table_name}.user_id = ?", user.id])
else
raise ArgumentError.new("Unknown type of impact")
end
return suggestions, total
end
private
def add_first_vote
if(self.votes.size == 0)
v = Vote.new
v.suggestion = self
v.user = self.user
v.save
end
end
end
end
|
class LookingForAJob < ActiveRecord::Migration
def change
create_table :candidates do |t|
t.string :first_name
t.string :last_name
t.string :email
t.text :about_me
t.string :experience_level
t.string :github_name
t.string :twitter_name
t.text :looking_for
t.boolean :receive_updates, default: true
end
add_index :candidates, :receive_updates
end
end
|
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
record.errors[attribute] << (options[:message] || "is not an email")
end
end
end
class Member < ActiveRecord::Base
validates :prename, presence: true, length: {in: 2..100}
validates :name, presence: true, length: {in: 2..100}
validates :email, presence: true, email: true
validates :street, presence: true, length: {in: 5..100}
validates :nr, presence: true, format: /\d{1,3}\w?/
validates :plz, presence: true, numericality: true, length: {in: 4..6}
validates :city, presence: true, length: {in: 4..50}
validates :birthdate, presence: true, format: /\d{4}-\d{1,2}-\d{1,2}/
validates :country, presence: true
validates :phone, presence: false, numericality: true
end |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Factor.create([{ name: 'Mision proyecto institucional' },
{ name: 'Estudiantes' },
{ name: 'Profesores' },
{ name: 'Procesos académicos' },
{ name: 'Visibilidad nacional e internacional' },
{ name: 'Espacion de investigación, innovación, y creación artística y cultural' },
{ name: 'Pertinecia e impacto social' },
{ name: 'Autoevaluación y Autorregulacón' },
{ name: 'Bienestar institucional' },
{ name: 'Organización, Gestión y administración' },
{ name: 'Recursos de apoyo académico e infraestructura física' },
{ name: 'Recursos financieros' }])
Indicator.create([{ description: 'Barreras para el aprendizaje y la participación', factor_id: 1 },
{ description: 'Identificación y caracterización de estudiantes desde la educación inclusiva', factor_id: 1 },
{ description: 'Participación de estudiantes', factor_id: 2 },
{ description: 'Admisión, permanencia y sistemas de estímulos y créditos para estudiantes', factor_id: 2 },
{ description: 'Participación de docentes', factor_id: 3 },
{ description: 'Docentes inclusivos', factor_id: 3 },
{ description: 'Interdisciplinariedad y flexibilidad curricular', factor_id: 4 },
{ description: 'Evaluación flexible', factor_id: 4 },
{ description: 'Inserción de la institución en contextos académicos nacionales e internacionales', factor_id: 5 },
{ description: 'Relaciones externas de profesores y estudiantes', factor_id: 5 },
{ description: 'Investigación, innovación y creación artística y cultural en educación inclusiva', factor_id: 6 },
{ description: 'Articulación de la educación inclusiva con los procesos de investigación, innovación y creación artística y cultural', factor_id: 6 },
{ description: 'Extensión, proyección social y contexto regional', factor_id: 7 },
{ description: 'Seguimiento y apoyo a vinculación laboral', factor_id: 7 },
{ description: 'Procesos de autoevaluación y autorregulación con enfoque de educación inclusiva', factor_id: 8 },
{ description: 'Estrategias de mejoramiento', factor_id: 8 },
{ description: 'Sistema de información inclusivo', factor_id: 8 },
{ description: 'Procesos administrativos y de gestión flexibles', factor_id: 9 },
{ description: 'Estructura organizacional', factor_id: 9 },
{ description: ' Recursos, equipos y espacios de práctica', factor_id: 10 },
{ description: ' Instalaciones e infraestructura', factor_id: 10 },
{ description: ' Programas de bienestar universitario', factor_id: 11 },
{ description: ' Permanencia estudiantil', factor_id: 11 },
{ description: ' Programas de educación inclusiva sostenibles', factor_id: 12 },
{ description: ' Apoyo financiero a estudiantes', factor_id: 12 }])
Replay.create([{ description: 'Existe Y Se Implementa' },
{ description: 'Existe Y No Se Implementa' },
{ description: 'No Existe' },
{ description: 'No Sabe' },
{ description: 'Siempre' },
{ description: 'Algunas Veces' },
{ description: 'Nunca' },
{ description: 'Si' },
{ description: 'No' }])
Category.create([{ name: 'Exsistencia' },
{ name: 'Frecuencia' },
{ name: 'Reconocimiento' }])
Gender.create([{ name: 'Masculino' },
{ name: 'Femenino' },
{ name: 'Otro' } ])
Institution.create([{ name: 'Sena', totalPopulation: 3000, sample: 600 },
{ name: 'Universidad autonoma del caribe', totalPopulation: 5000, sample: 500 },
{ name: 'Universidad del atlantico', totalPopulation: 8000, sample: 800 },
{ name: 'Universidad del norte', totalPopulation: 4500, sample: 800 },
{ name: 'Universidad Simon Bolivar', totalPopulation: 1500, sample: 500 }])
Group.create([{ name: 'Administrativo' },
{ name: 'Docente' },
{ name: 'Estudiante' }])
Field.create([{ name: 'Facultad' },
{ name: 'Departamento' },
{ name: 'Cargo' },
{ name: 'Dependencia' },
{ name: 'Antigüedad en el cargo(años)' },
{ name: 'Antigüedad en el cargo(meses)' },
{ name: 'Antigüedad en la institución(años)' },
{ name: 'Antigüedad en la institución(meses)' },
{ name: 'Carrera' },
{ name: 'Semestres' },
{ name: 'Año de ingreso' },
{ name: 'Semestre de ingreso' },
{ name: 'Tipo de vinculación' },
{ name: 'Horas a la semana' }])
Question.create([{ detail: 'La institución de educación superior cuenta con una política de educación inclusiva que permite reconocer y minimizar las barreras para el aprendizaje y la Participación.', category_id: 1, indicator_id: 1},
{ detail: 'La institución identifica la diversidad estudiantil caracterizando sus particularidades (sociales, económicas, políticas, culturales, lingüísticas, sexuales, físicas, geográficas y relacionadas con el conflicto armado) y pone énfasis en aquellos que son más proclives a ser excluidos del sistema.', category_id: 2 , indicator_id: 2 },
{ detail: 'La institución cuenta con estrategias y procesos que permiten y facilitan el acceso y la permanencia de los estudiantes, y adicionalmente cuenta con sistemas de becas, préstamos y estímulos que propician el ingreso y la permanencia de estudiantes académicamente valiosos y en condición de vulnerabilidad, para garantizar graduación con calidad.', category_id: 1, indicator_id: 4 },
{ detail: 'La institución cuenta con una política que facilita la participación de todos los estudiantes en los procesos académicos y Administrativos.', category_id: 1, indicator_id: 3 },
{ detail: 'La institución cuenta con una política que facilita la participación de todos los docentes en los procesos académicos y administrativos.', category_id: 1, indicator_id: 5 },
{ detail: 'La institución genera los mecanismos para que los docentes participen en los procesos de docencia, investigación y extensión, transformen las prácticas pedagógicas y valoren la diversidad de sus estudiantes como parte del proceso educativo.', category_id: 2, indicator_id: 6 },
{ detail: 'Los currículos de la institución son flexibles e interdisciplinarios y contienen elementos que facilitan el aprendizaje y el desarrollo de capacidades, potencialidades y/o competencias de la diversidad estudiantil.', category_id: 2, indicator_id: 7 },
{ detail: 'Los procesos académicos de la institución cuentan con herramientas de evaluación flexible que reconocen las particularidades, las capacidades y las potencialidades de cada estudiante.', category_id: 1, indicator_id: 8 },
{ detail: 'En sus procesos académicos, la institución toma como referencia las tendencias, el estado del arte de las disciplinas o profesiones y los criterios de calidad aceptados por las comunidades académicas nacionales e internacionales, estimula el contacto con miembros reconocidos de esas comunidades y promueve la cooperación con instituciones y programas en el país y en el exterior.', category_id: 3, indicator_id: 9 },
{ detail: 'La institución promueve la interacción con otras instituciones de los ámbitos nacional e internacional, y coordina la movilidad de profesores y estudiantes, entendida esta como el desplazamiento temporal, en doble vía, con enfoque inclusivo y propósitos académicos.', category_id: 3, indicator_id: 10 },
{ detail: 'La institución cuenta con centros, grupos y/o programas de investigación en temas relacionados con educación inclusiva.', category_id: 3, indicator_id: 11 },
{ detail: 'La institución desarrolla, en los procesos de investigación, temáticas relacionadas con la educación inclusiva, y promueve estrategias enmarcadas en sus principios.', category_id: 2, indicator_id: 12 },
{ detail: 'La institución desarrolla programas y actividades de extensión o proyección social que responden a necesidades regionales y poblacionales determinadas, teniendo en cuenta el enfoque de educación inclusiva en el contexto colombiano.', category_id: 3, indicator_id: 13 },
{ detail: 'La IES desarrolla estrategias e implementa mecanismos de acompañamiento a sus egresados, como parte de una política de seguimiento y apoyo a la vinculación laboral.', category_id: 1, indicator_id: 14 },
{ detail: 'La institución implementa procesos de autoevaluación y autorregulación que permiten identificar el cumplimiento institucional frente al enfoque de la educación inclusiva y sus características.', category_id: 2, indicator_id: 15 },
{ detail: 'La institución implementa estrategias de mejoramiento continuo a partir de los resultados de las autoevaluaciones y las evaluaciones de la comunidad académica.', category_id: 2, indicator_id: 16 },
{ detail: 'La institución cuenta con un sistema de información disponible, confiable y accesible, que orienta la formulación de políticas institucionales que fomentan la educación inclusiva en educación superior.', category_id: 1, indicator_id: 17 },
{ detail: 'Los programas de bienestar universitario promueven, por medio de acciones concretas, la participación de los estudiantes y su adaptación a la vida universitaria, teniendo en cuenta sus particularidades y potencialidades.', category_id: 2, indicator_id: 18 },
{ detail: 'La IES identifica, como parte del bienestar universitario, los factores asociados a la deserción de sus estudiantes, y diseña programas que favorecen la permanencia, de acuerdo con sus particularidades y necesidades diferenciales.', category_id: 2, indicator_id: 19 },
{ detail: 'Los procesos administrativos están soportados en el enfoque de educación inclusiva y permiten identificar con claridad sus características.', category_id: 2, indicator_id: 20 },
{ detail: 'La estructura organizacional de la institución permite desarrollar acciones específicas de educación inclusiva.', category_id: 2, indicator_id: 21 },
{ detail: 'Los recursos, equipos y espacios de práctica son accesibles y pertinentes para corresponder a las características del enfoque de educación inclusiva.', category_id: 2, indicator_id: 22 },
{ detail: 'Las instalaciones y la infraestructura de la institución responden a las exigencias de la normatividad vigente. En particular las NTC.', category_id: 3, indicator_id: 23 },
{ detail: 'La institución destina recursos y garantiza la sostenibilidad de las estrategias de educación inclusiva.', category_id: 2, indicator_id: 24 },
{ detail: 'La institución cuenta con programas especiales o establece convenios de cooperación con entidades que financian el acceso y la permanencia de los estudiantes más proclives a ser excluidos del sistema (en relación con los grupos priorizados en los lineamientos de política de educación inclusiva del Ministerio de Educación Nacional).', category_id: 2, indicator_id: 25 }])
CategoryReplay.create([{replay_id: 1, category_id: 1 },
{replay_id: 2, category_id: 1 },
{replay_id: 3, category_id: 1 },
{replay_id: 4, category_id: 1 },
{replay_id: 5, category_id: 2 },
{replay_id: 6, category_id: 2 },
{replay_id: 7, category_id: 2 },
{replay_id: 8, category_id: 3 },
{replay_id: 4, category_id: 2 },
{replay_id: 4, category_id: 3 },
{replay_id: 9, category_id: 3 }])
|
class Currency_Converter
def initialize(conversion_rate = 1.0, country_code = :USD)
@conversion_rate = conversion_rate
@country_code = country_code
end
def conversion_rate
@conversion_rate = conversion_rate
end
def country_code
@country_code = country_code
end
def to_s
"#{@country_code}, #{@conversion_number}"
end
def hash_of_code_values
# puts "Do you have conversion rates and country codes?
# Or do you want to use the defaults?"
# hash_decision = gets.chomp
# if hash_decision = "yes"
# #have user enter their own hash
# gets.cho
# else
hash_of_code_values = {USD: 1.0, EUR: 0.74}
# end
end
def convert(desired_currency_amount, desired_currency_code, total_amount)
# convert (1, :USD) to (.74, :USD)
if hash_of_code_values.include?(desired_currency_code)
desired_currency_code = hash_of_code_values[desired_currency_code]
else
raise UnknownCurrencyCodeError
end
Currency.new(desired_currency_amount * total_amount, desired_currency_code)
end
end
|
class Api::V1::Transactions::InvoiceController < ApplicationController
def index
transaction = Transaction.find_by(id: params[:transaction_id])
invoice = Invoice.find_by(id: transaction.invoice_id)
render json: InvoiceSerializer.new(invoice)
end
end
|
require 'rails_helper'
RSpec.describe "phrases/show", type: :view do
before(:each) do
@phrase = assign(:phrase, Phrase.create!(
:english_text => "English Text",
:audio => "",
:image => ""
))
end
it "renders attributes in <p>" do
render
expect(rendered).to match(/English Text/)
expect(rendered).to match(//)
expect(rendered).to match(//)
end
end
|
class Event < ActiveRecord::Base
acts_as_commentable
has_many :occurrences
belongs_to :sponsor
has_many :performances
belongs_to :category, :class_name => 'Attribute'
has_many :places , :through => :occurrences
has_many :campaigns, :through => :promotions
has_many :performers , :through => :performances
has_and_belongs_to_many :labels, :class_name => "Attribute" , :join_table=> "events_attributes"
validates_presence_of :title, :description, :category_id
def to_param
"#{id}-#{title.to_url}"
end
def rate(rating)
if rating >= 1 and rating <= 5
self.rating = ((((self.rating || 0) * self.rated_count + rating).to_f / (self.rated_count + 1)) * 10).round.to_f / 10
self.rated_count += 1
end
self.rating
end
def rating_int
rating.round
end
def self.correct_images
# Check thrumbnails for empty images and remove them
Dir.glob('public/thumbnails/*.jpg').each do |filename|
unless File.size?(filename)
event = Event.find_by_image_url filename[7..-1]
if event
event.image_url = nil
event.save
end
File.delete filename
end
end
end
end
class Performance < ActiveRecord::Base
belongs_to :event
belongs_to :performer
end
# == Schema Info
# Schema version: 20110328181217
#
# Table name: events
#
# id :integer(4) not null, primary key
# title :string(128) not null
# description :text not null, default("")
# text :text(2147483647
# thumbnail :string(200)
# created_at :datetime not null
# updated_at :datetime not null
# sponsor_id :integer(4)
# price :float
# image_url :string(200)
# web :string(200)
# duration :integer(4)
# category_id :integer(4)
# rating :float not null, default(0.0)
# rated_count :integer(4) not null, default(0) |
class Printer
# вывод версии игры
def version(version)
puts version
puts
end
# Вывод приветствия
def welcome(name)
puts "#{name},"
puts "Ответьте, пожалуйста, честно на 16 " \
"вопросов, чтобы узнать насколько вы общительный человек."
puts
end
# вывод последовательно всех вопросов (используется в методе start_test класса Test)
def question(question, i)
i += 1
puts "#{i}. #{question}"
end
# вывод вариантов ответа (используется в методе start_test класса Test)
def variants
puts "а) да;"
puts "б) нет;"
puts "в) иногда."
end
# вывод конечного результата
def result(count, results)
puts "Ваши результат:"
puts "Вы набрали #{count} балла(ов)"
puts
# тут выцепляются нужные фрагменты текста для каждого результата
result = case count
when 30..32 then results[/30\.\.32.*?\n\n/m].gsub(/^\d.*\d\n/, "")
when 25..29 then results[/25\.\.29.*?\n\n/m].gsub(/^\d.*\d\n/, "")
when 19..24 then results[/19\.\.24.*?\n\n/m].gsub(/^\d.*\d\n/, "")
when 14..18 then results[/14\.\.18.*?\n\n/m].gsub(/^\d.*\d\n/, "")
when 9..13 then results[/9\.\.13.*?\n\n/m].gsub(/^\d.*\d\n/, "")
when 4..8 then results[/4\.\.8.*?\n\n/m].gsub(/^\d.*\d\n/, "")
when 0..3 then results[/\n0\.\.3.*/m].gsub(/^\d.*\d\n/, "")
end
puts result
end
end
|
# frozen_string_literal: true
class CancelUnpaidReservationWorker
include Sidekiq::Worker
def perform
Reservation.where(status: 'pending')
.where('screening_time < ?', Time.current + 30.minutes)
.joins(:screening)
.update_all(status: 'cancelled')
ReservationMailer.cancel_reservation(User.find(id: reservation.user_id).email, reservation).deliver_now
end
end
|
if defined?(ChefSpec)
def create_consul_template(message)
ChefSpec::Matchers::ResourceMatcher.new(:consul_template, :create, resource_name)
end
def remove_consul_template(message)
ChefSpec::Matchers::ResourceMatcher.new(:consul_template, :create, resource_name)
end
def create_consul_template_config(message)
ChefSpec::Matchers::ResourceMatcher.new(:consul_template_config, :create, resource_name)
end
def remove_consul_template_config(message)
ChefSpec::Matchers::ResourceMatcher.new(:consul_template_config, :create, resource_name)
end
def create_consul_template_installation(message)
ChefSpec::Matchers::ResourceMatcher.new(:consul_template_installation, :create, resource_name)
end
def remove_consul_template_installation(message)
ChefSpec::Matchers::ResourceMatcher.new(:consul_template_installation, :create, resource_name)
end
def enable_consul_template_service(message)
ChefSpec::Matchers::ResourceMatcher.new(:consul_template_service, :create, resource_name)
end
def disable_consul_template_service(message)
ChefSpec::Matchers::ResourceMatcher.new(:consul_template_service, :create, resource_name)
end
end
|
class Account < ActiveRecord::Base
validates :emailId , presence: true , length: {minimum: 5 ,maximum:100}
validates :userName , presence:true , length: {minimum: 3, maximum:15}
validates :password , presence:true , length: {minimum:6 , maximum: 20}
end
|
namespace :parse do
desc "Parsing of events based on Berlin events"
task :other_event_creator => :environment do
# Scraper for Categories Film, Theater and Concert
available_categories = {movie: "film", theater: "theaterperformance", concert: "konzert"}
available_categories.each do |cat|
3.times do |d|
@event = Nokogiri::HTML(open("https://www.museumsportal-berlin.de/de/veranstaltungen/?selected_date=2017-12-#{d + 1}&category=#{cat[1]}"))
@date = Date.parse("Dec #{d + 1} 2017")
p "Category: #{cat[0].capitalize} --> Date: #{@date}"
# Venue Creator
20.times do |i|
# checks if the accessed container is empty
if @event.xpath("//*[@id='container']/div/div[#{i}]/a/h3").empty?
else
# creates url of event outside of index page
@event_url = "https://www.museumsportal-berlin.de/#{@event.xpath("//*[@id='container']/div/div[#{i}]/a").attr('href').text.strip}"
# creates Nokogiri variable with Event-URL
@event_url_nokogiri = Nokogiri::HTML(open("#{@event_url}"))
#checks if venue already exists and skips if yes
if Venue.find_by_name(@event_url_nokogiri.xpath("//*[@id='collapse-location']/div/p/b/a").text)
else
r = Venue.create!(
name: @venue_name = @event_url_nokogiri.xpath("//*[@id='collapse-location']/div/p/b/a").text,
city: "Berlin",
address: @event_url_nokogiri.xpath("//*[@id='wdgt_to']").text.split.join(" "),
# description = opening hours
description: @event_url_nokogiri.xpath("//*[@id='collapse-opening-times']/div/div[1]").text.split.join(" "),
# phone: ,
# email: ,
# user_id: host1.id,
# remote_photo_url: ,
)
p "> Venue: #{@venue_name}"
end
end
end
#byebug
# Event Creator
20.times do |i|
# puts "this is event #{i}"
# checks if the accessed container is empty
if @event.xpath("//*[@id='container']/div/div[#{i}]/a/h3").empty?
# p "empty"
else
# p "not empty"
# creates url of event outside of index page
@event_url = "https://www.museumsportal-berlin.de/#{@event.xpath("//*[@id='container']/div/div[#{i}]/a").attr('href').text.strip}"
# creates Nokogiri variable with Event-URL
@event_url_nokogiri = Nokogiri::HTML(open("#{@event_url}"))
# stores price and picture of Event from Event-URL
@event_price = @event_url_nokogiri.xpath("//*[@id='collapse-prices']/div/dl[1]/dd").empty? ? "Free Admission" : @event_url_nokogiri.xpath("//*[@id='collapse-prices']/div/dl[1]/dd").text.strip
@picture_url = @event_url_nokogiri.xpath("//*[@id='cover_img']/a[1]/img").empty? ? "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/No_image_available.svg/200px-No_image_available.svg.png" : "https://www.museumsportal-berlin.de/#{@event_url_nokogiri.xpath("//*[@id='cover_img']/a[1]/img").attr("data-original").value}"
# p @event_price
@venue_name = @event_url_nokogiri.xpath("//*[@id='collapse-location']/div/p/b/a").text
r = Event.create!(
name: @event.xpath("//*[@id='container']/div/div[#{i}]/a/h3").text.strip,
description: "#{@event_url_nokogiri.xpath("//*[@id='exhibition']/div/div/div[1]/article/div[5]/p[1]").text.strip} #{@event_url_nokogiri.xpath("//*[@id='exhibition']/div/div/div[1]/article/div[4]/p[1]").text.strip} #{@event_url_nokogiri.xpath("//*[@id='exhibition']/div/div/div[1]/article/div[3]/p[1]").text.strip}",
category: cat[0],
tags: ["Dramatic", "Romantic", "Modern", "Funny"].sample,
date: @date,
price: @event_price,
mood: ["Dramatic", "Romantic", "Glamorous", "Wild", "Nerdy"].sample,
venue_id: Venue.find_by_name(@venue_name).id,
city: 'Berlin',
remote_photo_url: @picture_url,
)
p "> Event: #{@event.xpath("//*[@id='container']/div/div[#{i}]/a/h3").text.strip}"
end
end
end
end
end
end
|
FactoryBot.define do
factory :patient_phone_number do
id { SecureRandom.uuid }
number { Faker::PhoneNumber.phone_number }
phone_type { "mobile" }
active { [true, false].sample }
device_created_at { Time.current }
device_updated_at { Time.current }
dnd_status { true }
patient
end
end
def build_patient_phone_number_payload(phone_number = FactoryBot.build(:patient_phone_number))
Api::V3::PatientPhoneNumberTransformer.to_response(phone_number)
end
|
class MicropostsController < ApplicationController
before_action :signed_in_user
def create
@micropost = curent_user.microposts.build(micropost_params)
if @micropost.save
flash[:succes] = "Micropost created!"
redirect_to root_path
else
render 'static_pages/home'
end
end
def destroy
end
private
def micropost_params
params.require(:micropost).permit(:contet)
end
end |
# frozen_string_literal: true
# == Schema Information
#
# Table name: room_users
#
# id :integer not null, primary key
# user_id :integer not null
# room_id :integer not null
# last_read_message_id :integer
# unread_message_count :integer default(0)
# created_at :datetime not null
# updated_at :datetime not null
#
FactoryGirl.define do
factory :room_user do
end
end
|
class HumanFactor < ActiveHash::Base
self.data = [
{ id: 1, name: '--' },
{ id: 2, name: '気分(高揚/沈潜)' },
{ id: 3, name: '欲得/(経済的/地位)' },
{ id: 4, name: '自失(無判断/未知遭遇)' },
{ id: 5, name: '思い入れが逆に働いた(生きがい/使命感)' },
{ id: 6, name: '横着(手抜き/責任転嫁)' },
{ id: 7, name: 'プライド(体裁/ええ格好)' },
{ id: 8, name: '惰性(性癖/習慣/行き掛かり/思い込み)' },
{ id: 9, name: '決まり違反(無知/無視/手抜き)' },
{ id: 10, name: '考え不足(浅慮/無思慮)' },
{ id: 11, name: 'うっかり(誤判断/忘却/看過)' },
{ id: 12, name: 'その他' }
]
end
|
#
# Cookbook Name:: gpg
# Recipe:: default
#
require 'etc'
chef_gem 'gpgme'
require 'gpgme'
package "gnupg" do
action :nothing
end.run_action(:upgrade)
directory gpg_home do
owner node['gpg']['user']
action :nothing
end.run_action(:create)
search(node[:gpg][:keys_data_bag]) do |key|
ruby_block "Import and trust GPG key #{key['id']}" do
block do
# Import the key
gpg_import = Mixlib::ShellOut.new("gpg --homedir #{Shellwords.escape(gpg_home)} --import", :input => key['public_key'])
gpg_import.run_command
gpg_import.error!
# Mark as ultimately trusted
gpg_trust = Mixlib::ShellOut.new("gpg --homedir #{Shellwords.escape(gpg_home)} --import-ownertrust", :input => "#{key['fingerprint']}:6:\n")
gpg_trust.run_command
gpg_trust.error!
end
end
end
|
class Award < ApplicationRecord
belongs_to :rifa_id
belongs_to :ticket_drawn
end
|
namespace :lock do
desc 'check lock'
task :check do
on roles(:db) do
if test("[ -f #{lock_path} ]")
require 'time'
lock_mtime = Time.parse capture("stat --format '%z' #{lock_path}")
time_now = Time.parse capture('date')
time_diff = Time.at(time_now - lock_mtime).utc.strftime('%H:%M:%S')
deploy_user = capture("cat #{lock_path}").strip
raise StandardError.new <<~MSG
\n\n\e[31mDeployment is already in progress
Started #{time_diff} ago by #{deploy_user}
Run 'cap <stage> lock:release' if previous deploy was terminated\e[0m\n
MSG
end
end
end
desc 'create lock'
task :create do
on roles(:db) do
deploy_user = `git config user.name`.strip
execute "echo '#{deploy_user}' > #{lock_path}"
end
end
desc 'release lock'
task :release do
on roles(:db) do
execute "rm #{lock_path}"
end
end
def lock_path
"#{shared_path}/cap.lock"
end
end
before 'deploy:starting', 'lock:check'
after 'lock:check', 'lock:create'
after 'deploy:finished', 'lock:release'
|
class Smartphone
#属性の定義
#インスタンス変数を読み書きするためのアクセサメソッド
attr_accessor :manufacture, :color, :storage
#initializeメソッド…インスタンスが生成される時に自動的に呼び出されるメソッド
# 必ず実行したい処理(初期化など)を、メソッドを呼び出すことなく実行できる
def initialize(manufacture,color,storage)
# インスタンス生成時に与えられた値(属性の内容)をインスタンス変数に保存
@manufacture = manufacture
@color = color
@storage = storage
end
# 操作(メソッド)の定義
def tel(name)
puts "#{name}に電話をかける"
end
def email(name)
puts "#{name}にメールを送る"
end
def picture
puts "写真を撮る"
end
end
# 上記のクラス(設計図)を元にインスタンス(実物)を生成する
smaho_1 = Smartphone.new("Apple","black",128)
smaho_2 = Smartphone.new("Google","whire",64)
# スマホ1の属性
puts "スマホ1"
puts smaho_1.manufacture
puts smaho_1.color
puts smaho_1.storage
# スマホ2の属性
puts "スマホ2"
puts smaho_2.manufacture
puts smaho_2.color
puts smaho_2.storage
# クラスで定義した操作をする
puts "操作"
smaho_1.tel("母")
smaho_1.email("父") |
class CreateSubscriptions < ActiveRecord::Migration
def change
create_table :subscriptions do |t|
t.references :partner, null: false
t.references :noun, polymorphic: true, null: false
t.timestamps
end
add_index :subscriptions, :partner_id
add_index :subscriptions, [:noun_id, :noun_type]
end
end
|
class UserMethod < ApplicationRecord
validates :user_level, :controller_method_id, presence: true
belongs_to :controller_method
end
|
# == Schema Information
#
# Table name: user_submission_votes
#
# id :integer not null, primary key
# user_id :integer
# scholarship_submission_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class UserSubmissionVote < ActiveRecord::Base
# Relations
belongs_to :scholarship_submission, counter_cache: true
belongs_to :user
# Attribute availability
attr_accessible :scholarship_submission, :user
class << self
def already_voted?(user_id, submission_id)
UserSubmissionVote.where(
user_id: user_id,
scholarship_submission_id: submission_id
).exists?
end
def find_by_user_and_submission(user_id, submission_id)
UserSubmissionVote.where(
user_id: user_id,
scholarship_submission_id: submission_id
).first
end
end
end
|
require './app/doubles/calculator_display'
require 'test/unit'
require 'test/unit/notify'
require 'mocha/test_unit'
class CalculatorDisplaySpyTest < Test::Unit::TestCase
def test_shows_default_separator()
# Arrange
resultToInject = 100
expectedOutput = "100.00"
mockedCalculator = mock()
mockedCalculator.expects(:result).returns(resultToInject)
display = CalculatorDisplay.new(mockedCalculator)
# Act
actualOutput = display.show()
# Assert
assert_equal(expectedOutput, actualOutput,
"standard decimal separator")
end
def test_showsAlternateSeparators()
# How to write a test when we still don't
# know the underlying technology enough?
# spike! (i.e. using a separate folder or
# using a new branch)
# Arrange
resultToInject = 100.0;
expectedOutput = "100,00"
mockedCalculator = mock()
mockedCalculator.expects(:result).returns(resultToInject)
display = CalculatorDisplay.new(mockedCalculator)
display.thousandSeparator= "."
display.decimalSeparator= ","
# Act
actualOutput = display.show()
# Assert
assert_equal(expectedOutput, actualOutput,
"decimal separator change")
# Code above was extracted to a single method
assert_alternate_separator_behaviour(
"single thousand separator", 1000,
".", ",", "1.000,00")
assert_alternate_separator_behaviour(
"multiple thousand separators",
1000000000, ".", ",",
"1.000.000.000,00");
assert_alternate_separator_behaviour(
"thousand separator on negative numbers",
-45000, ".", ",", "-45.000,00");
end
def show_specific_numer_of_decimals()
end
def show_hexadecimal_representation()
end
def show_binary_representation()
end
private
def assert_alternate_separator_behaviour(msg,
resultToInject, thousandSeparator, decimalSeparator,
expectedOutput)
# Arrange
mockedCalculator = mock()
mockedCalculator.expects(:result).returns(resultToInject)
display = CalculatorDisplay.new(mockedCalculator)
display.thousandSeparator= "."
display.decimalSeparator= ","
# Act
actualOutput = display.show()
# Assert
assert_equal(expectedOutput, actualOutput, msg)
end
end
|
class Role < ActiveRecord::Base
attr_accessible :name
has_many :user_roles
has_many :users, :through => :user_roles
validates :name, :presence => true,
:length => {:minimum => 5}
end
|
class User < ApplicationRecord
# devise :database_authenticatable, :registerable,
# :recoverable, :rememberable, :validatable
# Make omniauthable
devise :omniauthable, :omniauth_providers => [:google_oauth2]
def self.from_omniauth(auth)
# Either create a User record or update it based on the provider (Google) and the UID
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.token = auth.credentials.token
user.expires = auth.credentials.expires
user.expires_at = auth.credentials.expires_at
user.refresh_token = auth.credentials.refresh_token
# Also save email and image
user.email = auth.info.email
user.name = auth.info.name
user.image = auth.info.image
end
end
end |
class CreateRequisitions < ActiveRecord::Migration
def self.up
create_table :requisitions do |t|
t.string :req_no
t.text :description
t.integer :priority_id # req_priority fixed -> Operation, Emergency, Safety, Other
t.integer :status_id # req_status fixed -> New, Open, Pre-Approved, Approved, Voided
t.integer :req_on_po_id # req_on_po
t.integer :source_id # req_source fixed -> Other, Auto-Reorder, Workorder
t.integer :state_id # req_state -> Open, Reopen, Closed
t.date :due_date
t.integer :shipping_type_id # shipping_type fixed -> Ground, Express
t.integer :wo_id # workorder
t.integer :request_user_id # users
t.datetime :request_at
t.decimal :req_total
t.integer :costcode_id # costcode # TODO
t.integer :dept_id # dept
t.integer :next_user_id # users
t.string :next_note
t.integer :updated_id # users
t.integer :created_id # users
t.timestamps
end
end
def self.down
drop_table :requisitions
end
end
|
require 'rspec'
require './enumerables'
describe Enumerable do
let(:ary) { %w[a b c] }
let(:rng) { (1..5) }
let(:block) { |item| print item, '--' }
let(:sym_ary) { %i[foo bar sym] }
let(:words) { %w[ant bear cat] }
let(:numbers) { [1, 3.14, 42] }
describe '#my_each' do
let(:block) { proc { |item| print item, '--' } }
it 'Return an enumerator if no block is given' do
expect(ary.my_each).to be_an(Enumerator)
end
context 'when a block is given' do
it 'Applies the block to every element of the array' do
expect(ary.my_each(&block)).to be(ary.each(&block))
end
it 'Applies the block to every element of the range' do
expect(rng.my_each(&block)).to be(rng.each(&block))
end
end
end
describe '#my_each_with_index' do
let(:block) { |item, index| print "Item: #{item}, Index: #{index}" }
it 'calls block with two arguments, the item and its index, for each item in enum' do
expect(ary.my_each_with_index).to be_an(Enumerator)
end
context 'when a block is given' do
it 'returns the array after calling the given block once for each slement in self' do
expect(ary.my_each_with_index { :block }).to be(ary.each_with_index { :block })
end
it 'returns the array after calling the given block once for each slement in self::range' do
expect(rng.my_each_with_index { :block }).to be(rng.each_with_index { :block })
end
end
end
describe '#my_select' do
let(:block) { |item| item > 3 }
let(:sym_block) { |item| item == :foo }
it 'returns an Enumerator if no block is given' do
expect(rng.my_select).to be_an(Enumerator)
end
context 'when a block is given' do
it 'returns an array with all elements for which the given block returns a true value.' do
expect(rng.my_select { :block }).to eq(rng.select { :block })
end
it 'returns an array with all elements for which the given block returns a true value.' do
expect(sym_ary.my_select { :sym_block }).to eq(sym_ary.select { :sym_block })
end
end
end
describe '#my_all?' do
let(:block) { |item| item > 3 }
let(:block_is_numeric) { |item| item > 0 }
context 'when a block is given' do
it 'The method returns true if the block never returns false or nil after applying the block to every item' do
expect(rng.my_all? { :block }).to eq(rng.all? { :block })
end
it 'The method returns true if the block never returns false or nil after applying the block to every item' do
expect(rng.my_all? { :block_is_numeric }).to eq(rng.all? { :block_is_numeric })
end
it 'The method returns true if the block never returns false or nil after applying the block to every item' do
expect(rng.my_all?(Numeric)).to eq(rng.all?(Numeric))
end
end
end
describe '#my_any?' do
let(:block) { proc { |word| word.length >= 3 } }
let(:false_collection) { [] }
let(:true_collection) { [nil, true, 99] }
context 'when no argument or block is given' do
it 'returns true if the block ever returns a value other than false or nil' do
expect(true_collection.my_any?).to be true_collection.any?
end
it 'doesn´t return true when one of the collection members are false or nil' do
expect(false_collection.my_any?).not_to be true
end
it 'returns false when one of the collection members are false or nil' do
expect(false_collection.my_any?).to be false_collection.any?
end
end
context 'when a class is passed as an argument' do
it 'returns true if at least one of the collection members is a member of such class' do
ary << 2
expect(ary.my_any?(Numeric)).to be ary.any?(Numeric)
end
end
context 'when a pattern is passed as an argument' do
it 'returns true if at least one of the collection members matches the regex' do
expect(ary.my_any?(/b/)).to be ary.any?(/b/)
end
it 'returns false if none of the collection members matches the regex' do
expect(ary.my_any?('d')).to be ary.any?('d')
end
end
context 'when a block is given' do
it 'returns true if the block ever returns a value other than false or nil' do
expect(words.my_any?(&block)).to be words.any?(&block)
end
end
end
describe '#my_none' do
let(:true_collection) { [nil, false] }
let(:false_collection) { [nil, false, true] }
let(:true_block) { proc { |word| word.length == 5 } }
let(:false_block) { proc { |word| word.length == 5 } }
context 'when no argument or block is given' do
it 'return true only if none of the collection members is true' do
expect(true_collection.my_none?).to be true_collection.none?
end
it 'returns false if any of the collection members are truthy' do
expect(false_collection.my_none?).to be false_collection.none?
end
end
context 'when a class is passed as an argument' do
it 'returns true only if none of the collection members is a member of such class' do
expect(words.my_none?(Integer)).to be words.none?(Integer)
end
it 'doesn´t return true if any of the element in the collection is not a member of the class' do
expect(words.my_none?(Integer)).not_to be words.any?(Integer)
end
it 'returns false if any of the collection members are truthy' do
expect(numbers.my_none?(Float)).to be numbers.none?(Float)
end
end
context 'when a pattern is passed as an argument' do
it 'returns whether pattern === element for none of the collection members' do
expect(words.my_none?(/d/)).to be words.none?(/d/)
end
end
context 'when a block is given' do
it 'returns true if the block never returns true for all elements' do
expect(words.my_none?(&true_block)).to be words.none?(&true_block)
end
it 'returns false if the block returns true for any collection members' do
expect(words.my_none?(&false_block)).to be words.none?(&false_block)
end
end
end
describe '#my_count' do
let(:block) { |item| item > 3 }
it 'It returns the number of items in the object if no param or block is given' do
expect(rng.my_count).to eq(rng.count)
end
context 'when an argument is given' do
it 'The method returns the count that argument appears in object' do
expect(rng.my_count(2)).to eq(rng.count(2))
end
end
context 'when a block is given' do
it 'The method returns the times the block yields true' do
expect(rng.my_count { :block }).to eq(rng.count { :block })
end
end
end
describe '#my_map' do
let(:block) { |i| i * i }
let(:block2) { 'cat' }
context 'When no block is given' do
it 'returns an Enumerator if no block is given' do
expect(rng.my_map).to be_an(Enumerator)
end
end
context 'when a block is given' do
it 'It returns a new array with the results of running block once for every element' do
expect(rng.my_map { :block }).to eq(rng.map { :block })
end
it 'It returns a new array with the results of running block once for every element' do
expect(rng.my_map { :block2 }).to eq(rng.map { :block2 })
end
end
end
describe '#my_inject' do
let(:ary_case1) { [1, :*] }
arg_case2 = :*
initial_value = 1
let(:block_case3) { |product, n| product * n }
let(:block_case4) { proc { |memo, word| memo.length > word.length ? memo : word } }
context 'When no block or argument is given' do
it 'raises a LocalJumpError' do
expect { rng.my_inject }.to raise_error LocalJumpError
end
end
context 'When an initial value and a symbol are given' do
it 'it returns the accumulation of the block result, accumulating from the initial value' do
expect(rng.my_inject(ary_case1[0], ary_case1[1])).to eq(rng.inject(ary_case1[0], ary_case1[1]))
end
end
context 'When only a symbol is given' do
it 'it passes the symbol to the block and returns the accum' do
expect(rng.my_inject(arg_case2)).to eq(rng.inject(arg_case2))
end
end
context 'When an initial value and a block are given' do
it 'it returns the accumulation of the block result, accumulating from the initial value' do
expect(rng.my_inject(initial_value) { :block_case3 }).to eq(rng.inject(initial_value) { :block_case3 })
end
end
context 'When only a block given' do
it 'the block is passed each element in the object' do
expect(words.my_inject(&block_case4)).to eq(words.inject(&block_case4))
end
end
end
describe '#multiply_els' do
it 'accepts an array as an argument and multiplies each element together using #my_inject' do
my_method = multiply_els [3, 5, 8]
expect(my_method).to eq 120
end
end
end
|
class RemoveMedicationFromMedicationInteractions < ActiveRecord::Migration[5.1]
def change
remove_reference :medication_interactions,
:medication
end
end
|
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
include AuthenticatedSystem
before_filter :adjust_for_group
before_filter :adjust_format_for_iphone
before_filter :login_required
before_filter :check_group_access
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
layout 'common'
# Scrub sensitive parameters from your log
# filter_parameter_logging :password
protected
def access_denied
redirect_to "/"
end
# store the grouping in the request. Determine grouping from server_name prefix
def adjust_for_group
puts ">>> SERVER_NAME=#{request.env["SERVER_NAME"]}"
if request.env["SERVER_NAME"] =~ /^(.*?)\./
prefix = $1
@grouping = Grouping.find(:first, :conditions=>["prefix=?", prefix]) || Grouping.default_grouping
else
@grouping = Grouping.default_grouping
end
end
# check that current_user belongs to the current grouping. If not: logout
def check_group_access
if current_user
if current_user.grouping.id != @grouping.id
logout_killing_session!
redirect_to('/')
end
end
end
def adjust_format_for_iphone
request.format = :mobile if @grouping.prefix != 'uptown' and (iphone_request? or android_request? or mobile_server_request?)
end
def iphone_request?
request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(Mobile\/.+Safari)/]
end
def android_request?
request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/Android/]
end
def mobile_server_request?
request.env["SERVER_NAME"] =~ /^.*?\.mobile\./
end
end
|
class Instrument < ApplicationRecord
has_many :albums
has_many :artists, through: :albums
end |
require 'date'
require 'active_support/core_ext/integer/inflections'
# rspec should is deprecated
# Formats date range
class DateRangeFormatter
def initialize(from, to, from_time = nil, to_time = nil)
@from = Date.parse(from)
@to = Date.parse(to)
@from_time = from_time
@to_time = to_time
end
def format(date)
date.strftime "#{date.day.ordinalize} %B %Y"
end
def format_with_time(date, time, type)
time = time.nil? ? '' : " #{type} #{time}"
date.strftime "#{date.day.ordinalize} %B %Y#{time}"
end
def format_short(date)
date.strftime "#{date.day.ordinalize} %B"
end
def normal_format(from, to, from_time, to_time)
f = format_with_time(from, from_time, :at)
t = format_with_time(to, to_time, :at)
"#{f} - #{t}"
end
def same_format(from, from_time, to_time)
base = format(from)
base += " at #{from_time}" unless from_time.nil?
base += " to #{to_time}" unless to_time.nil?
base
end
def same_month_format(from, to)
to_day = to.day.ordinalize
from.strftime "#{from.day.ordinalize} - #{to_day} %B %Y"
end
def same_month_format_with_time(from, to, from_time, to_time)
f = format_with_time(from, from_time, :at)
t = format_with_time(to, to_time, :at)
"#{f} - #{t}"
end
def same_year_format(from, to)
year = to.year
f = format_short(from)
t = format_short(to)
"#{f} - #{t} #{year}"
end
def to_s
if @from == @to
same_format(@from, @from_time, @to_time)
elsif @from.year == @to.year && @from.month == @to.month
if @from_time.nil? && @to_time.nil?
same_month_format(@from, @to)
else
same_month_format_with_time(@from, @to, @from_time, @to_time)
end
elsif @from.year == @to.year && @from_time.nil? && @to_time.nil?
same_year_format(@from, @to)
else
normal_format(@from, @to, @from_time, @to_time)
end
end
end
|
FactoryGirl.define do
factory :exercise_task do
title 'Test Exercise Task'
description 'Test Description'
instructions 'Test instructions'
end
end |
class Encounter < ApplicationRecord
include Mergeable
extend SQLHelpers
belongs_to :patient, optional: true
belongs_to :facility
has_many :observations
has_many :blood_pressures, through: :observations, source: :observable, source_type: "BloodPressure"
has_many :blood_sugars, through: :observations, source: :observable, source_type: "BloodSugar"
has_one :cphc_migration_audit_log, as: :cphc_migratable
scope :for_sync, -> { with_discarded }
def self.generate_id(facility_id, patient_id, encountered_on)
UUIDTools::UUID
.sha1_create(UUIDTools::UUID_DNS_NAMESPACE,
[facility_id, patient_id, encountered_on].join(""))
.to_s
end
def self.generate_encountered_on(time, timezone_offset)
time
.to_time
.utc
.advance(seconds: timezone_offset)
.to_date
end
end
|
class RemoveAfpIdfromWorkers < ActiveRecord::Migration
def change
remove_column :workers, :afp_id
remove_column :workers, :afptype
remove_column :workers, :afpnumber
end
end
|
class Site
include Singleton
attr_accessor :root_directory
def initialize(root_directory)
@root_directory = root_directory
end
def self.file_data(path)
path = self.instance.resolve_path(path)
self.instance.read_file(path)
end
def resolve_path(path)
file_read_path = "#{@root_directory}#{path}"
file_read_path = file_read_path + "index.html" if file_read_path[-1] == "/"
end
def read_file(path)
if File.exist?(file_read_path)
file_data = File.read(file_read_path)
@logger.debug "Serving : #{file_read_path}"
else
file_data = "<html><head</head><body>Error 404</body></html>"
@logger.warn "Error: 404"
end
if file_read_path.include?(".html")
file_data = file_data.gsub("<body>","<body><div style=\"\">This page is being served by Tye's Ruby HTTP Server.<br />Requested Path: #{request_path}<br />Your Address: #{client_address}</div><hr /><br />")
end
file_data
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.