text stringlengths 10 2.61M |
|---|
class Passenger
attr_reader :name
@@all = []
def initialize (name)
@name = name
@@all << self unless @@all.any?(self)
end
def drivers
rides.all.map {|ride| ride.driver }
end
def rides
Ride.all.select {|ride| ride.passenger == self}
end
def total_distance
rides.inject(0) { |sum, ride| sum + ride.distance }
end
def self.premium_members
Ride.premium
end
def self.all
@@all
end
end
|
require 'logger'
require 'open3'
require 'erb'
module Dotpkgbuilder
class Stage
attr_reader :context, :log
delegate :working_dir, to: :context
def initialize(context, options = {})
@context = context
@log = options[:log] || Logger.new(STDOUT)
end
def run; end
protected
def dir
@dir || working_dir
end
def inside(dir, &block)
@dir = dir
log.info "chdir #{dir.inspect}"
result = block.call
@dir = nil
result
end
def sh(cmd)
log.info "#{@dir}$ #{cmd}"
stdout, stderr, status = Open3.capture3(cmd, chdir: dir)
if status.success?
log.info stdout
stdout
else
log.error stderr
stderr
end
end
def use(stage)
log.info "*** #{stage}"
instance = stage.new(context, log: @log)
instance.run
end
def render_erb(files)
files.each do |(erb_in, erb_out)|
erb = ERB.new(File.read(erb_in), nil, '-')
result = erb.result(binding)
log.info "[erb] #{erb_in} -> #{erb_out}"
File.write(erb_out, result)
end
end
def provide(context_var, value)
if context.respond_to?("#{context_var}=")
log.info "#{context_var}=#{value.inspect}"
context.send("#{context_var}=", value)
raise 'oops' unless context.send(context_var) == value
end
end
end
end
|
#!/usr/bin/ruby
require 'optparse'
require 'json'
def cmd_line()
options = {}
optparse = OptionParser.new do |opts|
opts.banner = "Usage: #{opts.program_name}"
opts.on("-s","--session [STRING]","session name") do |s|
options[:session] = s
end
opts.on("-l","--host_list [STRING]","path to host list.") do |s|
host_list = File.open(s).readlines.map { |line| line.strip }
options[:host_list] = host_list
end
options[:user] = `echo $USER`.chomp
opts.on('-u', '--user [USER]', 'The user to login as. Default=<current user>') do |s|
options[:user] = s
end
options[:max_panes] = 20
opts.on("-m","--max_panes [INT]", OptionParser::DecimalInteger, "Max number of panes per session.") do |s|
options[:max_panes] = s
end
opts.on('-r',"--aws_region [REGION]", "The region to use when looking up hosts.") do |s|
options[:aws_region] = s
end
options[:aws_tag] = []
opts.on('-t', "--aws_tag [TAG]", "The name of the aws tag to use for looking up hosts.") do |s|
options[:aws_tag].push(s)
end
opts.on('-d', '--debug', 'Will print debug info.') do |s|
options[:debug] = s
end
opts.on('--list-hosts', "Outputs list of hosts and then exits.") do |s|
options[:list_hosts] = s
end
opts.on('--get-tags', 'Output the tags.') do |s|
options[:get_tags] = s
end
end
optparse.parse!
# Set the session name if it is not set.
if options[:session] == nil
options[:session] = "tmux_session_#{$$}"
end
return options
end
class AwsHosts
attr_reader :instances
def initialize(debug=nil)
@instances = []
@debug = debug
end
def get_hosts_by_tag_value(tag_array, region=nil)
query_str = %/--query "Reservations[].Instances[].{ n1: Tags[?Key == 'Name'].Value, t1: Tags } | [*].{ name: n1[0], tags: t1 }"/
filters = tag_array.collect { |x| "Name=tag-value,Values=#{x}" }.join(' ')
command = ["aws ec2 describe-instances"]
unless region.nil?
command.push("--region #{region}")
end
command.push("--filter #{filters} Name=instance-state-name,Values=running")
command.push("#{query_str}")
if @debug
puts "AWS command used => #{command.join('')}\n\n"
end
output = %x(#{command.join(' ')})
@instances = JSON.parse(output)
end
def list_hosts()
@instances.map { |host| host['name'] }
end
def print_host_list()
puts self.list_hosts().join("\n")
end
def print_instances()
puts JSON.pretty_generate(@instances)
end
end
def starttmux(host_ary, opts)
max_pane = opts[:max_panes]
cmd = 'tmux'
user = opts[:user]
session = opts[:session]
ittr_hosts = host_ary.each_slice(max_pane).to_a
ittr_hosts.each do |mem_ary|
system("#{cmd} new-session -d -s #{session}")
main_pane = %x(#{cmd} list-panes | awk {'print $1'} | sed s/://)
#print "main_pane is #{main_pane}"
mem_ary.each do |host|
puts "Adding #{host}"
run="#{cmd} split-window -v -t #{session} \"ssh -l #{user} #{host}\""
system(run)
run='tmux select-layout tiled'
system(run)
end
system("#{cmd} set-window-option synchronize-panes on")
system("#{cmd} kill-pane -t #{main_pane}")
system("#{cmd} attach -t #{session}")
end
end
def main(options)
if options[:debug]
puts "Options => #{options}\n\n"
end
ah_obj = AwsHosts.new(options[:debug])
host_ary = []
if options[:host_list]
host_ary = options[:host_list]
elsif not options[:aws_tag].empty?
ah_obj.get_hosts_by_tag_value(options[:aws_tag], options[:aws_region])
host_ary = ah_obj.list_hosts
end
if host_ary.empty?
print "No hosts."
exit(1)
end
if options[:debug]
puts "host_ary => #{host_ary}\n\n"
end
if options[:list_hosts]
if not options[:aws_tag].empty?
puts "List hosts from aws_tag." unless options[:debug].nil?
print ah_obj.print_host_list
elsif options[:host_list]
puts "List hosts from host list." unless options[:debug].nil?
puts host_ary
end
exit(0)
elsif options[:get_tags]
puts "List the host data." unless options[:debug].nil?
print ah_obj.print_instances
exit(0)
end
starttmux(host_ary, options)
end
if __FILE__ == $0
options = cmd_line()
main(options)
end
|
#encoding: UTF-8
require 'mongoid'
require 'rubygems'
require 'nokogiri'
require 'open-uri'
require 'pp'
require_relative "common"
Dir.glob("#{File.dirname(__FILE__)}/app/models/*.rb") do |lib|
require lib
end
ENV['MONGOID_ENV'] = 'local'
Mongoid.load!("config/mongoid.yml")
class GetCarAndDetail
include Common
def initialize(sid = "", webmaker ="" , maker = "", brand ="", from_site ="")
@sid = sid
@maker = maker
@brand = brand
@brand_num = sid.split('-')[1].to_s
@webmaker = webmaker
@from_site = from_site
end
def read_chexi
brand_url = "http://car.autohome.com.cn/price/#{@sid}.html"
@doc_brand = fetch_chexing(brand_url)
return if @doc_brand.nil?
@doc_brand.xpath('//div[@class="brand_r"]/ul/li').each do |item|
if item.at_xpath('div/a/text()').to_s == @webmaker
item.xpath('div[@class="brand_car"]//a').each_with_index do |object, i|
chexi = object.at_xpath('@title').to_s
chexi = chexi.split('(')[0].strip
url = object.at_xpath('@href').to_s
chexi_num = url.scan(/\d+/)[0]
#get the chexing's url
chexing_url = "http://www.autohome.com.cn/#{chexi_num}/" #http://www.autohome.com.cn/826/
@doc_chexing = fetch_chexing(chexing_url)
# the new rule of autohome website
# data:2013-8-6
# 1.online soon
@doc_chexing.xpath("//div[@id='speclist10']/ul/li/div[1]/div/p/a[1]").each do |myobj|
chexing = myobj.at_xpath('text()').to_s.strip
year = chexing.split(' ')[0].strip
chexing = chexing[5..-1].strip
chexing_num = myobj.at_xpath('@href').to_s.strip.split('/')[2].to_s
pic_url = "http://car.autohome.com.cn/pic/series-s#{chexing_num}/#{chexi_num}.html"
#break
save_chexing(@maker, chexi, chexing, year, chexi_num, chexing_num, pic_url, @from_site, status = 'init')
end #end of online soon
#break
# 2.on sale
@doc_chexing.xpath("//div[@id='speclist20']/ul/li/div[1]/div/p/a[1]").each do |myobj|
chexing = myobj.at_xpath('text()').to_s.strip
year = chexing.split(' ')[0].strip
chexing = chexing[5..-1].strip
chexing_num = myobj.at_xpath('@href').to_s.strip.split('/')[2]
pic_url = "http://car.autohome.com.cn/pic/series-s#{chexing_num}/#{chexi_num}.html"
#break
save_chexing(@maker, chexi, chexing, year, chexi_num, chexing_num, pic_url, @from_site, status = 'init')
end #end of on sale
#break
# 3.off sale
@doc_chexing.xpath("//div[@id='drop2']//a").each do |myobj|
year = myobj.at_xpath('text()').to_s.strip
y = myobj.at_xpath('@data').to_s.strip
s = chexi_num
my_url = "http://www.autohome.com.cn/ashx/series_allspec.ashx?s=#{s}&y=#{y}"
html_stream = open_http(my_url)
#from json get chexing
s_json = JSON.parse(html_stream)
s_json["Spec"].each do |myitem|
chexing_num = myitem["Id"]
chexing = myitem["Name"]
chexing = chexing[5..-1].strip
pic_url = "http://car.autohome.com.cn/pic/series-s#{chexing_num}/#{chexi_num}.html"
save_chexing(@maker, chexi, chexing, year, chexi_num, chexing_num, pic_url, @from_site, status = 'init')
end
end #end of off sale
# 4. old rule
if @doc_chexing.xpath("//div[@class='tabwrap']//td[@class='name_d']/a").length == 0
all_chexing = @doc_chexing.xpath("//select[@class= 'select-carpic-filter']/option").each do |myobj|
chexing = myobj.at_xpath('text()').to_s.strip
year = chexing.split(' ')[0].strip
chexing = chexing[5..-1].strip
chexing_num = myobj.at_xpath('@value').to_s.strip
pic_url = "http://car.autohome.com.cn/pic/series-s#{chexing_num}/#{chexi_num}.html"
save_chexing(@maker, chexi, chexing, year, chexi_num, chexing_num, pic_url, @from_site, status = 'init')
end
else
all_chexing = @doc_chexing.xpath("//div[@class='tabwrap']//td[@class='name_d']/a")
all_chexing.each do |myobj|
chexing = myobj.at_xpath('@title').to_s.strip
year = chexing.split(' ')[0].strip
chexing = chexing[5..-1].strip
chexing_num = myobj.at_xpath('@href').to_s.strip.split('/')[1]
pic_url = "http://car.autohome.com.cn/pic/series-s#{chexing_num}/#{chexi_num}.html"
save_chexing(@maker, chexi, chexing, year, chexi_num, chexing_num, pic_url, @from_site, status = 'init')
end
end #end of old rule
#Data 2013-9-10 add autohome's sale.html page,the stopsale'car lost if this year has saleing cars.
#add stop sale page's car
puts chexing_sale_url = "http://www.autohome.com.cn/#{chexi_num}/sale.html" #http://www.autohome.com.cn/826/sale.html
@doc_chexing = fetch_chexing(chexing_sale_url)
next if @doc_chexing.nil?
@doc_chexing.xpath("//td[@class='name_d']/a").each do |myobj|
chexing = myobj.at_xpath('@title').to_s.strip
year = chexing.split(' ')[0].strip
chexing = chexing[5..-1].strip
chexing_num_str = myobj.at_xpath('@href').to_s
chexing_num = chexing_num_str.to_s.strip.split('/')[1]
pic_url = "http://car.autohome.com.cn/pic/series-s#{chexing_num}/#{chexi_num}.html"
#puts "#{chexi}-#{chexing}-#{year}-#{chexing_num}"
save_chexing(@maker, chexi, chexing, year, chexi_num, chexing_num, pic_url, @from_site, status = 'init')
end
end# end of object
end #end of if
end #end of doc_brand
end #end of read_chexi
def run
end
def save_pic
# @cars = Car.where(:maker => @maker, :from_site => @from_site, :status => 'update')
@cars = Car.where(maker: @maker, brand: @brand, pics: nil, from_site: @from_site).asc(:created_at)
puts @cars.length
@cars.each do |car|
fetch_chexing(car.pic_url)
puts car.pic_url
imgs = []
@doc_chexing.xpath("//div[@class='r_tit']//img/@src").each_with_index do |img, j|
break if j > 9
@pic = Pic.new
@pic.name = "#{car.maker}_#{car.chexi}_#{car.year}_#{car.chexing}_#{j+1}"
img = img.to_s.gsub('s_' , '')
@pic.url = img
imgs << @pic
end
car.pics = imgs
puts car.pic_num = imgs.length
car.save
end
end
def save_config
create_file_to_write('config_save')
#@cars = Car.where(:maker => @maker).desc(:created_at)
@cars = Car.where(maker: @maker, brand: @brand, parameters: nil, from_site: @from_site).desc(:created_at)
#@cars = Car.where(:maker => @maker, :from_site => @from_site).desc(:created_at)
puts length = @cars.count
# return
@cars.all.each_with_index do |car, i|
@num = 0
#next if i < 100
params = []
print "#{@brand}-#{@maker}-#{i}/#{length} "
puts url = "http://www.autohome.com.cn/spec/#{car.chexing_num}/config.html"
@file_to_write.puts "#{i}-#{url}"
html_stream = open_http(url).strip
html_stream.encode!('utf-8', 'gbk', :invalid => :replace)
@doc = Nokogiri::HTML(html_stream)
#@file_to_write.puts @doc.to_s
#break
if @doc.css('script').length < 7
puts "error"
@file_to_write.puts "error-#{i}-#{url}"
next
end
@doc.css('script').each do |item|
puts item.to_s.length
end
str = @doc.css('script')[6].text.to_s
puts "the script's length #{str.length}"
next if str.length < 2000
#break
#替换规则-单行
# update 2013-9-5 add the 2 lines to delete the first
str.gsub!(/var levelId.*;/, '')
str = str.strip
# 'var ' => '["' 行头
str.gsub!('var ' , '{"')
# ' = ' => '":"' 中
str.gsub!(' = ' , '" : ')
# '};' => '],' 行尾
str.gsub!('};' , '}} ,')
str = "{\"root\" : [#{str}{\"end\" : \"yes\"}]}"
#str = '{"sub" : "100"},'
#str = "{\"root\" : [#{str}{\"end\" : \"yes\"}]}"
#puts str
s_json = JSON.parse(str)
s_json["root"].each do |item|
item.each do |key , value|
puts key
if (key == "config" || key == "option")
puts value["result"]["paramtypeitems"].length if key == "config" #分组
puts value["result"]["configtypeitems"].length if key == "option" #分组
groups = value["result"]["paramtypeitems"] if key == "config"
groups = value["result"]["configtypeitems"] if key == "option"
groups.each do |g_value|
g_value.each do |g_key, sub_g_value|
puts @category = sub_g_value if g_key == "name"
#break
if g_key == "paramitems" || g_key == "configitems"
sub_g_value.each do |item|
#puts
name = item["name"]
item["valueitems"].each do |i_value|
if car.chexing_num.to_s == i_value['specid'].to_s
#puts i_value['value']
@num += 1
@para = Parameter.new
@para.name = name
@para.value = i_value['value']
@para.category = @category
@para.num = @num
params << @para
end
end
end
#
end
end
end
end
end
end
car.parameters = params
car.save
puts "saved!"
end
end
def down_pic(pre_folder)
if(File.exist?(pre_folder))
puts "folder '#{pre_folder}' structure already exist!"
else
Dir.mkdir(pre_folder) #if folder not exist,then creat it.
end
create_file_to_write('pic_download')
# @cars = Car.where(:maker => @maker, :from_site => @from_site, :status => 'update').desc(:created_at)
@cars = Car.where(maker: @maker, brand: @brand, from_site: @from_site).asc(:created_at)
#@cars = Car.all.asc(:created_at)
puts @cars.length
@cars.each_with_index do |car , c_i|
#next if c_i < 255
car.pics.each_with_index do |item, p_i|
#next if p_i < 1 && c_i < 1
puts "#{c_i} -#{p_i}"
@file_to_write.puts "#{c_i} -#{p_i}"
houzui = item.url.strip.from(-4)
puts filename = item.name + houzui
filename.gsub!("/", "_")
filename.gsub!("\\", "_")
filename.gsub!("*", "_")
filename.gsub!('"', "_")
puts item.url
if File.exist?("./#{pre_folder}/#{filename}")
puts "exist!"
else
download_images(pre_folder, filename, item.url)
end
#break
end
#break
end
end
def export_report_test(name = "report")
create_file_to_write(name)
@cars = Car.where(:maker => @maker, :from_site => @from_site).desc(:chexi_num)
@cars.all.each_with_index do |car, i|
@file_to_write.puts "#{i}\t#{car.maker}\t#{car.chexi}\t#{car.chexi_num}\t#{car.year}\t#{car.chexing}\t#{car.chexing_num}\t#{car.pic_num}\t#{car.from_site}\t#{car.status}"
end
end
def remove_maker
@cars = Car.where(:maker => @maker, :from_site => @from_site)
@cars.delete
end
def export_report(name = "report")
create_file_to_write(name)
@cars = Car.where(:maker => @maker, :from_site => @from_site).desc(:chexi_num)
length = @cars.count
@title2 = []
@title1 = ["品牌","车系", "年款", "名称", "图片前缀","张数", "来源"]
@cars.all.each_with_index do |car, i|
print "#{i} "
car.parameters.each do |param|
#str << "#{param.value}\t"
@title2 << param.name
#puts "#{param.name}\t#{param.value}"
end
@title2.uniq!
end
@title = @title1 + @title2
@file_to_write.puts @title.join('$')
@cars.all.each_with_index do |car, i|
print "#{i} "
str = ""
@title2.each do |title|
car.parameters.each do |param|
if (title == param.name && title != "车身颜色")
txt_str = param.value
#txt_str = CGI::unescape(txt_str)
#txt_str.color_str_to_line
str << txt_str
end
end
str << "\t"
end
qianzui = "#{car.maker}_#{car.chexi}_#{car.year}_#{car.chexing}"
@file_to_write.puts "#{car.maker}\t#{car.chexi}\t#{car.year}\t#{car.chexing}\t#{qianzui}\t#{car.pic_num}\t#{car.from_site}\t#{str}"
#break
end
end
private
def create_file_to_write(name = 'file')
file_path = File.join('.', "#{name}-#{Time.now.to_formatted_s(:number) }.txt")
@file_to_write = IoFactory.init(file_path)
end #create_file_to_write
def download_images(pre_folder, filename, url)
sleep_time = 0.34
retries = 2
File.open("./#{pre_folder}/#{filename}", "wb") do |saved_file|
begin
open(url) do |read_file|
saved_file.write(read_file.read)
end
rescue StandardError,Timeout::Error, SystemCallError, Errno::ECONNREFUSED
puts $!
retries -= 1
if retries > 0
sleep sleep_time and retry
else
#logger.error($!)
#错误日志
#TODO Logging..
end
end
end
end #end of download_images
def fetch_chexing(detail_url)
@doc_chexing = nil
html_stream = safe_open(detail_url , retries = 5, sleep_time = 0.32, headers = {})
return nil if html_stream.nil?
# begin
html_stream.encode!('utf-8', 'gbk', :invalid => :replace) #忽略无法识别的字符
# rescue StandardError,Timeout::Error, SystemCallError, Errno::ECONNREFUSED #有些异常不是标准异常
# puts $!
# end
@doc_chexing = Nokogiri::HTML(html_stream)
end
def open_http(url)
safe_open(url , retries = 5, sleep_time = 0.43, headers = {})
end #end of open_http
def update_chexing(maker, chexi, chexing, year, chexi_num, chexing_num, pic_url, from_site, status = 'update')
# @car = Car.where(:chexing_num => chexing_num.to_s, :from_site => from_site)
# return if @car.length > 0
# @car = Car.create(:chexing_num => chexing_num.to_s, :from_site => from_site)
@car = Car.find_or_create_by(:chexing_num => chexing_num.to_s, :from_site => from_site)
@car.brand = @brand
@car.brand_num = @brand_num
@car.maker = maker
@car.chexi = chexi
@car.chexing = chexing
@car.year = year
@car.chexi_num = chexi_num.to_s
@car.pic_url = pic_url
@car.status = status
@car.save
end #end of update_chexing
def save_chexing(maker, chexi, chexing, year, chexi_num, chexing_num, pic_url, from_site, status = 'init')
# @car = Car.where(:chexing_num => chexing_num.to_s, :from_site => from_site)
# return if @car.length > 0
# @car = Car.create(:chexing_num => chexing_num.to_s, :from_site => from_site)
@car = Car.find_or_create_by(:chexing_num => chexing_num.to_s, :from_site => from_site)
@car.brand = @brand
@car.brand_num = @brand_num
@car.maker = maker
@car.chexi = chexi
@car.chexing = chexing
@car.year = year
@car.chexi_num = chexi_num.to_s
@car.pic_url = pic_url
@car.status = status
@car.save
puts "#{@brand}-#{@brand_num}-#{maker}-#{chexi}-#{chexing}-#{year}-saved!"
end #end of save_chexing
end
|
class Smpp::Transceiver < Smpp::Base
# Expects a config hash,
# a proc to invoke for incoming (MO) messages,
# a proc to invoke for delivery reports,
# and optionally a hash-like storage for pending delivery reports.
def initialize(config, mo_proc, dr_proc, pdr_storage={})
super(config)
@state = :unbound
@mo_proc = mo_proc
@dr_proc = dr_proc
@pdr_storage = pdr_storage
# Array of un-acked MT message IDs indexed by sequence number.
# As soon as we receive SubmitSmResponse we will use this to find the
# associated message ID, and then create a pending delivery report.
@ack_ids = Array.new(512)
ed = @config[:enquire_link_delay_secs] || 5
comm_inactivity_timeout = [ed - 5, 3].max
rescue Exception => ex
logger.error "Exception setting up transceiver: #{ex}"
raise
end
# Send an MT SMS message
def send_mt(message_id, source_addr, destination_addr, short_message, options={})
logger.debug "Sending MT: #{short_message}"
if @state == :bound
pdu = Pdu::SubmitSm.new(source_addr, destination_addr, short_message, options)
write_pdu pdu
# keep the message ID so we can associate the SMSC message ID with our message
# when the response arrives.
@ack_ids[pdu.sequence_number] = message_id
else
raise InvalidStateException, "Transceiver is unbound. Cannot send MT messages."
end
end
# Send an MT SMS message
def send_multi_mt(message_id, source_addr, destination_addr_arr, short_message, options={})
logger.debug "Sending Multiple MT: #{short_message}"
if @state == :bound
pdu = Pdu::SubmitMulti.new(source_addr, destination_addr_arr, short_message, options)
write_pdu pdu
# keep the message ID so we can associate the SMSC message ID with our message
# when the response arrives.
@ack_ids[pdu.sequence_number] = message_id
else
raise InvalidStateException, "Transceiver is unbound. Cannot send MT messages."
end
end
# a PDU is received
def process_pdu(pdu)
case pdu
when Pdu::DeliverSm
write_pdu(Pdu::DeliverSmResponse.new(pdu.sequence_number))
logger.debug "ESM CLASS #{pdu.esm_class}"
if pdu.esm_class != 4
# MO message; invoke MO proc
@mo_proc.call(pdu.source_addr, pdu.destination_addr, pdu.short_message)
else
# Invoke DR proc (let the owner of the block do the mapping from msg_reference to mt_id)
@dr_proc.call(pdu.msg_reference.to_s, pdu.stat)
end
when Pdu::BindTransceiverResponse
case pdu.command_status
when Pdu::Base::ESME_ROK
logger.debug "Bound OK."
@state = :bound
when Pdu::Base::ESME_RINVPASWD
logger.warn "Invalid password."
EventMachine::stop_event_loop
when Pdu::Base::ESME_RINVSYSID
logger.warn "Invalid system id."
EventMachine::stop_event_loop
else
logger.warn "Unexpected BindTransceiverResponse. Command status: #{pdu.command_status}"
EventMachine::stop_event_loop
end
when Pdu::SubmitSmResponse
mt_message_id = @ack_ids[pdu.sequence_number]
if !mt_message_id
raise "Got SubmitSmResponse for unknown sequence_number: #{pdu.sequence_number}"
end
if pdu.command_status != Pdu::Base::ESME_ROK
logger.error "Error status in SubmitSmResponse: #{pdu.command_status}"
else
logger.info "Got OK SubmitSmResponse (#{pdu.message_id} -> #{mt_message_id})"
end
# Now we got the SMSC message id; create pending delivery report
@pdr_storage[pdu.message_id] = mt_message_id
when Pdu::SubmitMultiResponse
mt_message_id = @ack_ids[pdu.sequence_number]
if !mt_message_id
raise "Got SubmitMultiResponse for unknown sequence_number: #{pdu.sequence_number}"
end
if pdu.command_status != Pdu::Base::ESME_ROK
logger.error "Error status in SubmitMultiResponse: #{pdu.command_status}"
else
logger.info "Got OK SubmitMultiResponse (#{pdu.message_id} -> #{mt_message_id})"
end
else
super
end
end
# Send BindTransceiverResponse PDU.
def send_bind
raise IOError, 'Receiver already bound.' unless @state == :unbound
pdu = Pdu::BindTransceiver.new(
@config[:system_id],
@config[:password],
@config[:system_type],
@config[:source_ton],
@config[:source_npi],
@config[:source_address_range])
logger.info "Bind : #{pdu.to_human}"
write_pdu(pdu)
end
end
|
# BackgrounDRb Worker to reprocess assets.
class ProcessorReprocessWorker < BackgrounDRb::Rails
# Reprocess and attactment - and sets it's backgroundrb_job_key to nil when it's done.
# Expects args to be a hash - with values for the :class and :id of the Model Object to reprocess.
# def do_work(args)
# asset_class = eval("#{args[:class]}")
# asset_id = args[:id]
# asset_to_process = asset_class.find(asset_id)
# asset_to_process.reprocess_asset_without_backgroundrb
# key = asset_to_process.backgroundrb_job_key
# asset_class.update_all(['backgroundrb_job_key = ?', nil], ['id = ?', asset_id])
# MiddleMan.delete_worker(key)
# end
end |
class AddConsumerToExternals < ActiveRecord::Migration
def change
add_column :externals, :consumer_id, :integer
add_column :externals, :consumer_type, :string
end
end
|
require 'rails_helper'
RSpec.describe AppsController, type: :controller do
let(:user) { create(:user) }
before(:each) { login(user) }
describe "GET #index" do
it "returns a success response" do
create(:app, user: user)
get :index
expect(response).to be_successful
end
end
describe "GET #show" do
it "returns a success response" do
app = create(:app, user: user)
get :show, params: {name: app.name}
expect(response).to be_successful
end
end
describe "POST #create" do
context "with valid params" do
it "creates a new app" do
expect {
post :create, params: {app: attributes_for(:app)}
}.to change(App, :count).by(1)
end
it "renders a JSON response with the new app" do
post :create, params: {app: attributes_for(:app)}
expect(response).to have_http_status(:created)
expect(response.content_type).to eq('application/json')
expect(response.location).to eq(app_url(App.last))
end
end
context "with invalid params" do
it "renders a JSON response with errors for the new app" do
app = attributes_for(:app)
app[:api] = "unsupported-one"
post :create, params: {app: app}
expect(response).to have_http_status(:unprocessable_entity)
expect(response.content_type).to eq('application/json')
end
end
end
describe "PUT #update" do
context "with valid params" do
it "updates the requested app" do
app = create(:app, user: user)
valid = { api: "nodejs" }
put :update, params: {name: app.name, app: valid}
app.reload
expect(response).to be_successful
end
it "renders a JSON response with the app" do
app = create(:app, user: user)
put :update, params: {name: app.name, app: attributes_for(:app)}
expect(response).to have_http_status(:ok)
expect(response.content_type).to eq('application/json')
end
end
context "with invalid params" do
it "renders a JSON response with errors for the app" do
app = create(:app, user: user)
invalid = { api: "unsupported-one" }
put :update, params: {name: app.name, app: invalid}
expect(response).to have_http_status(:unprocessable_entity)
expect(response.content_type).to eq('application/json')
end
end
end
describe "DELETE #destroy" do
it "destroys the requested app" do
app = create(:app, user: user)
expect {
delete :destroy, params: {name: app.name}
}.to change(App, :count).by(-1)
end
end
end
|
class Asset < ActiveRecord::Base
belongs_to :uploadable, polymorphic: true
acts_as_list
scope :ordered, -> { order(:position) }
class << self
def permitted_params
[ :id, :attachment, :uploadable_type, :uploadable_id, :description, :position, :_destroy ]
end
end
def scope_condition
"assets.uploadable_id = #{uploadable_id} and assets.uploadable_type='#{uploadable_type}'"
end
end |
require 'tadb'
require_relative '../src/PersistentAttribute'
module Persistible
def self.table(table_name)
TADB::Table.new(table_name)
end
module ClassMethods
def all_instances
classes_to_instance = descendants.clone << self
classes_to_instance.map do |klass|
Persistible.table(klass).entries.map{|hashToConvert|
new_instance = klass.new #ROMPE SI INITIALIZE RECIBE PARÁMETROS (!!!)
new_instance.id = hashToConvert[:id]
new_instance.refresh!
}
end.flatten
end
def method_missing(sym, *args, &block)
if is_finder? sym
name = sym.to_s.split('find_by_').last.to_sym
return all_instances.select{|rd| rd.send("#{name}").eql?(args[0]) }
else
super
end
end
def respond_to_missing?(sym, include_all = false)
is_finder? sym || super
end
def is_finder?(method)
(method.to_s.start_with? 'find_by_') && is_parameterless_method?(method.to_s.split('find_by_').last.to_sym)
end
def is_parameterless_method? (methodName)
@attr_information.keys.include?(methodName) || (instance_method(methodName).arity==0 if method_defined? methodName)
#Se esta obteniendo @attr_information de la clase
end
end
module InstanceMethods
def table=(table)
@table = table
end
def attr_information=(hash_attr_information)
@attr_information = hash_attr_information
end
def persistent_attributes=(hash_persistent_attributes)#@persistent_attributes contiene los valores propios de la instancia
@persistent_attributes = hash_persistent_attributes
end
def persistent_attributes
@persistent_attributes ||= {}
end
def id
@id
end
def id=(argument)
@id=argument
end
def is_persisted?
!@id.nil?
end
def save!
validate!
if is_persisted?
@table.delete(id)
end
hash_to_persist = @persistent_attributes.map_values{|name, value| @attr_information[name].save(value)}
hash_to_persist[:id] = @id
@id=@table.insert(hash_to_persist)
end
def refresh!
if !is_persisted?
raise 'This object does not exist in the database'
end
hash_to_refresh = @table.entries.find{|entry| entry[:id] == @id}
hash_to_refresh.delete_if{|name, value| name.eql? :id}#elimino el id del hash, porque no se guarda en @persistent_attributes
@persistent_attributes = hash_to_refresh.map_values{|name, value| @attr_information[name].refresh(value)}
self #devuelvo el objeto actualizado (útil para la composición)
end
def forget!#HAY QUE CASCADEARLO (???)
@table.delete(@id)
@id = nil
end
def validate!
@persistent_attributes.each{|name, value| @attr_information[name].validate(value)}
end
end
def self.included(klass)
klass.include(InstanceMethods)
klass.extend(ClassMethods)
end
end
class Module
alias_method :no_persistence_attr_accessor, :attr_accessor
def has_one(type, named:,default: nil,**hash_validations)
hash_validations ||= {}#SE PUEDE PONER COMO VALOR DEFAULT?
initialize_persistent_attribute(default, named)
@attr_information[named] = PersistentAttribute.simple(type, default, hash_validations)
end
def has_many(type, named:, default: nil,**hash_validations)
hash_validations ||= {}#SE PUEDE PONER COMO VALOR DEFAULT?
initialize_persistent_attribute(default, named)
@attr_information[named] = PersistentAttribute.multiple(type, default, hash_validations)
end
def initialize_persistent_attribute(default, named)
if !is_persistible?
@campos_default = {}#@campos_default contiene las claves (nombres de atributos) y los valores default que van a tener TODAS las instancias
@attr_information = {}
self.include(Persistible)
end
@campos_default[named] = default#seteo valor por default (y me guardo como clave el nombre del atributo)
end
def attr_accessor(*syms)
syms.each do |sym|
if sym.to_s[-1].eql? 's'
is_multiple = true
name = sym.to_s.chomp('s')
else
is_multiple = false
name = sym.to_s
end
type_name = name.capitalize
if ((klass=Object.const_get(type_name)) && klass.is_a?(Class) && klass.is_persistible? rescue false)
#EL RESCUE ES UNA PORQUERÍA, PERO SINO EL CONST_GET ROMPE AL NO ENCONTRAR LA CONSTANTE
if(is_multiple)
has_many klass, named: sym
else
has_one klass, named: sym
end
else
no_persistence_attr_accessor(sym)
end
end
end
def descendants
@descendants ||= []
end
def included(klass)
descendants << klass if klass.is_a? Class
end
end
class Class
alias_method :new_no_persistence, :new
def is_persistible?
!@campos_default.nil? && !@campos_default.empty?
end
def new(*args)
nueva_instancia = self.new_no_persistence(*args)
if is_persistible?
campos_default_aux={}
attr_information_aux={}
self.ancestors.each{|ancestor| campos_default_aux=ancestor.instance_variable_get(:@campos_default).merge(campos_default_aux) if(!ancestor.instance_variable_get("@campos_default").nil?)}
self.ancestors.each{|ancestor| attr_information_aux=ancestor.instance_variable_get(:@attr_information).merge(attr_information_aux) if(!ancestor.instance_variable_get("@attr_information").nil?)}
@campos_default=campos_default_aux.merge(@campos_default)
@attr_information=attr_information_aux.merge(@attr_information)
@campos_default.each{|key,value| nueva_instancia.persistent_attributes[key]=value }
nueva_instancia.attr_information = @attr_information
nueva_instancia.table = Persistible.table(self)
@campos_default.keys.each do |name|
nueva_instancia.define_singleton_method("#{name}=") {|argument| persistent_attributes["#{name}".to_sym]=argument} #define el setter
nueva_instancia.define_singleton_method(name) {persistent_attributes["#{name}".to_sym]} #define el getter
end
end
nueva_instancia
end
def inherited(klass)
descendants << klass
end
end
class Hash
def map_values(&block)
Hash[self.map {|k, v| [k, block.call(k,v)] }]
end
end
module Boolean
def self.is_persistible?
false
end
end
class TrueClass
include Boolean
end
class FalseClass
include Boolean
end |
module AutoPublishedAt
extend ActiveSupport::Concern
included do
before_validation :set_published_at_to_now,
:if => -> {
self.published? && self.published_at.blank?
}
before_validation :set_published_at_to_nil,
:if => -> {
!self.published? && self.published_at.present?
}
validates :published_at,
:presence => true,
:if => :published?
end
# Set published_at to Time.zone.now
def set_published_at_to_now
self.published_at = Time.zone.now
end
# Set published_at to nil
def set_published_at_to_nil
self.published_at = nil
end
end
|
class CaipinsController < ApplicationController
before_action :set_admincaipin, only: [:show, :edit, :update, :destroy]
def index
@caipins = Caipin.all
@caipinclas = Caipincla.all
end
def show
end
# GET /tests/new
def new
@admincaipin = Caipin.new
end
# GET /tests/1/edit
def edit
end
# POST /tests
# POST /tests.json
def create
@admincaipin = Caipin.new(admincaipin_params)
respond_to do |format|
if @admincaipin.save
format.html { redirect_to admincaipins_path, notice: 'Test was successfully created.' }
format.json { render :show, status: :created, location: @admincaipin }
else
format.html { render :new }
format.json { render json: @admincaipin.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /tests/1
# PATCH/PUT /tests/1.json
def update
respond_to do |format|
if @caipin.update(admincaipins_params)
format.html { redirect_to @admincaipin, notice: 'Test was successfully updated.' }
format.json { render :show, status: :ok, location: @admincaipin }
else
format.html { render :edit }
format.json { render json: @admincaipin.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tests/1
# DELETE /tests/1.json
def destroy
@caipin.destroy
respond_to do |format|
format.html { redirect_to admincaipins_url, notice: 'Admin was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_admincaipin
@admincaipin = Caipin.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def admincaipin_params
params.require(:caipin).permit(:caipincla_id,:name,:summary, :price,:caipinimg)
end
end
|
#
# Cookbook Name:: postgresql
# Provider:: conf
#
# Copyright 2012 Damien DUPORTAL <damien.duportal@gmail.com>
# https://github.com/dduportal/dadou-chef-recipes
#
# This provider implements the postgresql_conf resource
#
# => Inspired by the chef comunity postgresql cookbook : https://github.com/opscode-cookbooks/postgresql
#
action :apply do
service_name = new_resource.service_name
pg_data_dir = new_resource.service_dir.chomp('/')
if new_resource.config and new_resource.config.kind_of?(Hash) and new_resource.config.length > 0 then
template pg_data_dir + "/postgresql.conf" do
source "postgresql.conf.erb"
owner "postgres"
group "postgres"
variables(new_resource.config)
notifies :restart, "postgresql_service[#{service_name}]", :immediately
end
else
log "No "
end
if new_resource.hba_config and new_resource.hba_config.kind_of?(Array) and new_resource.hba_config.length > 0 then
template pg_data_dir + "/pg_hba.conf" do
source "pg_hba.conf.erb"
owner "postgres"
group "postgres"
variables(
:pg_hba => new_resource.hba_config
)
notifies :reload, "postgresql_service[#{service_name}]", :immediately
end
end
end |
class PayGradeRate < ApplicationRecord
belongs_to :pay_grade
before_destroy :is_destroyable
validates_numericality_of :rate, :greater_than =>0
scope :current, -> { where('end_date IS NULL') }
scope :chronological, -> { order('start_date') }
scope :for_date, ->(date) { where("start_date <= ?", date) }
scope :for_pay_grade, -> (pay_grade){where('pay_grade_id == ?', pay_grade.id)}
private
def is_destroyable
throw(:abort)
end
end
|
#!/usr/bin/env ruby
# Here we have another similar code
# Except the customer's age
# is hanlded with a case
puts "Enter the customer's age: "
age = gets.to_i
case
when (age <= 12)
cost = 9
when (age >= 65)
cost = 12
else
cost = 18
end
puts "Ticket cost: " + cost.to_s
|
require 'resolv'
class DomainsController < ApplicationController
def index
domains = Domain.all
if (hostname = params[:hostname])
domains = domains.where hostname: hostname
end
if (ip_address = params[:ip_address])
domains = domains.where ip_address: ip_address
end
if (account_id = params[:account_id])
domains = domains.where account_id: account_id
end
render json: domains, response: 200
end
def show
domain = Domain.find params[:id]
render json: domain, response: 200
end
def create
domain = Domain.new domain_params.merge({ip_address: 'n/a'})
if domain.save
domain.delay.ip_lookup!
head 204, location: domain
else
render json: domain.errors, status: 422
end
end
def update
domain = Domain.find params[:id]
full_params = domain_params
full_params.merge!({ip_address: 'n/a'}) unless domain.hostname == full_params[:hostname]
if domain.update full_params
if full_params[:ip_address] == 'n/a'
domain.delay.ip_lookup!
end
head 204
else
render json: domain.errors, status: 422
end
end
def destroy
domain = Domain.find params[:id]
domain.destroy
head 204
end
private
def domain_params
params.require(:domain).permit :account_id, :hostname
end
end
|
class Report
include ActionView::Helpers::NumberHelper
# Required dependency for ActiveModel::Errors
extend ActiveModel::Naming
extend ActiveModel::Translation
attr_reader :errors
def initialize(params)
@params = params
@errors = ActiveModel::Errors.new(self)
end
def valid?
self.class::VALIDATES_PRESENCE_OF.each{ |validates| errors.add(validates, "must not be blank") if @params[validates].blank? }
self.class::VALIDATES_NUMERICALITY_OF.each{ |validates| errors.add(validates, "must be a number") unless @params[validates].is_a?(Numeric) }
errors.empty?
end
private
def format_date(date)
if date.present?
date.strftime("%m/%d/%Y")
else
''
end
end
def display_cost(cost)
if cost
dollars = (cost / 100.0) rescue nil
dollar, cent = dollars.to_s.split('.')
dollars_formatted = "#{dollar}.#{cent[0..1]}".to_f
number_to_currency(dollars_formatted, seperator: ",", unit: "")
else
"N/A"
end
end
end
|
class Favorite < ActiveRecord::Base
belongs_to :profile
belongs_to :favable, polymorphic: true
belongs_to :favorite_folder
has_many :tidbits, as: :targetable, dependent: :destroy
validates :profile_id, :favable_id, :favable_type, presence: true
validates :favable_id, uniqueness: { scope: [:profile_id, :favable_type] }
before_create :set_favorite_folder
after_create :create_tidbit_for_favable,
:create_tidbit_for_stream_faves
scope :journals, -> { where(favable_type: 'Journal' ) }
scope :streams, -> { where(favable_type: 'Stream') }
scope :submissions, -> { where(favable_type: 'Submission' ) }
scope :no_streams, -> { where.not(favable_type: 'Stream') }
def self.filtered_submissions
joins("INNER JOIN submissions s ON s.id = favorites.favable_id AND favorites.favable_type = 'Submission'")
.joins('LEFT OUTER JOIN filters_submissions fs ON fs.submission_id = s.id')
.where(['fs.filter_id IS NULL AND s.published_at <= ?', Time.now])
end
def self.filtered_journals
joins("INNER JOIN journals j ON j.id = favorites.favable_id AND favorites.favable_type = 'Journal'")
.joins('LEFT OUTER JOIN filters_journals fj ON fj.journal_id = j.id')
.where(['fj.filter_id IS NULL AND j.published_at <= ?', Time.now])
end
private
# Makes sure the favorite_folder_id is populated with the Profile
# default if none is provided.
#
def set_favorite_folder
self.favorite_folder_id = profile.favorite_folder.id if favorite_folder.nil?
end
def create_tidbit_for_favable
if not favable.is_a?(Stream)
favable.profile.tidbits.create(targetable: self)
end
end
def create_tidbit_for_stream_faves
if not favable.is_a?(Stream)
profile.streams.find_by_name('Favorites').favorites.map { |fave|
fave.profile if favable.profile != fave.profile and favable.profile_can_view?(fave.profile)
}.compact.each do |watching_profile|
tidbits.create(profile: watching_profile)
end
end
end
end
|
Rails.application.routes.draw do
resources :home, only: :index
root 'home#index'
get '/auth/:provider/callback', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'
end
|
require_relative 'lib/page_desc'
module Button
extend PageDesc::Action
also_extend PageDesc::Types::Clickable
action :on_click do
puts browser_element[:onclick]
end
end
class More < PageDesc::Section
selector css: '#more-less-button'
before :on_click do
puts 'before CALLED'
end
after :on_click do
puts 'after CALLED'
end
end
class Page < PageDesc::Page
button :more, More
end
class GooglePage < Page
url 'http://google.co.uk'
end
include PageDesc::Browser
browser.visit(GooglePage)
page.more.on_click
page.more.click |
require "test_helper"
require "database/setup"
require "mini_magick"
class ActiveStorage::Previewer::OfficePreviewerTest < ActiveSupport::TestCase
test "previewing a Word document" do
blob = create_file_blob \
filename: "hello.docx",
content_type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
ActiveStorage::Previewer::OfficePreviewer.new(blob).preview do |attachable|
assert_equal "image/png", attachable[:content_type]
assert_equal "hello.png", attachable[:filename]
image = MiniMagick::Image.read(attachable[:io])
assert_operator image.width, :>, 500
assert_operator image.height, :>, 500
assert_equal "image/png", image.mime_type
end
end
test "previewing a PowerPoint presentation" do
blob = create_file_blob \
filename: "hello.pptx",
content_type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
ActiveStorage::Previewer::OfficePreviewer.new(blob).preview do |attachable|
assert_equal "image/png", attachable[:content_type]
assert_equal "hello.png", attachable[:filename]
image = MiniMagick::Image.read(attachable[:io])
assert_operator image.width, :>, 500
assert_operator image.height, :>, 500
assert_equal "image/png", image.mime_type
end
end
test "previewing an Excel spreadsheet" do
blob = create_file_blob \
filename: "hello.xlsx",
content_type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
ActiveStorage::Previewer::OfficePreviewer.new(blob).preview do |attachable|
assert_equal "image/png", attachable[:content_type]
assert_equal "hello.png", attachable[:filename]
image = MiniMagick::Image.read(attachable[:io])
assert_operator image.width, :>, 500
assert_operator image.height, :>, 500
assert_equal "image/png", image.mime_type
end
end
end
|
class CreateWireStories < ActiveRecord::Migration[5.1]
def change
create_table :wire_stories do |t|
t.date :send_date
t.string :content_id
t.string :category_code
t.string :category_name
t.string :region_code
t.string :region_name
t.string :credit
t.string :source
t.string :title
t.text :body
t.references :issue, foreign_key: true
t.timestamps
end
end
end
|
require "rails_helper"
RSpec.describe HomeController do
describe "index" do
it "renders the home page" do
get :index
expect(response).to be_success
end
end
end
|
class AddOneTicketPerPieceToVendorPrinters < ActiveRecord::Migration
def change
add_column :vendor_printers, :one_ticket_per_piece, :boolean
end
end
|
Rails.application.routes.draw do
root 'welcome#index'
resources :articles do
resources :comments#This creates comments as a nested resource within articles.
end
end
|
# frozen_string_literal: true
module Api::V1::SC::Billing::Stripe
class SubscriptionSerializer < Api::V1::BaseSerializer
type 'subscriptions'
attributes :id,
:current_period_start_at,
:current_period_end_at,
:trial_start_at,
:trial_end_at,
:status,
:cancel_at_period_end,
:canceled_at,
:created_at,
:updated_at
belongs_to :user
has_many :plans
has_many :products
end
end
|
class Experience < ApplicationRecord
has_many :tag_experiences
has_many :tags, through: :tag_experiences
has_many :list_items
end
|
require 'active_record'
require 'cxbrank/master/base'
require 'cxbrank/master/music'
module CxbRank
module Master
class Monthly < Base
belongs_to :music
def self.last_modified
return self.maximum(:updated_at)
end
def self.get_csv_columns
return [
{:name => :text_id, :unique => true, :dump => true, :foreign => Music},
{:name => :span_s, :unique => true, :dump => true},
{:name => :span_e, :dump => true},
]
end
end
end
end
|
class User < ActiveRecord::Base
attr_accessible :name
has_many :user_candies
has_many :candies, :through => :user_candies
def primary_candy
Candy.primary_for(self).first
end
end
|
# encoding: utf-8
$: << 'RspecTests/url'
require 'generated/url'
include UrlModule
describe Paths do
before(:all) do
@base_url = ENV['StubServerURI']
dummyToken = 'dummy12321343423'
@credentials = MsRest::TokenCredentials.new(dummyToken)
client = AutoRestUrlTestService.new(@credentials, @base_url)
@paths_client = Paths.new(client)
@array_path = ['ArrayPath1', "begin!*'();:@ &=+$,/?#[]end", nil, '']
end
it 'should create test service' do
expect { AutoRestUrlTestService.new(@credentials, @base_url) }.not_to raise_error
end
it 'should get boolean true' do
result = @paths_client.get_boolean_true_async().value!
expect(result.response.status).to eq(200)
end
it 'should get boolean false ' do
result = @paths_client.get_boolean_false_async().value!
expect(result.response.status).to eq(200)
end
it 'should get int one million' do
result = @paths_client.get_int_one_million_async().value!
expect(result.response.status).to eq(200)
end
it 'should get int negitive one million' do
result = @paths_client.get_int_negative_one_million_async().value!
expect(result.response.status).to eq(200)
end
it 'should get ten billion' do
result = @paths_client.get_ten_billion_async().value!
expect(result.response.status).to eq(200)
end
it 'should get negative ten billion' do
result = @paths_client.get_negative_ten_billion_async().value!
expect(result.response.status).to eq(200)
end
it 'should get float scientific positive' do
result = @paths_client.float_scientific_positive_async().value!
expect(result.response.status).to eq(200)
end
it 'should get float scientific negative' do
result = @paths_client.float_scientific_negative_async().value!
expect(result.response.status).to eq(200)
end
it 'should get double decimal positive' do
result = @paths_client.double_decimal_positive_async().value!
expect(result.response.status).to eq(200)
end
it 'should get double decimal negative' do
result = @paths_client.double_decimal_negative_async().value!
expect(result.response.status).to eq(200)
end
it 'should get string url encoded' do
result = @paths_client.string_url_encoded_async().value!
expect(result.response.status).to eq(200)
end
it 'should get string empty' do
result = @paths_client.string_empty_async().value!
expect(result.response.status).to eq(200)
expect(result.body).to be_nil
end
it 'should get string null' do
expect { @paths_client.string_null_async(nil).value! }.to raise_error(ArgumentError)
end
# it 'should get byte multi byte' do
# result = @paths_client.byte_multi_byte_async("啊齄丂狛狜隣郎隣兀﨩".bytes).value!
# expect(result.response.status).to eq(200)
# expect(result.response.body).to eq("MultiByte")
# end
it 'should get byte empty' do
result = @paths_client.byte_empty_async().value!
expect(result.response.status).to eq(200)
end
it 'should get byte null' do
expect { result = @paths_client.byte_null_async(nil).value! }.to raise_error(ArgumentError)
end
it 'should get date valid' do
result = @paths_client.date_valid_async().value!
expect(result.response.status).to eq(200)
end
# Appropriately disallowed together with CSharp
it 'should get date null' do
pending('Appropriately disallowed together with CSharp')
expect { @paths_client.date_null_async('null').value! }.to raise_error(ArgumentError)
end
it 'should get dateTime valid' do
pending('Appropriately disallowed together with CSharp')
result = @paths_client.date_time_valid(DateTime.new(2012, 1, 1, 1, 1, 1, 'Z')).value!
expect(result.response.status).to eq(200)
expect(result.response.body).to eq("Valid")
end
# Appropriately disallowed together with CSharp
it 'should get dateTime null' do
pending('Appropriately disallowed together with CSharp')
result = @paths_client.date_time_null_async('null').value!
expect(result.response.status).to eq(200)
end
it 'should get array csv in path' do
result = @paths_client.array_csv_in_path_async(@array_path).value!
expect(result.response.status).to eq(200)
end
end |
require 'redcarpet'
require 'pygments.rb'
class LazyDownRender < Redcarpet::Render::XHTML
def doc_header()
github_css = File.join File.dirname(__FILE__), 'github.css'
'<style>' + File.read(github_css) + '</style><article class="markdown-body">'
end
def doc_footer
'</article>'
end
def block_code(code, language)
Pygments.highlight(code, :lexer => language, :options => {:encoding => 'utf-8'})
end
end |
# frozen_string_literal: true
# require_relative 'cargo_train'
# require_relative 'passenger_train'
require_relative 'manufacturer'
require_relative 'instance_counter'
require_relative 'validator'
class Train
include Manufacturer
include InstanceCounter
include Validation
NUM = /^\w{3}-?\w{2}$/i
attr_reader :current_station_index, :wagons, :trains,:speed, :type,:number
validate :number, :format, NUM
validate :number, :presence
@@trains = []
qty_instance
def initialize(number,type)
@number = number
@type = type
@speed = 0
@wagons = []
@current_station_index = 0
@@trains.push(self)
#register_instance
end
def self.all
@@trains
end
def self.find(number = nil)
@@trains.detect { |train| train.number == number }
end
def pick_up_speed(value)
self.speed += value if value >= 0
end
def stop_train
self.speed = 0
end
def add_wagon(wagon)
@wagons.push(wagon) if type == wagon.type && self.speed.zero?
end
def remove_wagon(wagon)
@wagons.delete(wagon) if @wagons.include?(wagon) && self.speed.zero?
end
def take_a_route(route)
@current_route = route
@current_station = route.stations.first
@current_station.add_train(self)
end
def next_station
@current_station = @current_route.stations[@current_station_index += 1]
end
def previos_station
@current_station = @current_route.stations[@current_station_index -= 1] if @current_route.stations.size.positive?
end
def move_forward
@current_station.remove_train(self)
next_station
@current_station.add_train(self)
end
def move_back
@current_station.remove_train(self)
previos_station
@current_station.add_train(self)
end
def block_of_wagons
wagons.collect(&block) if block_given?
end
end
|
class TypeContractsController < ApplicationController
before_action :set_type_contract, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
# GET /type_contracts
# GET /type_contracts.json
def index
@type_contracts = TypeContract.all
end
# GET /type_contracts/1
# GET /type_contracts/1.json
def show
end
# GET /type_contracts/new
def new
@type_contract = TypeContract.new
end
# GET /type_contracts/1/edit
def edit
end
# POST /type_contracts
# POST /type_contracts.json
def create
@type_contract = current_user.type_contract.new(type_contract_params)
respond_to do |format|
if @type_contract.save
format.html { redirect_to @type_contract, notice: 'Type contract was successfully created.' }
format.json { render :show, status: :created, location: @type_contract }
else
format.html { render :new }
format.json { render json: @type_contract.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /type_contracts/1
# PATCH/PUT /type_contracts/1.json
def update
respond_to do |format|
if @type_contract.update(type_contract_params)
format.html { redirect_to @type_contract, notice: 'Type contract was successfully updated.' }
format.json { render :show, status: :ok, location: @type_contract }
else
format.html { render :edit }
format.json { render json: @type_contract.errors, status: :unprocessable_entity }
end
end
end
# DELETE /type_contracts/1
# DELETE /type_contracts/1.json
def destroy
@type_contract.destroy
respond_to do |format|
format.html { redirect_to type_contracts_url, notice: 'Type contract was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_type_contract
@type_contract = TypeContract.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def type_contract_params
params.require(:type_contract).permit(:user_id, :contract_id, :descripcion)
end
end
|
# frozen_string_literal: true
module FileReaderTest
module Read
def test_read_without_internal_encoding
file = file_containing("kākāpō", external_encoding: "UTF-8", internal_encoding: nil)
assert_equal "kākāpō", file.read
end
def test_read_with_internal_encoding
file = file_containing("p\xEEwakawaka", external_encoding: "ISO-8859-13", internal_encoding: "UTF-8")
assert_equal "pīwakawaka", file.read
end
def test_read_with_encoding_options
file = file_containing("hoiho\r\ntawaki\r\n", external_encoding: "UTF-8", internal_encoding: "UTF-8", universal_newline: true)
assert_equal "hoiho\ntawaki\n", file.read
end
def test_read_changes_pos
file = file_containing("kererū")
file.read
assert_equal 7, file.pos
end
def test_read_leaves_file_at_eof
file = file_containing("whio")
file.read
assert file.eof?
end
def test_read_at_eof_returns_empty_string
assert_equal "", file_at_eof.read
end
def test_partial_read
file = file_containing("moa")
assert_equal "mo", file.read(2)
end
def test_partial_read_changes_pos
file = file_containing("korimako")
file.read 2
assert_equal 2, file.pos
file.read 2
assert_equal 4, file.pos
end
def test_partial_read_beyond_eof_returns_shorter_string_than_requested
file = file_containing("tīeke")
file.read 3
assert_equal "eke", file.read(42)
end
def test_partial_read_beyond_eof_sets_pos_to_eof
file = file_containing("hihi")
file.read 42
assert_equal 4, file.pos
end
def test_partial_read_at_eof_returns_empty_string
assert_equal "", file_at_eof.read(9000)
end
def test_partial_read_returns_binary_regardless_of_encoding_options
file = file_containing("tūī", external_encoding: "UTF-8")
assert_equal binary("t\xC5\xAB"), file.read(3)
end
def test_cannot_read_when_closed
assert_raises IOError do
closed_file.read
end
end
end
end
|
class Api::V1::SearchesController < ApplicationController
include SortAndFilterHelper
api :GET, '/v1/searches'
param :order, String, required: false, desc: "provide 'asc' or 'desc' to sort by date"
param :filter, String, required: false, desc: "provide 'alpha-asc' or alpha-desc' to sort alphabetically"
def index
searches = Search.all.order(sorted_by(params)).where('query LIKE ?', "%#{filter_by(params)}%")
results = SearchSerializer.new(searches, include: [:cocktails]).serializable_hash
render json: results, status: 200
end
api :GET, '/v1/searches/:id'
param :id, :number, required: true, desc: 'id of the requested search object'
def show
search = Search.find(params[:id])
result = SearchSerializer.new(search, include: [:cocktails]).serializable_hash
render json: result, status: 200
end
api :DELETE, '/v1/searches/:id'
param :id, :number, required: true, desc: 'id of the search object to be deleted'
def destroy
search = Search.find(params[:id])
search.destroy
render json: "Search has been deleted", status: 200
end
api :POST, '/v1/searches'
param :cocktail, Hash, required: true do
param :query, String, required: true
end
def create
query = cocktail_params[:query]
existing_search = Search.find_by(query: query)
# if search is already in the database we'll just return that
if existing_search
render json: serialize_search(existing_search), status: 200
return
end
cocktail_search = cocktail_service(query)
results = JSON.parse(cocktail_search.response.body)
search = create_search_and_cocktails(query, cocktail_search.url, results)
render json: serialize_search(search), status: 200
end
private
def cocktail_params
params.require(:cocktail).permit(:query)
end
def create_search_and_cocktails(query, url, results)
search = Search.create!(query: query, url: url)
results['drinks'].each do |drink|
search.cocktails.create(recipe: drink)
end
search
end
def cocktail_service(query)
CocktailService.new(query)
end
def serialize_search(search)
SearchSerializer.new(search, include: [:cocktails])
end
end
|
class AddUnreadNotificationToUserProfile < ActiveRecord::Migration[5.0]
def self.up
add_column :user_profiles, :num_unread_notification, :integer
add_column :user_profiles, :unread_notifications, :text
end
def self.down
remove_column :user_profiles, :num_unread_notification, :integer
remove_column :user_profiles, :unread_notifications, :text
end
end
|
FactoryGirl.define do
factory :bs_elawa_segment, class: 'Bs::Elawa::Segment' do
name "MyString"
start_date "2016-04-18 01:30:41"
end_date "2016-04-18 01:30:41"
event_id 1
end
end
|
module Types
class QueryType < Types::BaseObject
# Add root-level fields here.
# They will be entry points for queries on your schema.
field :all_users, [UserType], null: true
field :me, UserType, null: true
field :all_venues, [VenueType], null:true do
argument :id, Integer, required: false
argument :city, String, required: false
end
field :all_events, [EventType], null: true do
argument :venue_id, Integer, required: false
end
field :all_venue_admins, [VenueAdminType], null:true do
argument :user_id, Integer, required: false
argument :venue_id, Integer, required: false
end
field :attendance, [UserEventType], null:true do
argument :user_id, Integer, required: false
argument :event_id, Integer, required: false
end
field :past_events, [EventType], null: true do
argument :venue_id, Integer, required: true
end
field :future_events, [EventType], null: true do
argument :venue_id, Integer, required: true
end
def me
context[:current_user]
end
def all_users
User.all
end
def all_venues(city: nil, id: nil)
if city
Venue.joins(:addresses).where(addresses: {city: city.downcase})
elsif id
Venue.where(id: id)
else
Venue.all
end
end
def all_venue_admins(user_id: nil, venue_id: nil)
if user_id && venue_id
VenueAdmin.where(user_id: user_id, venue_id: venue_id)
elsif user_id
VenueAdmin.where(user_id: user_id)
elsif venue_id
VenueAdmin.where(venue_id: venue_id)
else
VenueAdmin.all
end
end
def all_events(venue_id: nil)
if venue_id
Event.where(venue_id: venue_id)
else
Event.all
end
end
def attendance(user_id: nil, event_id: nil)
if user_id && event_id
UserEvent.where(user_id: user_id, event_id: event_id)
elsif user_id
UserEvent.where(user_id: user_id)
elsif event_id
UserEvent.where(event_id: event_id)
else
UserEvent.all
end
end
def past_events(venue_id: nil)
time = Time.now.to_formatted_s(:db)
Event.where(venue_id: venue_id).where("start_time < ?", time).order(start_time: :desc).limit(3)
end
def future_events(venue_id: nil)
time = Time.now.to_formatted_s(:db)
Event.where(venue_id: venue_id).where("start_time > ?", time).order(start_time: :asc)
end
end
end
|
# frozen_string_literal: true
# Advent of Code 2020
#
# Robert Haines
#
# Public Domain
require 'test_helper'
require 'aoc2020/ticket_translation'
class AOC2020::TicketTranslationTest < MiniTest::Test
INPUT = <<~EOINPUT
class: 1-3 or 5-7
row: 6-11 or 33-44
seat: 13-40 or 45-50
your ticket:
7,1,14
nearby tickets:
7,3,47
40,4,50
55,2,20
38,6,12
EOINPUT
INPUT2 = <<~EOINPUT2
class: 0-1 or 4-19
row: 0-5 or 8-19
seat: 0-13 or 16-19
your ticket:
11,12,13
nearby tickets:
3,9,18
15,1,5
5,14,9
EOINPUT2
PARSED = [
{
class: [1, 2, 3, 5, 6, 7],
row: [6, 7, 8, 9, 10, 11, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44],
seat: [
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 47, 48, 49, 50
]
},
[7, 1, 14],
[
[7, 3, 47],
[40, 4, 50],
[55, 2, 20],
[38, 6, 12]
]
].freeze
def setup
@tt = AOC2020::TicketTranslation.new
end
def test_parse_field
assert_equal(
[:class, [1, 2, 3, 5, 6, 7]], @tt.parse_field('class: 1-3 or 5-7')
)
assert_equal(
[:your_seat, [13, 14, 20, 21]],
@tt.parse_field('your seat: 13-14 or 20-21')
)
end
def test_parse_input
assert_equal(PARSED, @tt.parse_input(INPUT))
end
def test_error_rate
fields, _, tickets = @tt.parse_input(INPUT)
field_values = fields.values.flatten
assert_equal(71, @tt.error_rate(tickets, field_values))
end
def test_valid_tickets
fields, _, tickets = @tt.parse_input(INPUT)
field_values = fields.values.flatten
assert_equal([[7, 3, 47]], @tt.valid_tickets(tickets, field_values))
end
def test_matching_fields_for_values
fields, _, tickets = @tt.parse_input(INPUT2)
field_values = tickets.transpose
assert_equal(
[:row], @tt.matching_fields_for_values(field_values[0], fields)
)
fields.delete(:row)
assert_equal(
[:class], @tt.matching_fields_for_values(field_values[1], fields)
)
fields.delete(:class)
assert_equal(
[:seat], @tt.matching_fields_for_values(field_values[2], fields)
)
end
def test_id_fields
fields, _, tickets = @tt.parse_input(INPUT2)
assert_equal(
{ row: 0, class: 1, seat: 2 }, @tt.id_fields(tickets, fields)
)
end
end
|
require 'rails_helper'
describe User do
it { should have_many(:characters) }
end
|
# frozen_string_literal: true
module Decidim
module Opinions
module Admin
# A form object to be used when admin users wants to merge two or more
# opinions into a new one to another opinion component in the same space.
class OpinionsMergeForm < OpinionsForkForm
validates :opinions, length: { minimum: 2 }
end
end
end
end
|
class UsersController < ApplicationController
before_filter :require_staff, except: [ :create, :login, :logout ]
def create
user = User.create(
first_name: params[:first_name],
last_name: params[:last_name],
email: params[:email]
)
if user
render text: "Thanks #{user.first_name}! We're looking forward to seeing you out at our next trial event!!!"
else
render json: user.errors.full_messages.to_json, status: 406
end
end
def index
render json: User.all.to_json
end
def login
user =
User.find_by_id(session[:user_id]) ||
User.find_by_email(params[:email]).try(:authenticate, params[:password])
if user
session[:user_id] ||= user.id
user.update(last_login: Time.now) if (Time.now.to_i - user.last_login.to_i) > 1.hour
render json: user.to_json
else
render json: nil
end
end
def logout
session.delete(:user_id)
render json: nil
end
def update
user = User.find(params[:id])
if user.update_attributes(params.require(:user).permit(:valid_email))
render json: user.to_json
else
render json: user.errors.full_messages.to_json, status: 406
end
end
def destroy
User.find(params[:id]).destroy
render json: nil
end
end |
class CreateRecordsTable < ActiveRecord::Migration[6.0]
def change
create_table :records do |t|
t.integer :character_id
t.integer :item_id
t.boolean :item_used?
t.integer :escape_id
end
end
end
|
template "/etc/default/varnish" do
mode '0755'
owner 'root'
# group deploy[:group]
source "varnish.erb"
# variables(:deploy => deploy, :application => application)
end
# service "varnish" do
# action :restart
# end
|
class CreateMaps < ActiveRecord::Migration[6.0]
def change
create_table :maps do |t|
t.string :name
t.string :type
t.integer :price
t.string :closing_day
t.time :open_time
t.text :website
t.text :photo1
t.text :photo2
t.text :photo3
t.boolean :beji
t.integer :tel
t.boolean :parking
t.text :address
t.timestamps
end
end
end
|
require('spec_helper')
describe('path through the stores pages', {:type => :feature}) do
it('shows message when no stores are in database') do
visit('/')
click_link('Stores')
expect(page).to have_content("There are no stores in the database. Add a store now.")
end
it('allows user to add a store to database and lists it') do
visit('/')
click_link('Stores')
fill_in('store_name', :with => 'Portland Ped')
click_button('Add Store')
expect(page).to have_content("Portland Ped")
end
it('allows the user to update the name of a store in the database') do
visit('/')
click_link('Stores')
fill_in('store_name', :with => 'Portland Ped')
click_button('Add Store')
click_link('Portland Ped')
save_and_open_page
fill_in('new_store_name', :with => 'portland zapateria')
click_button('Update Store')
expect(page).to have_content('Portland Zapateria')
end
it('allows the user to delete a store from the database') do
visit('/')
click_link('Stores')
fill_in('store_name', :with => 'Portland Ped')
click_button('Add Store')
click_link('Portland Ped')
click_button('Delete Store')
expect(page).to have_no_content('Portland Ped')
end
it('allows the user to add shoe brands to a store that sells them') do
Brand.create({:name => 'Siddartha Sandels'})
visit('/')
click_link('Stores')
fill_in('store_name', :with => 'Portland Ped')
click_button('Add Store')
click_link('Portland Ped')
select('Siddartha Sandels', :from => 'brand_select')
click_button('Add Brand')
expect(page).to have_content('Siddartha Sandels')
end
it('allows the user to remove a shoe brand from a store') do
Brand.create({:name => 'Siddartha Sandels'})
visit('/')
click_link('Stores')
fill_in('store_name', :with => 'Portland Ped')
click_button('Add Store')
click_link('Portland Ped')
select('Siddartha Sandels', :from => 'brand_select')
click_button('Add Brand')
select('Siddartha Sandels', :from => 'brand_remove')
click_button('Remove Brand')
expect(page).to have_content("No brands entered for this store currently")
end
end
|
require 'rails_helper'
RSpec.describe Cognito::SignInUser do
describe '#call' do
let(:email) { 'user@email.com' }
let(:password) { 'ValidPass123!' }
let(:challenge_name) { 'Challenge name' }
let(:session) { 'Session' }
let(:user_id_for_srp) { 'User id' }
let(:cookies_disabled) { false }
let(:aws_client) { instance_double(Aws::CognitoIdentityProvider::Client) }
context 'when success' do
let(:response) { described_class.call(email, password, cookies_disabled) }
before do
allow(Aws::CognitoIdentityProvider::Client).to receive(:new).and_return(aws_client)
allow(aws_client).to receive(:initiate_auth).and_return(OpenStruct.new(challenge_name: challenge_name, session: session, challenge_parameters: { 'USER_ID_FOR_SRP' => user_id_for_srp }))
end
it 'returns success' do
expect(response.success?).to eq true
end
it 'returns no error' do
expect(response.error).to eq nil
end
it 'returns challenge name' do
expect(response.challenge_name).to eq challenge_name
end
it 'returns challenge?' do
expect(response.challenge?).to eq true
end
it 'returns session' do
expect(response.session).to eq session
end
end
context 'when cognito error' do
before do
allow(Aws::CognitoIdentityProvider::Client).to receive(:new).and_return(aws_client)
allow(aws_client).to receive(:initiate_auth).and_raise(Aws::CognitoIdentityProvider::Errors::ServiceError.new('oops', 'Oops'))
end
it 'does not return success' do
response = described_class.call(email, password, cookies_disabled)
expect(response.success?).to eq false
end
it 'does returns cognito error' do
response = described_class.call(email, password, cookies_disabled)
expect(response.error).to eq I18n.t('facilities_management.users.sign_in_error')
end
end
context 'when user not confirmed' do
before do
allow(Aws::CognitoIdentityProvider::Client).to receive(:new).and_return(aws_client)
allow(aws_client).to receive(:initiate_auth).and_raise(Aws::CognitoIdentityProvider::Errors::UserNotConfirmedException.new('oops', 'Oops'))
end
it 'does not return success' do
response = described_class.call(email, password, cookies_disabled)
expect(response.success?).to eq false
end
it 'does returns cognito error' do
response = described_class.call(email, password, cookies_disabled)
expect(response.error).to eq 'Oops'
end
it 'returns needs_confirmation true' do
response = described_class.call(email, password, cookies_disabled)
expect(response.needs_confirmation).to eq true
end
end
context 'when password reset required' do
before do
allow(Aws::CognitoIdentityProvider::Client).to receive(:new).and_return(aws_client)
allow(aws_client).to receive(:initiate_auth).and_raise(Aws::CognitoIdentityProvider::Errors::PasswordResetRequiredException.new('oops', 'Oops'))
end
it 'does not return success' do
response = described_class.call(email, password, cookies_disabled)
expect(response.success?).to eq false
end
it 'does returns cognito error' do
response = described_class.call(email, password, cookies_disabled)
expect(response.error).to eq 'Oops'
end
it 'returns need_password_reset true' do
response = described_class.call(email, password, cookies_disabled)
expect(response.needs_password_reset).to eq true
end
end
context 'when Cogito error is UserNotFoundException' do
before do
allow(Aws::CognitoIdentityProvider::Client).to receive(:new).and_return(aws_client)
allow(aws_client).to receive(:initiate_auth).and_raise(Aws::CognitoIdentityProvider::Errors::UserNotFoundException.new('oops', 'Oops'))
end
it 'does not return success' do
response = described_class.call(email, password, cookies_disabled)
expect(response.success?).to eq false
end
it 'does returns cognito error' do
response = described_class.call(email, password, cookies_disabled)
expect(response.error).to eq I18n.t('facilities_management.users.sign_in_error')
end
it 'returns need_password_reset false' do
response = described_class.call(email, password, cookies_disabled)
expect(response.needs_password_reset).to eq false
end
end
context 'when cookies are disabled' do
let(:cookies_disabled) { true }
before do
allow(Aws::CognitoIdentityProvider::Client).to receive(:new).and_return(aws_client)
allow(aws_client).to receive(:initiate_auth).and_return(OpenStruct.new(challenge_name: challenge_name, session: session, challenge_parameters: { 'USER_ID_FOR_SRP' => user_id_for_srp }))
end
it 'does not return success' do
response = described_class.call(email, password, cookies_disabled)
expect(response.success?).to eq false
end
it 'does returns cognito error' do
response = described_class.call(email, password, cookies_disabled)
expect(response.errors.any?).to eq true
end
end
end
end
|
class AddEnvironmentToServers < ActiveRecord::Migration
def change
add_column :servers, :environment_id, :int
end
end
|
json.array!(@vehicles) do |vehicle|
json.extract! vehicle, :id, :marca, :modelo, :ano, :color, :npass, :tipo, :driver_id
json.url vehicle_url(vehicle, format: :json)
end
|
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, :only => [:create]
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:enrollment_number, :full_name ,:contact_number , :branch, :semester ,:password_confirmation, :email, :password) }
end
protect_from_forgery with: :exception
end
|
require 'gosu'
require_relative 'level'
require_relative 'player'
class Game
LEVEL1 = [
"+------------------+",
"|S.|....T..........|",
"|..|.--------..|++.|",
"|..|.|....|T|..|T..|",
"|.+|.|.E|.|....|...|",
"|..|.|---.|.|--|...|",
"|..|.|....|.|......|",
"|+.|.|......|..|-|.|",
"|..|.|-----.|..|+|.|",
"|..|........|..|+|.|",
"|..|T.......|..|+|.|",
"|.++--------+..|+|.|",
"|.+....+++.....|+|.|",
"|---------------+..|",
"|T+|......|.....|.||",
"|..|..|......+T.|.||",
"|+...+|---------+..|",
"|..|.............+.|",
"|T+|..++++++++++...|",
"+------------------+"
]
def initialize(window)
@window = window
@player = Player.new(@window, 0, 0)
@level = Level.new(@window, @player, LEVEL1)
@font = Gosu::Font.new(32)
@time_start = Time.now.to_i
end
def button_down(id)
@level.button_down(id)
end
def update
@level.update
if !@level.level_over?
@time_now = Time.now.to_i
end
end
def time_in_seconds
@time_now - @time_start
end
def draw_hud
if @level.level_over?
@font.draw("GAME OVER!", 170, 150, 10, 2, 2)
@font.draw("Collected #{@player.score} treasure in #{time_in_seconds}", 110, 300, 10)
else
@font.draw_markup("Time: #{time_in_seconds}", 4, 2, 10)
@font.draw_text("Score: #{@player.score}", 510, 2, 10)
end
end
def draw
@level.draw
draw_hud
end
end
|
class FirstAssociatesReport < ActiveRecord::Base
belongs_to :admin
has_many :first_associates_transactions
end
|
class AddColumnsForEquipmentToExercise < ActiveRecord::Migration[5.2]
def change
add_column :exercises, :common_exercise_id, :integer, null: false
add_column :exercises, :common_equipment_id, :integer, null: false
end
end
|
class QuotationPolicy < ApplicationPolicy
class Scope < Scope
def resolve_for_commissioner
if user.present?
scope.where("quotations.commissioner_id = ? OR quotations.public_for_commissioner = ?", user.id, true)
else
scope.where("quotations.public_for_commissioner = ?", true)
end
end
def resolve_for_artist
if user.present?
scope.where("(quotations.artist_id = ? OR quotations.public_for_artist = ?) AND quotations.state != 'draft'", user.id, true)
else
scope.where("quotations.public_for_artist = ? AND quotations.state != 'draft'", true)
end
end
end
def permitted_attributes
[
:proposal_id,
:description,
:tos_accepted,
:commissioner_id,
:artist_id,
{ quotation_assets_attributes: [:asset_id, :id, :_destroy], character_ids: [] }
]
end
def index?
true
end
def new?
user_is_commissioner? && proposal_is_valid? && artist_is_valid?
end
def create?
new?
end
def show?
user_is_commissioner? || (user_is_artist? && !record.draft?)
end
def edit?
user_is_commissioner? && record.draft? && artist_is_valid?
end
def update?
edit?
end
def destroy?
edit?
end
def accept?
user_is_artist?
end
def cancel_approval?
user_is_artist? && record.state.in?(['refused', 'waiting_payment'])
end
def paid?
user_is_artist?
end
def refuse?
user_is_artist?
end
def finish?
user_is_artist?
end
def rate_commissioner?
record.done? && user_is_artist?
end
def rate_artist?
record.done? && user_is_commissioner?
end
def publish_for_artist?
user_is_artist?
end
def unpublish_for_artist?
publish_for_artist?
end
def publish_for_commissioner?
user_is_commissioner?
end
def unpublish_for_commissioner?
publish_for_commissioner?
end
protected
def user_is_commissioner?
record.commissioner == user
end
def user_is_artist?
record.artist == user
end
def proposal_is_valid?
!record.proposal || record.proposal.visible
end
def artist_is_valid?
if record.proposal.present?
record.proposal.artist == record.artist && record.artist != user
else
record.artist != user
end
end
end
|
require 'rails_helper'
RSpec.describe "/shelters", type: :feature do
it "allows user to see all shelter names" do
shelter1 = Shelter.create(name: 'FuzzTime',
address: "895 Fuzz St.",
city: "Westminster",
state: "CO",
zip: "80021"
)
shelter2 = Shelter.create(name: 'DogPaws',
address: "123 Pup St.",
city: "Arvada",
state: "CO",
zip: "80005"
)
visit "/shelters"
expect(page).to have_content(shelter1.name)
expect(page).to have_content(shelter2.name)
end
it "allows user to see all shelters sorted alphabetically" do
shelter1 = Shelter.create(name: 'FuzzTime',
address: "895 Fuzz St.",
city: "Westminster",
state: "CO",
zip: "80021"
)
shelter2 = Shelter.create(name: 'DogPaws',
address: "123 Pup St.",
city: "Arvada",
state: "CO",
zip: "80005"
)
visit "/shelters"
shelter1.name.should appear_before(shelter2.name)
click_link "Sort Shelters (Alphabetical)"
expect(current_path).to eq("/shelters/sorted")
shelter2.name.should appear_before(shelter1.name)
expect(page).to have_content(shelter1.name)
expect(page).to have_content(shelter2.name)
end
end
# page.body.index(shelter2.name).should < page.body.index(shelter1.name) ordered assertion without the 'orderly' gem
|
#
# hermeneutics/mail.rb -- A mail
#
require "hermeneutics/message"
module Hermeneutics
class Mail < Message
# :stopdoc:
class FromReader
class <<self
def open file
i = new file
yield i
end
private :new
end
attr_reader :from
def initialize file
@file = file
@file.eat_lines { |l|
l =~ /^From .*/ rescue nil
if $& then
@from = l
@from.chomp!
else
@first = l
end
break
}
end
def eat_lines &block
if @first then
yield @first
@first = nil
end
@file.eat_lines &block
end
end
# :startdoc:
class <<self
def parse input
FromReader.open input do |fr|
parse_hb fr do |h,b|
new fr.from, h, b
end
end
end
def create
new nil, nil, nil
end
end
def initialize from, headers, body
super headers, body
@from = from
end
# String representation with "From " line.
# Mails reside in mbox files etc. and so have to end in a newline.
def to_s
set_unix_from
r = ""
r << @from << $/ << super
r.ends_with? $/ or r << $/
r
end
def receivers
addresses_of :to, :cc, :bcc
end
private
def addresses_of *args
l = args.map { |f| @headers.field f }
AddrList.new *l
end
def set_unix_from
return if @from
# Common MTA's will issue a proper "From" line; some MDA's
# won't. Then, build it using the "From:" header.
addr = nil
l = addresses_of :from, :return_path
# Prefer the non-local version if present.
l.each { |a|
if not addr or addr !~ /@/ then
addr = a
end
}
addr or raise ArgumentError, "No From: field present."
@from = "From #{addr.plain} #{Time.now.gmtime.asctime}"
end
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure('2') do |config|
config.vm.box = 'precise32'
config.vm.box_url = 'http://boxes.cogini.com/precise32.box'
config.vm.network :forwarded_port, guest: 80, host: 9020
config.vm.network :forwarded_port, guest: 22, host: 9021, id: "ssh", auto_correct: true
# apt wants the partial folder to be there
apt_cache = './.cache/apt'
FileUtils.mkpath "#{apt_cache}/partial"
chef_cache = '/var/chef/cache'
shared_folders = {
apt_cache => '/var/cache/apt/archives',
'./.cache/chef' => chef_cache,
}
config.vm.provider :virtualbox do |vb|
#vb.gui = true
shared_folders.each do |source, destination|
FileUtils.mkpath source
config.vm.synced_folder source, destination
vb.customize ['setextradata', :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/#{destination}", '1']
end
vb.customize ['setextradata', :id, 'VBoxInternal2/SharedFoldersEnableSymlinksCreate/v-root', '1']
end
config.vm.provision :chef_solo do |chef|
chef.provisioning_path = chef_cache
chef.cookbooks_path = [
'chef/chef-cookbooks',
'chef/site-cookbooks',
]
chef.json = {
:portfolio => {
:server_name => 'localhost',
:log_dir => '/vagrant/logs',
:site_dir => '/vagrant',
:admin_email => 'support@vagrant.local',
:db => {
:password => 'vagrant',
},
:app_user => 'vagrant',
},
# Attributes for vagrant machine
:apache => {
:user => 'vagrant',
},
:php => {
:fpm => {
:user => 'vagrant',
},
},
:nginx => {
:sendfile => 'off',
},
:mysql => {
:server_root_password => 'vagrant',
},
:postgresql => {
:client_auth => [
{
:type => 'local',
:database => 'all',
:user => 'all',
:auth_method => 'trust',
}
]
}
}
chef.add_recipe 'vagrant'
#chef.data_bags_path = '../my-recipes/data_bags'
end
end
|
class ReorderPythonImports < Formula
include Language::Python::Virtualenv
desc "Rewrites source to reorder python imports"
homepage "https://github.com/asottile/reorder_python_imports"
url "https://github.com/asottile/reorder_python_imports/archive/v2.3.6.tar.gz"
sha256 "33df7db05db1557c743ddb3fe24cbf2d5d29bb56c3e42cb41383a242c8a213db"
license "MIT"
bottle do
cellar :any_skip_relocation
sha256 "8a46ea15899ccd66b9ce3778f8a655e42317c6e656e5f9d9c781c8078c1c2769" => :catalina
sha256 "688e50c273fc03cc99b0ed5670dd7b21bfbc49c6a67e401ea87f8efb6342b0b4" => :mojave
sha256 "eaba68481ccf5c4272ef4b29e46aea5e14875c767d1fb951004c5070dd534f8f" => :high_sierra
end
depends_on "python@3.9"
resource "aspy.refactor-imports" do
url "https://files.pythonhosted.org/packages/34/6e/37cbfba703b06fca29c38079bef76cc01e8496197701fff8f0dded3b5b38/aspy.refactor_imports-2.1.1.tar.gz"
sha256 "eec8d1a73bedf64ffb8b589ad919a030c1fb14acf7d1ce0ab192f6eedae895c5"
end
resource "cached-property" do
url "https://files.pythonhosted.org/packages/61/2c/d21c1c23c2895c091fa7a91a54b6872098fea913526932d21902088a7c41/cached-property-1.5.2.tar.gz"
sha256 "9fa5755838eecbb2d234c3aa390bd80fbd3ac6b6869109bfc1b499f7bd89a130"
end
def install
virtualenv_install_with_resources
end
test do
(testpath/"test.py").write <<~EOS
from os import path
import sys
EOS
system "#{bin}/reorder-python-imports", "--exit-zero-even-if-changed", "#{testpath}/test.py"
assert_equal("import sys\nfrom os import path\n", File.read(testpath/"test.py"))
end
end
|
class CreateRemixes < ActiveRecord::Migration
def change
create_table :remixes do |t|
t.string :name
t.string :download_url
t.references :circle
t.references :stem
t.references :remixer
t.timestamps
end
end
end
|
require 'rails_helper'
RSpec.describe "EmailProcessor", :type => :request do
describe "with a valid email posted to EmailProcessor" do
let(:email) { fake_sendgrid_params("This is a test") }
describe "when there is a matching user in the database" do
let!(:user) { FactoryGirl.create(:user, mtname:'griddles') }
it "creates a new Letter" do
expect { page.driver.post(email_processor_path, email) }.to change(Letter, :count)
end
describe "when there is no matching sender in the database" do
it "creates a new Sender" do
expect(Sender.all.count).to be 0
expect { page.driver.post(email_processor_path, email) }.to change(Sender, :count)
end
specify "the sender's display name is properly computed" do
page.driver.post(email_processor_path, email)
sender = Sender.all.first
expect(sender.display_name).to eq('Smith')
end
end
describe "when there is a matching sender in the database already" do
let!(:sender) { Sender.create(name:'smith.com') }
it "does not create a new Sender" do
expect(Sender.all.count).to be 1
expect { page.driver.post(email_processor_path, email) }.not_to change(Sender, :count)
end
end
end
describe "when there is no matching user in the database" do
it "does not create a new Letter" do
expect(User.all.count).to be 0
expect { page.driver.post(email_processor_path, email) }.not_to change(Letter, :count)
end
it "does not create a new Sender" do
expect(Sender.all.count).to be 0
expect { page.driver.post(email_processor_path, email) }.not_to change(Sender, :count)
end
end
end
describe "with a valid email from Gilt and valid matching user" do
let!(:user) { FactoryGirl.create(:user, mtname:'griddles') }
let(:email) { fake_gilt_email_params }
specify "the sender's display name is properly computed" do
page.driver.post(email_processor_path, email)
sender = Sender.all.first
expect(sender.display_name).to eq('Gilt')
end
end
def fake_gilt_email_params
{
to: 'Mr. Griddles <griddles@example.com>',
from: 'Bob Smith <emailtoyou@g.gilt.com>',
text: 'hello',
}
end
def fake_sendgrid_params(message)
{
to: 'Mr. Griddles <griddles@example.com>',
from: 'Bob Smith <bob@smith.com>',
text: message,
}
end
end
|
class TripsController < ApplicationController
before_action :logged_in_admin, only: :new
before_action :admin_user, only: [:create, :destroy]
def index
@trips = Trip.paginate(page: params[:page])
end
def show
@trip = Trip.find(params[:id])
end
def new
@trip = Trip.new
end
def create
@trip = Trip.new(trip_params)
if @trip.save
flash[:success] = "Trip created!"
redirect_to @trip
else
render 'new'
end
end
def edit
@trip = Trip.find(params[:id])
end
def update
@trip = Trip.find(params[:id])
if @trip.update_attributes(trip_params)
flash[:success] = "Trip updated"
redirect_to @trip
else
render 'edit'
end
end
def destroy
Trip.find(params[:id]).destroy
flash[:success] = "Trip deleted"
redirect_to trips_url
end
private
#only allow these params. prevents giving URL queries that could mess with app.
def trip_params
params.require(:trip).permit(:name, :start_date, :end_date, :location)
end
def admin_user
redirect_to(root_url) unless current_participant.admin?
end
def logged_in_admin
unless logged_in?
store_location
flash[:danger] = "Please log in."
redirect_to login_url
end
end
end
|
# frozen_string_literal: true
require "rails_helper"
RSpec.describe HomeworksController, type: :routing do
before do
user = FactoryBot.create(:user)
sign_in user
end
describe "routing" do
it "routes to #edit" do
expect(get: "/subjects/1/courses/1/homeworks/1/edit").to route_to("homeworks#edit", id: "1", course_id: "1",
subject_id: "1")
end
it "routes to #create" do
expect(post: "/subjects/1/courses/1/homeworks").to route_to("homeworks#create", course_id: "1", subject_id: "1")
end
it "routes to #update via PUT" do
expect(put: "/subjects/1/courses/1/homeworks/1").to route_to("homeworks#update", id: "1", course_id: "1",
subject_id: "1")
end
it "routes to #update via PATCH" do
expect(patch: "/subjects/1/courses/1/homeworks/1").to route_to("homeworks#update", id: "1", course_id: "1",
subject_id: "1")
end
it "routes to #destroy" do
expect(delete: "/subjects/1/courses/1/homeworks/1").to route_to("homeworks#destroy", id: "1", course_id: "1",
subject_id: "1")
end
end
end
|
require "rails_helper"
RSpec.describe Queries::ContestantType do
subject { Queries::ContestantType }
context "fields" do
let(:fields) { %w(id model_id first_name last_name residence description points pool eliminated scores) }
it "has the proper fields" do
expect(subject.fields.keys).to match_array fields
end
describe "model_id" do
subject { Queries::ContestantType.fields["model_id"] }
let(:contestant) { create(:contestant) }
it "is the database id of the object" do
expect(subject.resolve(contestant, nil, nil)).to eq contestant.id
end
end
end
end
|
class Role
include DataMapper::Resource
property :id, Serial
property :instrument, String
property :player, String
def fill(person)
return if person.empty?
self.player = person
self.save
end
def found
'found' if self.player
end
def to_hash
Hash[self.instrument, self.player]
end
end
|
require 'test/test_helper'
require 'flog'
describe 'flog command' do
before :each do
@flog = stub('Flog',
:flog_files => true,
:report => true,
:exit => nil,
:puts => nil)
# Flog.stubs(:new).returns(@flog)
end
def run_command
# HACK eval File.read(File.join(File.dirname(__FILE__), *%w[.. bin flog]))
end
describe 'when no command-line arguments are specified' do
before :each do
ARGV.clear
end
it 'should run' do
lambda { run_command }.wont_raise_error(Errno::ENOENT)
end
it 'should not alter the include path' do
@paths = $:.dup
run_command
$:.must_equal @paths
end
# it 'should create a Flog instance' do
# Flog.expects(:new).returns(@flog)
# run_command
# end
#
# it 'should not have any options flags set' do
# Flog.expects(:new).with({}).returns(@flog)
# run_command
# end
it 'should call flog_files on the Flog instance' do
@flog.expects(:flog_files)
run_command
end
it "should pass '-' (for the file path) to flog_files on the instance" do
@flog.expects(:flog_files).with(['-'])
run_command
end
it 'should call report on the Flog instance' do
@flog.expects(:report)
run_command
end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
describe "when -a is specified on the command-line" do
before :each do
ARGV.replace ['-a']
end
# it 'should create a Flog instance' do
# Flog.expects(:new).returns(@flog)
# run_command
# end
#
# it "should set the option to show all methods" do
# Flog.expects(:new).with(:all => true).returns(@flog)
# run_command
# end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
describe "when --all is specified on the command-line" do
before :each do
ARGV.replace ['--all']
end
# it 'should create a Flog instance' do
# Flog.expects(:new).returns(@flog)
# run_command
# end
#
# it "should set the option to show all methods" do
# Flog.expects(:new).with(:all => true).returns(@flog)
# run_command
# end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
describe "when -s is specified on the command-line" do
before :each do
ARGV.replace ['-s']
end
# it 'should create a Flog instance' do
# Flog.expects(:new).returns(@flog)
# run_command
# end
#
# it "should set the option to show only the score" do
# Flog.expects(:new).with(:score => true).returns(@flog)
# run_command
# end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
describe "when --score is specified on the command-line" do
before :each do
ARGV.replace ['--score']
end
# it 'should create a Flog instance' do
# Flog.expects(:new).returns(@flog)
# run_command
# end
#
# it "should set the option to show only the score" do
# Flog.expects(:new).with(:score => true).returns(@flog)
# run_command
# end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
describe "when -m is specified on the command-line" do
before :each do
ARGV.replace ['-m']
end
# it 'should create a Flog instance' do
# Flog.expects(:new).returns(@flog)
# run_command
# end
#
# it "should set the option to report on methods only" do
# Flog.expects(:new).with(:methods => true).returns(@flog)
# run_command
# end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
describe "when --methods-only is specified on the command-line" do
before :each do
ARGV.replace ['--methods-only']
end
# it 'should create a Flog instance' do
# Flog.expects(:new).returns(@flog)
# run_command
# end
#
# it "should set the option to report on methods only" do
# Flog.expects(:new).with(:methods => true).returns(@flog)
# run_command
# end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
describe "when -v is specified on the command-line" do
before :each do
ARGV.replace ['-v']
end
# it 'should create a Flog instance' do
# Flog.expects(:new).returns(@flog)
# run_command
# end
#
# it "should set the option to be verbose" do
# Flog.expects(:new).with(:verbose => true).returns(@flog)
# run_command
# end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
describe "when --verbose is specified on the command-line" do
before :each do
ARGV.replace ['--verbose']
end
# HACK
# it 'should create a Flog instance' do
# Flog.expects(:new).returns(@flog)
# run_command
# end
# HACK
# it "should set the option to be verbose" do
# Flog.expects(:new).with(:verbose => true).returns(@flog)
# run_command
# end
# HACK
# it 'should exit with status 0' do
# self.expects(:exit).with(0)
# run_command
# end
end
describe "when -h is specified on the command-line" do
before :each do
ARGV.replace ['-h']
end
it "should display help information" do
self.expects(:puts)
run_command
end
# HACK: useless anyhow
# it 'should not create a Flog instance' do
# Flog.expects(:new).never
# run_command
# end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
describe "when --help is specified on the command-line" do
before :each do
ARGV.replace ['--help']
end
it "should display help information" do
self.expects(:puts)
run_command
end
# HACK: useless anyhow
# it 'should not create a Flog instance' do
# Flog.expects(:new).never
# run_command
# end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
describe 'when -I is specified on the command-line' do
before :each do
ARGV.replace ['-I /tmp,/etc']
@paths = $:.dup
end
# HACK - very little value to begin with
# it "should append each ':' separated path to $:" do
# run_command
# $:.wont_equal @paths
# end
# it 'should create a Flog instance' do
# Flog.expects(:new).returns(@flog)
# run_command
# end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
describe 'when -b is specified on the command-line' do
before :each do
ARGV.replace ['-b']
end
# it 'should create a Flog instance' do
# Flog.expects(:new).returns(@flog)
# run_command
# end
#
# it "should set the option to provide 'blame' information" do
# Flog.expects(:new).with(:blame => true).returns(@flog)
# run_command
# end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
describe 'when --blame is specified on the command-line' do
before :each do
ARGV.replace ['--blame']
end
# it 'should create a Flog instance' do
# Flog.expects(:new).returns(@flog)
# run_command
# end
#
# it "should set the option to provide 'blame' information" do
# Flog.expects(:new).with(:blame => true).returns(@flog)
# run_command
# end
it 'should exit with status 0' do
self.expects(:exit).with(0)
run_command
end
end
end
|
# -*- coding: utf-8 -*-
=begin
Faça um programa de forma que se possa trabalhar com vários
comandos digitados de uma só vez. Atualmente, apenas um comando
pode ser inserido por vez. Altere-o de forma a considerar operação
como uma string.
Exemplo: FFFAAAS significaria três novos clientes, três novos
atendimentos e, finalmente, a saida do programa.
=end
puts("=" * 60)
último = 10
fila = (1...11).to_a
while true
puts("\nExistem #{(fila).length} clientes na fila")
puts("Fila atual:", fila)
puts("Digite F para adicionar um cliente ao fim da fila,")
puts("ou A para realizar o atendimento. S para sair.")
print("Operação (F, A ou S):")
operação = gets.chomp.to_s
x = 0
sair = false
while x < (operação).length
if operação == "A" or operação == "a"
if((fila).length) > 0
atendido = fila[-1]
printf("Cliente %d atendido" % atendido)
else
puts("Fila vazia! Ninguém para atender.")
end
elsif operação == "F" or operação == "f"
último += 1 # Increnta o ticket do novo cliente
fila.insert(último)
elsif operação == "S" or operação == "s"
sair = true
break
else
puts("Operação inválida: #{operação} na posição #{[x]} #{x}! Digite apenas F, A ou S!")
end
x += 1
if (sair)
break
end
end
puts("=" * 60)
|
# Create a new list
# define an empty hash
# def list
# # grocery_list={}
# {}
# end
list = {}
my_list = {}
your_list = {}
# Add an item with a quantity to the list
# input: three items, hash list, one for name of item, one for quantity,
# body: add items to hash
# output: return hash
def add_item(list, name,quantity)
# grocery_list=list
list[name]=quantity
list
end
# Remove an item from the list
# input: hash list, name of item to remove
# body: Determine if item is on list and if yes, remove item
# output: return hash
def remove_item(list, name)
if !list.has_key?(name)
"Item not in list"
else
list.delete(name)
list
end
end
# Update quantities for items in your list
# input: three arguments, the list, one for name of item, one for new quantity
# body: check to see if item exists on list, and if yes, update quantity, if not then add item to list.
# output: return hash
def update_quantity(list, name, quantity)
if list.has_key?(name)
list[name]=quantity
list
else
add_item(list, name, quantity)
end
end
# Print the list (Consider how to make it look nice!)
# input: list hash
# output: print list
def print_list(list)
p "Item\tquantity"
list.each do |item,quantity|
# p item+"\t"+quantity.to_s
p "#{item}\t#{quantity}"
end
end
# We probably want to use a hash since we will be storing the items as strings and we also need to store a quantity
p list
p add_item(list, "apple", 1)
p add_item(list, "pineapple", 1)
p add_item(list, "bread", 1)
p remove_item(list, "apple")
p remove_item(list, "milk")
p add_item(list, "apple",1)
p update_quantity(list, "apple",2)
print_list(list)
#Reflection
#1- It is a helpful tool to outline the steps of the programming solution
#2- Hashes are easy to access values by using string keys, whereas arrays are
# easy to access via integer indexes. However in this challenge, hashes are
# more useful since they access values by keys
#3- A method returns the last item on the method definition if a return statement
# is not explicity stated
#4- A method can receive any data type as an argument
#5- By passing global variable into a method as an argument, the variable will
# be changed and can be accessed by other methods as an argument.
#6- the concept of passing arguments and returning values was solidified.
# reflection |
#encoding:utf-8
class ApplicationController < ActionController::Base
include SessionsHelper
protect_from_forgery with: :exception
helper_method :signed_in?, :current_user
before_action :set_locale
private
def set_locale
# 可以將 ["en", "zh-TW"] 設定為 VALID_LANG 放到 config/environment.rb 中
if params[:locale] && I18n.available_locales.include?( params[:locale].to_sym )
session[:locale] = params[:locale]
end
I18n.locale = session[:locale] || I18n.default_locale
end
def login(user)
session[:user_id] = user.id
if user.group.name =='Foodie Group Buying Group'
session[:locale]='en'
else
session[:locale]='zh'
end
end
def logout
session[:user_id] = nil
end
def current_user
@current_user ||= User.find_by_id(session[:user_id]) if session[:user_id]
#@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def signed_in?
current_user
end
def validate_user!
unless signed_in?
redirect_to login_url, alert: '请先登录!'
end
end
def validate_permission!(user)
unless current_user == user || is_admin?
redirect_to root_url, alert: '很抱歉您没有权限操作!'
end
end
end
|
FactoryBot.define do
factory :position, class: IGMarkets::Position do
contract_size 1000.0
controlled_risk false
created_date '2015/08/17 10:27:28:000'
created_date_utc '2015-07-24T09:12:37'
currency 'USD'
deal_id 'DEAL'
deal_reference 'reference'
direction 'BUY'
level 100.0
limit_level 110.0
limited_risk_premium { build :limited_risk_premium }
size 10.4
stop_level 90.0
trailing_step nil
trailing_stop_distance nil
market { build :market_overview }
end
end
|
require 'spec_helper'
require_relative '../../models/site'
require_relative '../../models/user'
require_relative '../../mappers/site_mapper'
describe SiteMapper do
describe "persist" do
let(:db) {Database.new}
let(:mapper) {SiteMapper.new(db)}
let(:user) {User.new("test@test.com", "testpassword", "testpassword")}
let(:url) {"http://test.com"}
let(:site) {Site.new(user, url)}
it "should set code of site that it persisted" do
mapper.persist(site)
expect(site.code).to_not be(nil)
end
it "should set id of site that it persisted" do
mapper.persist(site)
expect(site.id).to_not be(nil)
end
end
end |
class CreateHeadlineWidget < ::RailsConnector::Migration
def up
create_obj_class(
name: 'HeadlineWidget',
type: 'publication',
title: 'Headline widget',
attributes: [
{:name=>"headline", :type=>:string, :title=>"Headline"},
],
preset_attributes: {},
mandatory_attributes: nil
)
end
end
|
class ChangeColumns < ActiveRecord::Migration[5.2]
def change
change_column :sections, :departments_id, :text
change_column :sections, :teachers_id, :text
change_column :students, :section_id, :text
change_column :subjects, :department_id, :text
end
end
|
require_dependency 'juridical/application_controller'
module Juridical
class DefendantsController < ApplicationController # :nodoc:
before_action :set_legal_advice
def new
@defendant = ActiveCodhab::Juridical::ManagerDefendant::DefendantForm.new
end
def create
@defendant = ActiveCodhab::Juridical::ManagerDefendant::DefendantForm.new(set_params)
@defendant.staff_id = current_user.id
@defendant.legal_advice_id = @legal_advice.id
@defendant.save
flash[:success] = 'Registro incluído com sucesso.'
end
private
def set_params
params.require(:defendant_form).permit(:name)
end
def set_legal_advice
@legal_advice = ActiveCodhab::Juridical::LegalAdvice.find(params[:legal_advice_id])
end
end
end
|
module Resourceful
module CanCanMethods
extend ActiveSupport::Concern
included do
alias_method_chain :can_create?, :cancan
alias_method_chain :can_update?, :cancan
alias_method_chain :can_show?, :cancan
alias_method_chain :can_destroy?, :cancan
end
def can_create_with_cancan?(item=nil)
can_create_without_cancan?(item) and can?(:create, self.resource_class)
end
def can_update_with_cancan?(item=nil)
can_update_without_cancan?(item) and can?(:update, item || resource)
end
def can_show_with_cancan?(item=nil)
can_show_without_cancan?(item) and can?(:read, item || resource)
end
def can_destroy_with_cancan?(item=nil)
can_destroy_without_cancan?(item) and can?(:destroy, item || resource)
end
end
end |
class Statement < ApplicationRecord
belongs_to :topic
before_create :randomize_id
private
def randomize_id
begin
self.id = SecureRandom.random_number(1_000_000)
end while Statement.where(id: self.id).exists?
end
end
|
class Review < ActiveRecord::Base
attr_accessible :why_livingsocial, :why_hungry, :candidate_id, :reviewer_id, :status, :recommendation
belongs_to :candidate
belongs_to :reviewer
belongs_to :milestone
RATINGS = %w( recommendation )
def completed?
!why_livingsocial.blank? && !why_hungry.blank?
end
def total_score
total = RATINGS.inject(0) do |total, rating|
total += self.send(rating.to_sym)
end
total.to_f / RATINGS.count
end
end
# == Schema Information
#
# Table name: reviews
#
# id :integer not null, primary key
# reviewer_id :integer
# candidate_id :integer
# comment :text
# created_at :datetime not null
# updated_at :datetime not null
#
|
class Api::V1::ProductsController < ApplicationController
def index
@products = Product.all
render json: @products
end
def create
@product = Product.create(Product_params)
params['pieces'].each do |piece|
Product_content.create(piece_id: piece['piece_id'], product_id: @product['id'])
end
render json: @product, include: [:pieces]
end
private
def Product_params
params.require(:Product).permit!
end
end
|
class CreateServices < ActiveRecord::Migration[5.0]
def change
create_table :services do |t|
t.string :name
t.references :user, foreign_key: true
t.references :category, foreign_key: true
t.references :district, foreign_key: true
t.text :description
t.string :permalink
t.string :phone
t.string :web
t.string :email
t.string :logo
t.string :address
t.string :lat
t.string :lng
t.string :zipcode
t.string :facebook
t.string :instagram
t.boolean :published, default: true
t.boolean :premium, default: false
t.boolean :verified, default: false
t.boolean :deleted, default: false
t.boolean :banned, default: false
t.string :banned_reason
t.time :opens
t.time :closes
t.timestamps
end
add_index :services, :name
add_index :services, :description
add_index :services, :address
add_index :services, :zipcode
add_index :services, :permalink
end
end
|
class AddProjecttypeToProject < ActiveRecord::Migration[5.1]
def change
add_column :projects, :projecttype, :string
end
end
|
def save_scores(paper,day)
@day = Date.parse(day)
mixed_score = Story.on_date(@day).where(source:paper).map(&:mixed).get_average.round(2)
if mixed_score.nan? || mixed_score.nil?
p "Score on #{day} not valid"
return
else
@sc = Score.on_date(@day).where(source: paper).first_or_create! do |sc| #ensures only one per paper per day
sc.update(score:mixed_score, date:@day)
end
if @sc.persisted?
status = (@sc.just_created? ? "New" : "Updated")
p "Score #{status}, #{@sc.date}, #{@sc.source}, #{@sc.id} "
else
p "Score for #{paper} not updated"
end
end
end
def create_or_update_score_for(source,day)
save_scores(source,day)
end
def check_and_update_scores(day)
scores_to_be_fetched = any_scores_not_fetched_today? (day)
if scores_to_be_fetched.any?
p "saving Scores"
scores_to_be_fetched.each {|params|save_scores(params[:name],day)}
end
end
def all_sources_fetched?
scores = []
Score.from_today.each{|s| scores << s.score}
return scores.all?
end
def any_scores_not_fetched_today? (day)
@not_yet_fetched = []
CURRENT_NAMES.each do |key|
if not Score.where(source:key).on_date(day).exists?
@not_yet_fetched << params = {:name=> key}
p "Score on #{day} doesnt exist"
else
p "Score on #{day} exists"
end
end
@not_yet_fetched
end
def update_or_create_all_scores
date1 = Story.first.date.midnight.to_date
date2 = (Story.last.date.midnight + 1.day).to_date
date1.upto(date2).each do |date|
check_and_update_scores(date.to_s)
end
end |
require 'redmine'
Redmine::Plugin.register :redmine_remaining_time do
name 'Redmine Remaining Time plugin'
author 'Kazuyuki Ohgushi'
description 'This is a plugin for managing remaining time'
version '0.0.1'
url 'https://github.com/kzgs/redmine_remaining_time'
author_url 'https://github.com/kzgs'
end
require_dependency 'redmine_remaining_time/hooks'
|
class Acronym
class << self
def abbreviate(word)
word.scan(/(\w)\w*/).join.upcase
end
end
end
|
#!/usr/bin/env ruby
# ner0 https://www.github.com/real-ner0
# knock4 : Implementation of ping (ICMP) for IPv4 Server
# I'm still working for pinging IPv6 Servers
# Check for arguments
if ARGV.empty?
puts "Usage: knock <host_name>"
puts "host_name could be hostname or host addrress"
exit
end
# Load the libraries
require 'net/ping'
require 'socket'
require 'resolv'
host = ARGV[0]
# Resolve to IP Address if hostname is entered and get the hostname if IP address in entered
begin
host_addr = IPSocket.getaddress(host)
puts "\nTarget -> " + host_addr + " <-> " + Resolv.getname(host_addr)
rescue
puts "Failed to resolve IP Address. Aborting\n"
exit
end
@icmp = Net::Ping::ICMP.new(host_addr)
rtary = []
pingfails = 0
puts "\nKnocking...\n"
puts "CTRL + Z to stop...\n"
puts
# Start pinging
10.times do
if @icmp.ping
rtary << @icmp.duration
puts "Got Reply in #{@icmp.duration}"
else
pingfails += 1
puts "Timeout..."
end
end
puts "\n#{pingfails} packets were dropped..."
# End of Code
|
class UserPassedTestsController < ApplicationController
before_action :find_user_passed_test, only: %i[show update result gist]
def show; end
def result; end
def update
@user_passed_test.accept!(params[:answer_ids])
if @user_passed_test.completed?
awards = BadgeRuleService.new(@user_passed_test).check_awards
if awards.any?
@user_passed_test.user.badges << awards
flash[:notice] = t('.new_awards')
end
redirect_to result_user_passed_test_path(@user_passed_test)
else
render :show
end
end
def gist
result = GistQuestionService.new(@user_passed_test.current_question).call
flash_options = if result.success?
current_user.gists.create!(question: @user_passed_test.current_question,
url: result.html_url)
{ notice: t('.success',
url: view_context.link_to('gist.github.com',
result.html_url,
target: :blank)) }
else
{ alert: t('.failure') }
end
redirect_to @user_passed_test, flash_options
end
private
def find_user_passed_test
@user_passed_test = UserPassedTest.find(params[:id])
end
end
|
require 'thor'
require 'food'
require 'food/generators/recipe'
module Food
class CLI < Thor
desc "portray ITEM", "Determines if a piece of food is gross or delicious"
def portray(name)
puts Food.portray(name)
end
desc "pluralize", "Pluralizes a word"
method_option :word, aliases: "-w"
def pluralize
puts Food.pluralize(options[:word])
end
desc "recipe", "Generates a recipe scaffold"
def recipe(group, name)
Generators::Recipe.start([group, name])
end
end
end |
class PaypalIpn < ActiveRecord::Base
attr_accessible :data, :txn_id, :state, :subscr_id, :txn_type, :subscription, :subscription_id, :custom, :payment_status, :receiver_email
belongs_to :user
OK = 'ok'
NOT_UNIQUE = 'not_unique'
NOT_COMPLETED = 'not_completed'
WRONG_SELLER = 'wrong_seller'
USER_NOT_FOUND = 'user_not_found'
UNKNOWN_TRANSACTION = 'unknown_transaction'
STATES = [OK, NOT_UNIQUE,NOT_COMPLETED, WRONG_SELLER, USER_NOT_FOUND, UNKNOWN_TRANSACTION]
end
|
class AddBuzzSumoFieldtoUrls < ActiveRecord::Migration[5.1]
def change
add_column :urls, :buzzsumo, :integer
end
end
|
require 'spec_helper'
describe Landlord do
context 'phone format' do
it 'converts phone number to only numbers and no special characters' do
landlord1 = FactoryGirl.create(:landlord, phone: '(310)-123/4561')
expect(landlord1.phone).to eql('3101234561')
end
it 'returns invalid if phone length is > 10' do
expect{FactoryGirl.create(:landlord, phone: '12345678911')}.to raise_error(ActiveRecord::RecordInvalid)
end
it 'returns invalid if phone length is < 10' do
expect{FactoryGirl.create(:landlord, phone: '1234567')}.to raise_error(ActiveRecord::RecordInvalid)
end
end
end |
class RecipeIngredient < ActiveRecord::Base
has_many :ingredients
has_many :recipes
end
|
class MenuSolver
attr_reader :price, :menu, :orders
def initialize(price, menu)
@price = price
@menu = menu
@orders = []
end
def possible_orders
find_orders
orders.empty? ? "No solutions found" : orders
end
def find_orders(money=price, order=[], start_index=0)
menu.each_with_index do |(item, cost), index|
next if index < start_index
if money == cost # order + current item is a solution
solution = order << item
orders << solution unless orders.include? solution
elsif money - cost > 0 # item is suitable for current order
o = order.dup << item
find_orders(money - cost, o, index)
end
end
end
end
|
CarrierWave.configure do |config|
if ENV['AWS_BUCKET'] and !Rails.env.test?
config.storage = :aws
config.aws_bucket = ENV.fetch('AWS_BUCKET')
config.aws_acl = 'private'
# Optionally define an asset host for configurations that are fronted by a
config.asset_host = "https://s3-#{ENV.fetch('AWS_REGION')}.amazonaws.com/#{config.aws_bucket}"
# The maximum period for authenticated_urls is only 1 minute.
config.aws_authenticated_url_expiration = 60 * 5
config.aws_credentials = {
access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY'),
region: ENV.fetch('AWS_REGION')
}
else
config.enable_processing = false if Rails.env.test?
config.storage = :file
end
end
|
# Plugin's routes
# See: http://guides.rubyonrails.org/routing.html
#get 'global_roadmap', :to => 'global_roadmap#index'
get '/projects/:project_id/global_roadmap' , :to => "global_roadmap#index", :as => :global_roadmap
|
include_recipe 'chef-openstack::common'
prereq_packages = %w[openvswitch-datapath-dkms]
common_packages = %w[openvswitch-switch
neutron-plugin-openvswitch-agent
neutron-lbaas-agent
haproxy]
network_services = %w[openvswitch-switch
neutron-plugin-openvswitch-agent
neutron-lbaas-agent]
prereq_packages.each do |pkg|
package prereq_packages.join(' ') do
action :install
end
end
common_packages.each do |pkg|
package pkg do
action :install
end
end
network_services.each do |srv|
service srv do
provider Chef::Provider::Service::Upstart
action :nothing
end
end
template 'neutron network node OVS config' do
path '/etc/neutron/plugins/openvswitch/ovs_neutron_plugin.ini'
owner 'root'
group 'neutron'
mode '0644'
source 'neutron/ovs_neutron_plugin.ini.erb'
notifies :restart,
resources(:service => 'neutron-plugin-openvswitch-agent'),
:immediately
notifies :restart,
resources(:service => 'openvswitch-switch'),
:immediately
end
template '/etc/neutron/lbaas_agent.ini' do
source 'neutron/lbaas_agent.ini.erb'
owner 'root'
group 'root'
mode '0644'
notifies :restart, resources(:service => 'neutron-lbaas-agent')
end
bash 'create external bridge' do
not_if('ovs-vsctl list-br | grep br-ex')
code <<-CODE
ovs-vsctl add-br br-ex
CODE
end
bash 'create SoftLayer private bridge' do
not_if('ovs-vsctl list-br | grep br-priv')
code <<-CODE
ovs-vsctl add-br br-priv
CODE
end
bash 'create integration bridge' do
not_if('ovs-vsctl list-br | grep br-int')
code <<-CODE
ovs-vsctl add-br br-int
CODE
end
if node[:node_info][:is_bonded] == 'True'
template '/etc/network/interfaces' do
owner 'root'
group 'neutron'
mode '0644'
source 'neutron/interfaces-bonded.erb'
end
else
template '/etc/network/interfaces' do
owner 'root'
group 'neutron'
mode '0644'
source 'neutron/interfaces-nonbonded.erb'
end
end
private_iface = node[:node_info][:private_iface]
private_cidr = node[:node_info][:private_ip] + '/' + \
node[:node_info][:private_cidr]
public_iface = node[:node_info][:public_iface]
public_cidr = node[:node_info][:public_ip] + '/' + \
node[:node_info][:public_cidr]
# Private bridge configuration
if node[:node_info][:private_dest] && node[:node_info][:private_via]
# SoftLayer hardware
execute 'Configure SoftLayer internal network bridge' do
not_if("ip addr show dev br-priv | grep #{node[:node_info][:private_ip]}")
command "ip addr del #{private_cidr} dev #{private_iface};
ip addr add #{private_cidr} dev br-priv;
ovs-vsctl add-port br-priv #{private_iface};
ip link set dev br-priv up;
route add -net #{node[:node_info][:private_dest]} \
gw #{node[:node_info][:private_via]} \
dev br-priv"
action :run
end
else
# Commodity hardware and virtual machines
execute 'Configure other internal network bridge' do
not_if("ip addr show dev br-priv | grep #{node[:node_info][:private_ip]}")
command "ip addr del #{private_cidr} dev #{private_iface};
ip addr add #{private_cidr} dev br-priv;
ovs-vsctl add-port br-priv #{private_iface};
ip link set dev br-priv up"
action :run
end
end
# Public bridge configuration
execute 'Configure external network bridge' do
not_if("ip addr show dev br-ex | grep #{node[:node_info][:public_ip]}")
command "ip addr del #{public_cidr} dev #{public_iface};
ip addr add #{public_cidr} dev br-ex;
ovs-vsctl add-port br-ex #{public_iface};
ip link set dev br-ex up;
route add default gw #{node[:node_info][:default_gateway]} br-ex"
action :run
end
|
# encoding: UTF-8
control "local-file-check" do
title "Compliance check for local file."
desc "
Check local file for contents.
"
impact 0.5
describe file("/home/ec2-user/chef.txt") do
its("content") { should match("Chef is good.") }
end
end |
class User < ActiveRecord::Base
has_secure_password
has_many :tweets
def self.is_logged_in?(session)
!!session[:user_id]
end
def self.current_user(session)
user = User.find_by_id(session[:user_id])
user
end
def slug
slug = self.username.split(" ").join("-")
end
def self.find_by_slug(slug)
unslugged = slug.split("-").join(" ")
user = User.find_by(username:unslugged)
user
end
end |
class PreviewsController < ApplicationController
# GET /previews
# GET /previews.json
def index
@previews = Preview.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @previews }
end
end
# GET /previews/1
# GET /previews/1.json
def show
@preview = Preview.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @preview }
end
end
# GET /previews/new
# GET /previews/new.json
def new
@preview = Preview.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @preview }
end
end
# GET /previews/1/edit
def edit
@preview = Preview.find(params[:id])
end
# POST /previews
# POST /previews.json
def create
@preview = Preview.new(params[:preview])
respond_to do |format|
if @preview.save
format.html { redirect_to @preview, notice: 'Preview was successfully created.' }
format.json { render json: @preview, status: :created, location: @preview }
else
format.html { render action: "new" }
format.json { render json: @preview.errors, status: :unprocessable_entity }
end
end
end
# PUT /previews/1
# PUT /previews/1.json
def update
@preview = Preview.find(params[:id])
respond_to do |format|
if @preview.update_attributes(params[:preview])
format.html { redirect_to @preview, notice: 'Preview was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: @preview.errors, status: :unprocessable_entity }
end
end
end
# DELETE /previews/1
# DELETE /previews/1.json
def destroy
@preview = Preview.find(params[:id])
@preview.destroy
respond_to do |format|
format.html { redirect_to previews_url }
format.json { head :ok }
end
end
end
|
Avocado::Engine.routes.draw do
root to: 'specs#index'
resources :specs, only: [:create]
end
|
# The Google Maps Results representing class
class Gmresult
include DataMapper::Resource
property :id, Serial
property :email, String, required: true, length: 255
property :formatted_address, Text, required: true
property :place_id, Text, required: true
property :created_at, DateTime, required: true
has n, :gmaddresscomponents
has n, :gmtypes
has 1, :gmgeometry
belongs_to :gmresponse
end
|
class BikesController < ApplicationController
before_action :authenticate_user!, :except => [:index]
before_action :set_bike, :only => [ :show, :edit, :update, :destroy]
def index
@bikes = Bike.all
@bikes = Bike.page(params[:page]).per(5)
end
def new
@bike = Bike.new
end
def create
@bike = Bike.new(bike_params)
if @bike.save
flash[:notice] = "was successfully created"
redirect_to bikes_path
else
render :action => :new
end
end
def show
@page_title = @bike.name
end
def edit
end
def update
if @bike.update(bike_params)
flash[:notice] = "was successfully updated"
redirect_to bike_url(@bike)
else
render :action => :edit
end
end
def destroy
flash[:alert] = "was successfully deleted"
@bike.destroy
redirect_to bikes_url
end
private
def set_bike
@bike=Bike.find(params[:id])
end
def bike_params
params.require(:bike).permit(:name, :description, :category_id)
end
end
|
class Restaurant
@@filepath = nil
def self.filepath=(path=nil)
@@filepath = File.join(APP_ROOT, path)
end
#checks if restaurant file exists
def self.file_exists?
#class should know if the restaurant file file_exists
if @@filepath && File.exists?(@@filepath)
return true
else
return false
end
end
#boolean tests for useable restaurant file, better than file_exists?
def self.file_useable?
return false unless @@filepath
return false unless File.exists?(@@filepath)
return false unless File.readable?(@@filepath)
#writable not writeable!!!!
return false unless File.writable?(@@filepath)
return true
end
def self.create_file
#create the restaurant file
File.open(@@filepath, 'w') unless file_exists?
return file_useable?
end
def self.saved_restaurants
#read the restaurant file
#return instances of restaurant
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.