text stringlengths 10 2.61M |
|---|
class WorkoutGroup < ApplicationRecord
has_many :user_groups, :dependent => :delete_all
has_many :users, through: :user_groups
has_many :workouts, :dependent => :delete_all
validates :name, presence: true
accepts_nested_attributes_for :user_groups
accepts_nested_attributes_for :workouts, reject_if: :all_blank
scope :search, ->(query) {where("name LIKE ?", "%#{query}%")}
def find_current_user_group(current_user)
user_groups.where("user_id = ?", current_user.id).first
end
end
|
require 'rails_helper'
describe 'Team Parser' do
describe '.parse' do
context 'with valid parameters' do
it 'creates a new team if one does not exist' do
TeamParser.parse(create_pull_request_params)
expect(Team.all.size).to eq(1)
end
it 'finds the team if one does exist' do
team = create(:team)
parsed_team = TeamParser.parse(create_pull_request_params)
expect(Team.all.size).to eq(1)
expect(parsed_team).to eq(team)
end
end
context 'with invalid paramters' do
it 'returns nil if the object cannnot be parsed' do
team = create(:team)
invalid_params = create_pull_request_params
invalid_params.delete(:team_id)
nil_team = TeamParser.parse(invalid_params)
expect(nil_team).to eq(nil)
end
end
end
end
|
class SynchronizeRepositoryWorker
include Sidekiq::Worker
def perform(repository_id)
repository = Repository.find(repository_id)
provider = repository.provider.camelize.constantize
provider::Repositories.synchronize(repository)
repository.save!
SynchronizeIssuesWorker.perform_async(repository.id)
end
end
|
class Post < ActiveRecord::Base
attr_accessible :body, :title, :summary
belongs_to :user
validates :body, :presence => true
validates :title, :presence => true
def to_param
"#{id}-#{title.gsub(/[^a-z0-9]+/i, '-')}"
end
end
|
require 'openssl'
require 'yaml'
require 'hashlib'
require 'deep_merge'
require 'addressable/uri'
require 'httparty'
require 'onering/config'
module Onering
class API
module Actions
class Retry < ::Exception; end
end
module Errors
class Exception < ::Exception; end
class NotConnected < Exception; end
class ClientError < Exception; end
class Unauthorized < ClientError; end
class Forbidden < ClientError; end
class NotFound < ClientError; end
class ServerError < Exception; end
class ConnectionTimeout < Exception; end
class AuthenticationMissing < Exception; end
end
include Onering::Util
include ::HTTParty
attr_accessor :url
format :json
DEFAULT_BASE="https://onering"
DEFAULT_PATH="/api"
DEFAULT_CLIENT_PEM=["~/.onering/client.pem", "/etc/onering/client.pem"]
DEFAULT_CLIENT_KEY=["~/.onering/client.key", "/etc/onering/client.key"]
DEFAULT_VALIDATION_PEM="/etc/onering/validation.pem"
def initialize(options={})
@_plugins = {}
options = {} if options.nil?
@_connection_options = options
# load and merge all config file sources
Onering::Config.load(@_connection_options[:configfile], @_connection_options.get(:config, {}))
if options.get('config.nosslverify', false) == true
# deliberately break SSL verification
Onering::Logger.warn("Disabling SSL peer verification for #{options.get('config.url')}")
OpenSSL::SSL.send(:const_set, :OLD_VERIFY_PEER, OpenSSL::SSL::VERIFY_PEER)
OpenSSL::SSL.send(:remove_const, :VERIFY_PEER)
OpenSSL::SSL.send(:const_set, :VERIFY_PEER, OpenSSL::SSL::VERIFY_NONE)
else
# restore SSL verification if it's currently broken
if defined?(OpenSSL::SSL::OLD_VERIFY_PEER)
if OpenSSL::SSL::VERIFY_PEER == OpenSSL::SSL::VERIFY_NONE and OpenSSL::SSL::OLD_VERIFY_PEER != OpenSSL::SSL::VERIFY_NONE
OpenSSL::SSL.send(:remove_const, :VERIFY_PEER)
OpenSSL::SSL.send(:const_set, :VERIFY_PEER, OpenSSL::SSL::OLD_VERIFY_PEER)
end
end
end
if OpenSSL::SSL::VERIFY_PEER == OpenSSL::SSL::VERIFY_NONE
Onering::Logger.warn("Disabling SSL peer verification for #{options.get('config.url')}")
end
# source interface specified
# !! HAX !! HAX !! HAX !! HAX !! HAX !! HAX !! HAX !! HAX !! HAX !! HAX !!
# Due to certain versions of Ruby's Net::HTTP not allowing you explicitly
# specify the source IP/interface to use, this horrific monkey patch is
# necessary, if not right.
#
# If at least some of your code doesn't make you feel bottomless shame
# then you aren't coding hard enough.
#
if options.get('config.source').is_a?(String)
if options.get('config.source') =~ /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/
# insert firing pin into the hack
TCPSocket.instance_eval do
(class << self; self; end).instance_eval do
alias_method :_stock_open, :open
attr_writer :_hack_local_ip
define_method(:open) do |conn_address, conn_port|
_stock_open(conn_address, conn_port, @_hack_local_ip)
end
end
end
# arm the hack
TCPSocket._hack_local_ip = options.get('config.source')
# sound the siren
Onering::Logger.info("Using local interface #{options.get('config.source')} to connect", "Onering::API")
else
raise "Invalid source IP address #{options.get('config.source')}"
end
end
# set API connectivity details
Onering::API.base_uri(options.get('config.url', Onering::Config.get(:url, DEFAULT_BASE)))
Onering::Logger.info("Server URL is #{Onering::API.base_uri}", "Onering::API")
# add default parameters
options.get('config.params',{}).each do |k,v|
_default_param(k,v)
end
connect(options) if options.get(:autoconnect, true)
end
def connect(options={})
# setup authentication
_setup_auth()
Onering::Logger.debug("Connection setup complete", "Onering::API")
return self
end
def request(method, endpoint, options={})
endpoint = [Onering::Config.get(:path, DEFAULT_PATH).strip, endpoint.sub(/^\//,'')].join('/')
Onering::Logger.debug("#{method.to_s.upcase} #{endpoint}#{(options[:query] || {}).empty? ? '' : '?'+options[:query].join('=', '&')}", "Onering::API")
options.get(:headers,[]).each do |name, value|
next if name == 'Content-Type' and value == 'application/json'
Onering::Logger.debug("+#{name}: #{value}", "Onering::API")
end
begin
case (method.to_sym rescue method)
when :post
rv = Onering::API.post(endpoint, options)
when :put
rv = Onering::API.put(endpoint, options)
when :delete
rv = Onering::API.delete(endpoint, options)
when :head
rv = Onering::API.head(endpoint, options)
else
rv = Onering::API.get(endpoint, options)
end
rescue SocketError => e
Onering::Logger.fatal!("Unable to connect to #{Onering::API.base_uri}", "Onering::API")
end
if rv.code >= 500
raise Errors::ServerError.new("HTTP #{rv.code} - #{Onering::Util.http_status(rv.code)} #{rv.parsed_response.get('error.message','') rescue ''}")
elsif rv.code >= 400
message = "HTTP #{rv.code} - #{Onering::Util.http_status(rv.code)} #{rv.parsed_response.get('error.message', '') rescue ''}"
case rv.code
when 401
raise Errors::Unauthorized.new(message)
when 403
raise Errors::Forbidden.new(message)
when 404
raise Errors::NotFound.new(message)
else
raise Errors::ClientError.new(message)
end
else
rv
end
end
def get(endpoint, options={})
request(:get, endpoint, options)
end
def post(endpoint, options={}, &block)
if block_given?
request(:post, endpoint, options.merge({
:body => yield
}))
else
request(:post, endpoint, options)
end
end
def put(endpoint, options={}, &block)
if block_given?
request(:put, endpoint, options.merge({
:body => yield
}))
else
request(:put, endpoint, options)
end
end
def delete(endpoint, options={})
request(:delete, endpoint, options)
end
# I'm not a huge fan of what's happening here, but metaprogramming is hard...
#
# "Don't let the perfect be the enemy of the good."
#
def method_missing(method, *args, &block)
modname = method.to_s.split('_').map(&:capitalize).join
if not (plugin = (Onering::API.const_get(modname) rescue nil)).nil?
@_plugins[method] ||= plugin.new.connect(@_connection_options)
return @_plugins[method]
else
super
end
end
def status()
Onering::API.new.get("/").parsed_response
end
# -----------------------------------------------------------------------------
def _setup_auth()
type = Onering::Config.get('authentication.type', :auto)
_setup_auth_token()
end
# -----------------------------------------------------------------------------
def _default_param(key, value)
@_default_params ||= {}
@_default_params[key] = value
Onering::API.default_params(@_default_params)
end
# -----------------------------------------------------------------------------
def _setup_auth_token()
Onering::Logger.info("Using token authentication mechanism", "Onering::API")
# get first keyfile found
key = Onering::Config.get('authentication.key', Onering::Config.get('authentication.keyfile'))
if key.nil?
if Onering::Config.get('authentication.bootstrap.enabled', true)
Onering::Logger.warn("Authentication token not found, attempting to autoregister client", "Onering::API")
if not (bootstrap = Onering::Config.get('authentication.bootstrap.key')).nil?
if bootstrap.to_s =~ /[0-9a-f]{32,64}/
# attempt to create key.yml from least-specific to most, first writable path wins
clients = [{
:path => "/etc/onering",
:name => fact('hardwareid'),
:keyname => 'system',
:autodelete => true
},{
:path => "~/.onering",
:name => ENV['USER'],
:keyname => 'cli',
:autodelete => false
}]
# for each client attempt...
clients.each do |client|
# expand and assemble path
client[:path] = (File.expand_path(client[:path]) rescue client[:path])
keyfile = File.join(client[:path], 'key.yml')
# skip this if we can't write to the parent directory
next unless File.writable?(client[:path])
Dir.mkdir(client[:path]) unless File.directory?(client[:path])
next if File.exists?(keyfile)
self.class.headers({
'X-Auth-Bootstrap-Token' => bootstrap
})
# attempt to create/download the keyfile
Onering::Logger.debug("Requesting authentication token for #{client[:name].strip}; #{bootstrap}", "Onering::API")
response = self.class.get("/api/users/#{client[:name].strip}/tokens/#{client[:keyname]}")
# if successful, write the file
if response.code < 400 and response.body
File.open(keyfile, 'w').puts(YAML.dump({
'authentication' => {
'key' => response.body.strip.chomp
}
}))
key = response.body.strip.chomp
else
# all errors are fatal at this stage
Onering::Logger.fatal!("Cannot autoregister client: HTTP #{response.code} - #{(response.parsed_response || {}).get('error.message', 'Unknown error')}", "Onering::API")
end
self.class.headers({})
# we're done here...
break
end
else
raise Errors::AuthenticationMissing.new("Autoregistration failed: invalid bootstrap token specified")
end
else
raise Errors::AuthenticationMissing.new("Autoregistration failed: no bootstrap token specified")
end
else
raise Errors::AuthenticationMissing.new("Authentication token not found, and autoregistration disabled")
end
end
raise Errors::AuthenticationMissing.new("Token authentication specified, but cannot find a token config or as a command line argument") if key.nil?
# set auth mechanism
Onering::API.headers({
'X-Auth-Mechanism' => 'token'
})
# set default parameters
_default_param(:token, key)
end
end
end
|
class Content < ActiveRecord::Base
# attr_accessor :color, :text, :font
belongs_to :user
validates_presence_of :color, :title, :font, :user_id
before_create :restrict_user_from_creating_one_more_record
def restrict_user_from_creating_one_more_record
errors.add(:base, "Cannot create one more record, instead update") if self.id.present?
end
end
|
require 'sinatra'
require 'open-uri'
require 'openssl'
require 'nokogiri'
require 'nintendo_eshop'
# require 'pry'
# overwrite nintendo_eshop method due to some responses have nil dates
# `self.release_date = Date.parse(result.dig(:releaseDateMask))`
NintendoEshop::Game.class_eval do
def refresh_object(result)
self.art = "https://www.nintendo.com#{result.dig(:boxArt)}"
self.id = result.dig(:nsuid)
self.msrp = result.dig(:msrp)
self.sale_price = result.dig(:salePrice)
self.title = result.dig(:title)
end
end
helpers do
# inherit module, explicitly set client values
def set_client
NintendoEshop.base_url = 'https://u3b6gr4ua3-dsn.algolia.net'
NintendoEshop.api_key = '9a20c93440cf63cf1a7008d75f7438bf'
NintendoEshop.app_id = 'U3B6GR4UA3'
end
def document
Nokogiri::HTML(open('https://switcher.co/deals'))
end
def game_titles
document.css("span.bg-black").children.map {|child| child.text}
end
def listings
set_client
game_titles.map do |title|
NintendoEshop::GamesList.by_title(title).first
end
end
def game_count
eshop_games.count
end
def discount(retail, sale)
difference = retail - sale
enumerator = difference / retail
"-#{(enumerator * 100).round}%"
end
def generate_json
@file = File.new("data/eshop_sale_#{Time.now.strftime('%Y%m%d')}.json", 'w')
arr = []
eshop_games.each do |g|
game = {
:title => g.title,
:id => g.id,
:msrp => g.msrp,
:sale_price => g.sale_price,
:discount => discount(g.msrp, g.sale_price),
:art => g.art,
}
arr << game
end
@file.write(JSON.pretty_generate(arr))
@file.close
end
# only include listings from nintendo eshop
def eshop_games
arr = []
listings.each do |g|
if g&.sale_price
arr << g
end
end
arr
end
# include to json
def meta_critic
end
# profile to check if you own the game
def own?(game)
# current_user.games.find(id: game.id)
end
# helpers
end
get '/' do
file = File.read('data/eshop_sale_20200212.json')
@data_hash = JSON.parse(file)
erb :layout
end |
class Changeplayercolumns < ActiveRecord::Migration
def change
change_column :participants, :upgrades, :text, :limit => nil
end
end
|
module MigratorWeb
class Migration
include ActiveModel::Model
attr_accessor :id, :name, :status
def down
ActiveRecord::Migrator.run(:down, self.class.paths, id.to_i)
reload
end
def up
ActiveRecord::Migrator.run(:up, self.class.paths, id.to_i)
reload
end
def redo
down
up
reload
end
def to_param
id
end
def reload
self.status = self.class.find(id).status
end
class << self
def all(index = false)
db_list = ActiveRecord::Base.connection.select_values("SELECT version FROM #{ActiveRecord::Migrator.schema_migrations_table_name}")
db_list.map! { |version| "%.3d" % version }
file_list = []
self.paths.each do |path|
Dir.foreach(path) do |file|
# match "20091231235959_some_name.rb" and "001_some_name.rb" pattern
if match_data = /^(\d{3,})_(.+)\.rb$/.match(file)
status = db_list.delete(match_data[1]) ? 'up' : 'down'
file_list << [status, match_data[1], match_data[2].humanize]
end
end
end
db_list.map! do |version|
['up', version, '********** NO FILE **********']
end
migtaions = index ? {} : []
(db_list + file_list).sort_by {|m| m[1]}.each do |migration|
if index
migtaions[migration[1]] = self.new(id: migration[1], name: migration[2], status: migration[0])
else
migtaions << self.new(id: migration[1], name: migration[2], status: migration[0])
end
end
migtaions
end
def find(id)
all(true)[id.to_s]
end
def paths
ActiveRecord::Migrator.migrations_paths.map { |path| File.join([Rails.root, path]) }
end
def migrate
require 'active_record/schema_dumper'
ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, nil)
filename = File.join(Rails.root, 'db', 'schema.rb')
File.open(filename, "w:utf-8") do |file|
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end
end
end
end
end
|
class Image
def initialize (blur)
@picture = blur
end
def blur
@ones = []
@picture.each_with_index do |row, row_index|
row.each_with_index do |column, column_index|
if column == 1
@ones << [row_index, column_index]
end
end
end
@ones.each do |row, column|
maxRowIndex = @picture.length()-1
#puts maxRowIndex
maxColumnIndex = @picture[row].length - 1
#to the left of 1
if column > 0
# then
@picture [row] [column - 1] = 1
end
#to the right of 1
if column < maxColumnIndex
# then
@picture [row] [column + 1 ] = 1
end
#above 1
if row > 0
# then
@picture [row -1] [column] = 1
end
#below 1
if row < maxRowIndex
# then
@picture [row + 1] [column] = 1
end
end
end
def output_image
@picture.each do |row|
print row.join, "\n"
end
end
end
#---------------------------------
ManHatNum = ARGV[0].to_i
image = Image.new ([
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,1,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]
])
ManHatNum.times {
image.blur
}
image.output_image
puts ARGV |
# -*- coding: utf-8 -*-
module RolesHelper
include ApplicationHelper
def is_admin?(program = current_program)
return false unless session_exists?
return true if current_user && current_user.system_admin?
is_logged_in? && (!session[:act_as_admin].blank? || has_role('Admin', program))
end
def is_admin_any_program?
return false unless session_exists?
is_logged_in? && (!session[:act_as_admin].blank? || has_role_any_program('Admin'))
end
def has_read_all?(program = current_program)
return false unless session_exists?
is_logged_in? && (!session[:act_as_admin].blank? || has_role('Admin', program) || has_role('Full Read-only Access', program))
end
def is_super_admin?
return false unless session_exists?
is_logged_in? && current_user.system_admin?
# is_logged_in? && !session[:act_as_admin].blank?
end
def has_role(role, program)
return false unless is_logged_in?
return false if current_user.blank?
return false if current_user.roles_users.blank?
current_user.roles_users.for_program(program.try(:id)).each do |user_role|
return true if user_role.role.name == role
end
false
end
def has_role_any_program(role)
return false unless is_logged_in?
return false if current_user.blank?
return false if current_user.roles_users.blank?
current_user.roles_users.each do |user_role|
return true if user_role.role.name == role
end
false
end
def session_exists?
defined?(session) && ! session.nil?
end
end
|
class Api::UsersController < ApplicationController
skip_before_action :authenticate_request, only: [:login]
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
def create
@user = User.create!(user_params)
render status: :created
end
def login
@token = AuthenticateUser.call(user_params[:email], user_params[:password])
render json: { token: @token.result }
end
private
def user_params
params.require(:user).permit(
:email,
:password
)
end
end
|
#Write another method that returns true if the string passed as an argument is a palindrome, false otherwise.
#This time, however, your method should be case-insensitive, and it should ignore all non-alphanumeric characters.
def real_palindrome?(string)
alphanumeric = ('a'..'z').to_a + ('0'..'9').to_a
palindrome_chars = string.downcase.chars.select {|char| alphanumeric.include?(char)}
palindrome_chars.join.reverse == palindrome_chars.join
end
real_palindrome?('madam') == true
real_palindrome?('Madam') == true # (case does not matter)
real_palindrome?("Madam, I'm Adam") == true # (only alphanumerics matter)
real_palindrome?('356653') == true
real_palindrome?('356a653') == true
real_palindrome?('123ab321') == false
|
namespace :bm do
desc "one class' attributes and small intersection, query benchmarking"
task :one_class_small_intersection => :environment do
require 'benchmark'
include Benchmark
include RakeHelper
def loops
Artist.all.each do |artist|
if artist.commissions.present?
artist.name
end
end
end
def joins
Artist.joins(:commissions).each do |artist|
artist.name
end
end
def includes
Artist.includes(:commissions).each do |artist|
artist.name
end
end
puts "ARTISTS WITH COMMISSIONS"
bm_test = Benchmark.benchmark(CAPTION, 7, FORMAT) do |x|
tl = x.report("loops:") { loops }
tj = x.report("joins:") { joins }
ti = x.report("includes:") { includes }
end
bm_hash = parse_times(bm_test).sort_by{ |k,v| v }
write_partial('_scenario_three.html.erb', bm_hash)
end
end |
# first and last letters of each word in a string swapped
# strings separated by spaces
# input = string
# output = string (swapped first and last letters)
# Capital letters remain as is
# Spaces included in output string
# swap first and last letters around
# sub both letters
def swap(string)
array = string.split
swapped_array = array.map do |element|
element[0], element[-1] = element[-1], element[0]
element
end
swapped_array.join(' ')
end
|
require 'rails_helper'
RSpec.describe PhotoHelper, :type => :helper do
before(:each) do
allow(helper).to receive(:render).and_return("<tag />")
end
context "for two photos" do
it "calls render twice" do
photo = "anyObject"
photos = [photo, photo]
expect(helper).to receive(:render).with({partial: "photo", object: photo}).twice
helper.render_photos(photos)
end
it "renders concatenated photos" do
photo = "anyObject"
photos = [photo, photo]
expected = "<tag /><tag />"
rendered_photos = helper.render_photos(photos)
expect(rendered_photos).to eq(expected)
end
it "returns html_safe string" do
photo = "anyObject"
photos = [photo, photo]
rendered_photos = helper.render_photos(photos)
expect(rendered_photos).to be_html_safe
end
end
end
|
class AddBusVoltageLvToImportanceIndices < ActiveRecord::Migration
def self.up
add_column :importance_indices, :bus_voltage_lv_id, :integer
end
def self.down
remove_column :importance_indices, :bus_voltage_lv_id
end
end
|
class Post < ActiveRecord::Base
validates_presence_of :post
has_attached_file :image, :styles => { :medium => ["590x500>", :jpg]}, :convert_options => { :medium => "-quality 70" }, :message => ""
validates_attachment_content_type :image, :content_type => /\Aimage\/(jpg|jpeg|png|gif)\Z/, :message => "nope"
validates_attachment_file_name :image, matches: [/png\Z/, /jpe?g\Z/, /gif\Z/], :message => "nope"
validates_attachment_size :image, :in => 0.megabytes..5.megabytes, :message => ""
belongs_to :user
end
|
require 'socket'
module ML
module Learners
class Learner
SOCKET_PROTOCOL = 0
SOCKET_BUFFSIZE = 1048576
SOCKET_MESSAGES_IN_FLIGHT = 80
LARGE_SOCKET_MESSAGES_IN_FLIGHT = 10
PYTHON_BINARY = %w(python external/ml/mitclasses)
def initialize(model)
@model = model
@num_features = Array.wrap(model.num_features)
setup_sockets
spawn_process
end
def preprocess(preprocess_vectors)
send_vectors preprocess_vectors, :preprocess, in_flight: LARGE_SOCKET_MESSAGES_IN_FLIGHT
end
def build(feature_vectors)
send_vectors feature_vectors, :features
send_message nil, :eof
receive
end
def eval(feature_vector)
send_message [feature_vector], :features
receive['data'].flatten
end
def destroy
send_message nil, :quit
@ruby_socket.close
Process.waitpid(@pid)
end
private
def send_vectors(vectors, type, in_flight: SOCKET_MESSAGES_IN_FLIGHT)
vectors.in_groups_of(in_flight, false) do |group|
send_message group, type
end
end
def send_message(data, type = 'info')
@ruby_socket.send(JSON.dump(type: type, data: data), SOCKET_PROTOCOL)
rescue Errno::ENOBUFS => e
Rails.logger.warn e.message
sleep 0.1
retry
end
def receive
JSON.parse(@ruby_socket.recv(SOCKET_BUFFSIZE))
end
def setup_sockets
@ruby_socket, @python_socket = Socket.pair :UNIX, :DGRAM, SOCKET_PROTOCOL
[@ruby_socket, @python_socket].each do |socket|
socket.setsockopt :SOCKET, :SO_RCVBUF, SOCKET_BUFFSIZE
socket.setsockopt :SOCKET, :SO_SNDBUF, SOCKET_BUFFSIZE
end
end
def spawn_process
@pid = Process.spawn *PYTHON_BINARY, @python_socket.fileno.to_s,
@num_features.join(','), self.class.type.to_s, @model.name,
@python_socket => @python_socket
@python_socket.close
end
end
end
end
|
require 'spec_helper'
describe Enocean::Esp3::CommonCommand do
describe "ReadIdBase" do
let(:command) { Enocean::Esp3::ReadIdBase.create }
it "should create a ReadId command" do
command.packet_type.should == 0x05
end
it "should print the packet " do
command.to_s.should_not be_nil
end
describe "response" do
let(:response) { Enocean::Esp3::ReadIdBaseResponse.from_data([0x0, 0xff, 0x0, 0x1, 0x2]) }
it "should parse the correct response " do
response.should be_ok
response.base_id.should == [0xff, 0x0, 0x1, 0x2]
end
end
end
end |
class MoussaillonsController < ApplicationController
def index
@moussaillons = Moussaillon.all
# @number_of_gossips = Gossip.where("moussaillon_id = " + ).count
end
def new
@moussaillon = Moussaillon.new
end
def create
@moussaillon = Moussaillon.new
@moussaillon.username = params_moussaillon[:username]
@moussaillon.email = params_moussaillon[:email]
if @moussaillon.save
redirect_to moussaillons_path
else
render 'new'
end
end
def show
@moussaillon = Moussaillon.find(params[:id])
@gossips = Gossip.where(moussaillon_id: params[:id])
end
def edit
@moussaillon = Moussaillon.find(params[:id])
end
def update
@moussaillon = Moussaillon.find(params[:id])
if @moussaillon.update(params_moussaillon)
redirect_to moussaillons_path
else
render 'edit'
end
end
private
def params_moussaillon
params.require(:moussaillon).permit(:username, :email, :bio)
end
end
|
Rails.application.routes.draw do
root to: 'jobs#index'
get 'jobs/next', to: 'jobs#next'
resources :jobs
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
# Serve websocket cable requests in-process
mount ActionCable.server => '/cable'
end
|
class UsersController < ApplicationController
before_action :current_meetup, only: [:show, :directions, :cancel, :update]
def new
@user = User.new
categories = ['Technology','TV','Business','Politics','Travel','Games','Movies','Theatre','Sports','Fashion']
categories.each do |category|
interest = Interest.new(name: category)
match = Interest.find_by(name: interest.name)
if !match
interest.save
end
end
end
def create
@user = User.new(user_params)
if @user.save
log_in(@user)
redirect_to @user
else
p @user.errors.messages
render 'new'
end
end
def edit
@user = User.find(params[:id])
end
def show
@user = User.find(params[:id])
end
def index
redirect_to current_user
end
private
def user_params
params.require(:user).permit(:first_name,:last_name,:age,:phone_number,:email,:password,:password_confirmation,interest_ids:[])
end
def current_meetup
@current_meetup = Meetup.find_by(user_one: current_user.id)
@current_meetup_joined = Meetup.find_by(user_two: current_user.id)
end
end
|
require_relative "../spec_helper"
load_lw_resource("rbenv", "ruby")
describe Chef::Resource::RbenvRuby do
let(:resource) { described_class.new("antruby") }
it "sets the default attribute to definition" do
expect(resource.definition).to eq("antruby")
end
it "attribute definition_file defaults to nil" do
expect(resource.definition_file).to be_nil
end
it "attribute definition_file takes a String value" do
resource.definition_file("/blah/blah/rubay")
expect(resource.definition_file).to eq("/blah/blah/rubay")
end
it "attribute root_path defaults to nil" do
expect(resource.root_path).to be_nil
end
it "attribute root_path takes a String value" do
resource.root_path("/rootness/path")
expect(resource.root_path).to eq("/rootness/path")
end
it "attribute user defaults to nil" do
expect(resource.user).to be_nil
end
it "attribute user takes a String value" do
resource.user("curious_george")
expect(resource.user).to eq("curious_george")
end
it "action defaults to :install" do
expect(resource.action).to eq(:install)
end
it "actions include :reinstall" do
expect(resource.allowed_actions).to include(:reinstall)
end
it "#to_s includes user if provided" do
resource.user("molly")
expect(resource.to_s).to eq("rbenv_ruby[antruby] (molly)")
end
it "#to_s includes system label if user is not provided" do
expect(resource.to_s).to eq("rbenv_ruby[antruby] (system)")
end
end
|
RSpec.describe LaserGem, type: :model do
it "has working factory" do
laser_gem = build :laser_gem
expect(laser_gem.save).to be true
end
it "checks name attribute" do
laser_gem = build :laser_gem, name: ""
expect(laser_gem.save).to be false
end
it "validates low values for length" do
laser_gem = build :laser_gem, name: "t"
expect(laser_gem.save).to be false
end
it "validates high values for length" do
laser_gem = build :laser_gem, name: "hstglsnfmndvbdkjsdkfjdvjdfjdvkdjkkdjfkj"*3
expect(laser_gem.save).to be false
end
it "checks laser-gem has a gem spec" do
laser_gem_with_spec = create :laser_gem
expect(laser_gem_with_spec.gem_spec).not_to eq nil
end
describe "#register_dependency" do
it "creates a gem dependency" do
laser_gem = create :laser_gem
laser_gem2 = create :laser_gem
laser_gem.register_dependency(laser_gem2, "1.0.0")
expect(laser_gem.gem_dependencies.map(&:dependency)).to eq [laser_gem2]
end
it "does not allow a gem to be added as a dependency to the same parent gem twice" do
laser_gem = create :laser_gem
laser_gem2 = create :laser_gem
laser_gem.register_dependency(laser_gem2, "1.0.0")
expect(laser_gem.gem_dependencies.count).to eq 1
expect { laser_gem.register_dependency(laser_gem2, "2.0.0") }
.to raise_error(ActiveRecord::RecordInvalid)
laser_gem.reload
expect(laser_gem.gem_dependencies.count).to eq 1
end
end
describe "#remove_dependency" do
it "deletes a gem dependency" do
laser_gem = create :laser_gem
laser_gem2 = create :laser_gem
laser_gem.register_dependency(laser_gem2, "1.0.0")
expect(laser_gem.gem_dependencies.map(&:dependency)).to eq [laser_gem2]
laser_gem.remove_dependency(laser_gem2)
expect(laser_gem.gem_dependencies.map(&:dependency)).to eq []
end
end
end
|
class SessionsController < ApplicationController
include SessionsHelper
def index
if logged_in?
redirect_to user_profile_path(current_user.id)
end
end
def create
user = User.find_by(email: params[:email].downcase)
user = Instructor.find_by(email: params[:email].downcase) if !user
if user && user.authenticate(params[:password])
log_in user
if user.class.name == 'Instructor'
flash[:success] = "Welcome back <span class='text-danger'>instructor</span> #{user.name}"
redirect_to dashboard_instructor_path
else
flash[:success] = "Welcome back #{user.name}"
redirect_to dashboard_path
end
else
flash[:danger] = 'Invalid email/Wrong password' # Not quite right!
redirect_to request.referer
end
end
def destroy
log_out
flash[:success] = 'Thanks for visit us'
redirect_to root_url
end
private
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
sizes = ["Small", "Medium", "Large", "X-Large"]
10.times do
Item.create(
purchase_date: Faker::Date.in_date_period(year:2020),
name: Faker::Commerce.product_name,
brand: Faker::Company.name,
size: sizes.sample,
cost: Faker::Commerce.price
)
end
|
class Review < ApplicationRecord
validates :rating, presence: true
belongs_to :restaurant
belongs_to :user
end |
require 'spec_helper'
describe Crepe::API, '.mount' do
app do
sub_api = Class.new Crepe::API do
get { 'HI' }
end
mount sub_api
mount -> env { [200, {}, ['OK']] } => '/ping'
namespace :pong do
mount -> env { [200, {}, ['KO']] }
end
end
it 'mounts Rack apps in place' do
expect(get('/').body).to eq '"HI"'
end
it 'mounts Rack apps at paths' do
expect(get('/ping').body).to eq 'OK'
end
it 'mounts Rack apps within namespaces' do
expect(get('/pong').body).to eq 'KO'
end
end
|
class NicknameFan < ActiveRecord::Base
belongs_to :club
validates :club, presence: true
validates :name, presence: true
has_enumeration_for :status, with: CommonStatus, required: true,
create_scopes: true, create_helpers: true
after_initialize :pluralize_name, on: :create
default_scope { order(:name) }
private
def pluralize_name
self.plural = name.pluralize if name.present? && plural.nil?
end
end
|
require_relative 'berserk_player'
decribe BerserkPlayer do
before do
@initial_health = 50
@player = BerserkPlayer.new("berserker", @initial_health)
end
it "does not go berserk when w00ted up to 5 times" do 1.upto(5)
{@player.w00t}
@player.berserk?.should be_false
end
it "goes bersek when w00ted more than 5 times" do 1. upto(6)
{played.w00t}
@player.berserk?.should be_true
end
it "gets w00ted instead of blammed when its gone berserk"do
1. upto(6) {@player.w00t}
1.upto(2){player.blam}
@player.health.should == @initial_health + (8 * 15)
end
end
|
require_relative 'mover'
require_relative 'bomb'
class Player
attr_reader :pos
def initialize(window)
@window = window
@sprite = Gosu::Image.new(window, "images/stickfig.png", false)
@arm = Gosu::Image.new(window, "images/arm.png", false)
@pos = Mover.new
end
def facing xdir, ydir
@x_face = xdir
@y_face = ydir
end
def accel dir
case dir
when :left
@pos.xvel -= 1 unless @pos.xvel <= -5
when :right
@pos.xvel += 1 unless @pos.xvel >= 5
when :up
@pos.yvel = -40 if @pos.y == 602
when :down
@pos.yvel += 1 unless @pos.yvel >= 5
end
end
def make_bomb(xdir, ydir, fuse)
Bomb.new(@window, xdir, ydir, @pos.x, @pos.y, fuse)
end
def move
@pos.move
@pos.xvel *= 0.95
@pos.yvel *= 0.95
@pos.x = 0 if @pos.x < 0
@pos.x = 1024 - 64 if @pos.x > 1024-64
@pos.y = 602 if @pos.y > 602 #Floor is y=602
end
def draw
@sprite.draw(@pos.x, @pos.y, 1)
dx = 0
dx = -1 if @x_face == :left
dx = 1 if @x_face == :right
dy = 0
dy = 1 if @y_face == :down
dy = -1 if @y_face == :up
angle = Math.atan2(dy,dx) * (180.0/3.14159)
@arm.draw_rot(@pos.x + 32, @pos.y + 32, 1, angle, 0)
end
end
|
class BookGroupship < ApplicationRecord
belongs_to :book
belongs_to :group
end |
require 'bcrypt'
# The User model
class User < ApplicationRecord
include BCrypt
validates :name, :password_hash, presence: true
validates :admin, inclusion: [true, false]
validates :email, uniqueness: true
validates :email, presence: true,
format: { with: /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/ },
uniqueness: { case_sensitive: false }
def password
Password.new(password_hash)
end
def password=(new_password)
self.password_hash = Password.create(new_password)
end
def self.authenticated?(email, password)
user = User.find_by(email: email)
return user if user && user.password == password
false
end
end
|
require "json"
require "selenium-webdriver"
require "test/unit"
class LogIn < Test::Unit::TestCase
def setup
@driver = Selenium::WebDriver.for :chrome
@base_url = "https://staging.shore.com/merchant/sign_in"
@accept_next_alert = true
@driver.manage.timeouts.implicit_wait = 30
@verification_errors = []
end
def teardown
@driver.quit
assert_equal [], @verification_errors
end
def test_create_customer
target_size = Selenium::WebDriver::Dimension.new(1420, 940)
@driver.manage.window.size = target_size
@driver.get "https://staging.shore.com/merchant/sign_in"
@driver.find_element(:id, "merchant_account_email").clear
@driver.find_element(:id, "merchant_account_email").send_keys "js@shore.com"
@driver.find_element(:id, "merchant_account_password").clear
@driver.find_element(:id, "merchant_account_password").send_keys "secret"
@driver.find_element(:name, "button").click
#creates a new customer / delete the customer afterwards
@driver.find_element(:css, "i.shore-icon-backend-new-customer").click
@driver.find_element(:css, "#MerchantAppContainer > div > div.view-container.noHeader > div > div > shore-app-wrapper > div > div > div > div > div.customers-app--1n26yqc8E4W14AyFhyH_wj.panel-heading > div > div > div.flex-cell.flex-spread > div > div:nth-child(1) > div > div > a > span.customers-app--3dE172rI_1mUEgGr6c1w0W > i").click
@driver.find_element(:css, "div.dropdown.open > ul.dropdown-menu > li:first-child > a").click
@driver.find_element(:xpath, "(//input[@id=''])[1]").clear
@driver.find_element(:xpath, "(//input[@id=''])[1]").send_keys "Auto"
@driver.find_element(:xpath, "(//input[@id=''])[2]").clear
@driver.find_element(:xpath, "(//input[@id=''])[2]").send_keys "Chromedriver"
@driver.find_element(:xpath, "(//input[@id=''])[3]").clear
@driver.find_element(:xpath, "(//input[@id=''])[3]").send_keys "auto@shore.com"
@driver.find_element(:xpath, "(//input[@id=''])[4]").clear
@driver.find_element(:xpath, "(//input[@id=''])[4]").send_keys "+49 174 2499358"
@driver.find_element(:xpath, "(//input[@id=''])[5]").clear
@driver.find_element(:xpath, "(//input[@id=''])[5]").send_keys "18.02.1999"
@driver.find_element(:xpath, "(//input[@id=''])[6]").clear
@driver.find_element(:xpath, "(//input[@id=''])[6]").send_keys "Teststraße 10"
@driver.find_element(:xpath, "(//input[@id=''])[7]").clear
@driver.find_element(:xpath, "(//input[@id=''])[7]").send_keys "8000"
@driver.find_element(:xpath, "(//input[@id=''])[8]").clear
@driver.find_element(:xpath, "(//input[@id=''])[8]").send_keys "Selenium"
@driver.find_element(:css, "button.btn.btn-primary").click
assert_equal @driver.find_element(tag_name: 'body').text.include?("Auto"), false
@driver.find_element(:css, "#MerchantAppContainer > div > div.view-container.noHeader > div > div > shore-app-wrapper > div > div > div.col-xs-12.col-sm-12.col-md-8.col-lg-8 > div:nth-child(2) > div:nth-child(1) > div.customers-app--1_BbJF2bJfOvEfjYoTembg.customers-app--ccWgGgLlsk4LAV4R5jrJ3 > div > div.flex-cell.flex-spread > div > div.flex-cell.flex-spread > div > div > div.customers-app--1j4MRJEh133sJNdIys8XQo > ul > li > input").click
@driver.find_element(:css, "ul > li:nth-of-type(2) > span > span:nth-of-type(3)").click
@driver.find_element(:css, "div.flex-cell.button-cell > button.btn.btn-primary").click
@driver.find_element(:css, "div.flex-cell.flex-spread > input.form-control").send_keys "Auto note written by chrome"
@driver.find_element(:css, "form.flex-form-inline > div:nth-of-type(2) > button.btn.btn-primary").click
sleep 4
#delete customer
@driver.get "https://staging.shore.com/merchant/app/customers"
@driver.find_element(:css, "th.mtw-filter-column.mtw-filter-firstname > input").clear
@driver.find_element(:css, "th.mtw-filter-column.mtw-filter-firstname > input").send_keys "Auto"
sleep 4
@driver.find_element(:css, "span.mtw-column-action-delete-row").click
sleep 2
@driver.find_element(:css, "button.btn.btn-danger.btn-sm.mtw-column-confirm-action-delete-row").click
#search for customer in column
@driver.get "https://staging.shore.com/merchant/app/customers"
@driver.find_element(:css, "th.mtw-filter-column.mtw-filter-firstname > input").send_keys "Alisson"
sleep 5
@driver.find_element(:css, "tr.mtw-row.can-open > td:nth-of-type(2)").click
sleep 2
verify { assert_include @driver.find_element(:css, "h2 > span:first-child").text, "Alisson" }
@driver.find_element(:css,"i.shore-icon-backend-previous").click
@driver.find_element(:css, "th.mtw-filter-column.mtw-filter-lastname > input").send_keys "Travis"
sleep 5
@driver.find_element(:css, "tr.mtw-row.can-open > td:nth-of-type(2)").click
sleep 2
verify { assert_include @driver.find_element(:css, "h2 > span:nth-of-type(3)").text, "Travis" }
@driver.find_element(:css,"i.shore-icon-backend-previous").click
sleep 2
end
def verify(&blk)
yield
rescue Test::Unit::AssertionFailedError => ex
@verification_errors << ex
end
end
|
class ContactForm < MailForm::Base
attribute :name
attribute :email
attribute :phone
attribute :building
attribute :pets
attribute :smoker
attribute :student
attribute :comments
validates_presence_of :name, :email, :phone
validates_format_of :email, :with => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i, message: "Wromg email format"
validates_format_of :phone, with: /\A([1]-)?[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}\z/, message: "Wrong phone format"
def headers
{
:subject => "Brookview Properties Contact",
:to => "brookviewonellc@gmail.com",
:from => %("#{name}" <#{email}>)
}
end
end |
require ("minitest/autorun")
require_relative("../player")
require_relative("../board")
require_relative("../game")
class TestGame < MiniTest::Test
def setup
positions={
2=>4,
7=>-7,
}
@board=Board.new(9, positions)
@player1=Player.new("Val")
@player2=Player.new("Rick")
@players =[@player1,@player2]
@game=Game.new(@players,@board)
end
def test_game_starts_with_2_players
assert_equal(2,@game.number_of_players())
end
def test_game_current_player_starts_as_player_1
assert_equal(@player1,@game.current_player())
end
def test_update_current_player
assert_equal(@player2,@game.update_current_player())
end
def test_can_take_turn
@game.next_turn(1)
assert_equal(1,@player1.position)
assert_equal(@player2,@game.current_player)
end
def test_cannot_move_beyond_end_of_board
@game.next_turn(15)
assert_equal(8,@player1.position)
end
def test_can_take_turn_with_ladder
@game.next_turn(2)
assert_equal(6,@player1.position)
end
def test_can_take_turn_with_snake
@game.next_turn(7)
assert_equal(0,@player1.position)
end
def test_winner_starts_as_nil
assert_equal(nil,@game.winner)
end
def test_game_is_won
@game.next_turn(8)
assert_equal(true,@game.is_won?)
end
def test_game_is_lost
@game.next_turn(5)
assert_equal(true,@game.is_lost?)
end
def test_no_next_turn_on_win
@game.next_turn(8)
@game.next_turn(2)
assert_equal(0,@player2.position)
end
def test_adds_turn_to_log
@game.next_turn(1)
assert_equal(1,@game.log.size)
assert_equal("Val", @game.log[0].player.name)
assert_equal(1,@game.log[0].roll)
assert_equal(0,@game.log[0].modifier)
end
end
|
class ServiceProvider < ApplicationRecord
has_one :booked_service
end
|
Rails.application.routes.draw do
resources :ratings
resources :lessons
resources :reviews
resources :users
resources :sessions
resources :tags
root "new_age#index"
get 'new_age/index', to:"new_age#index"
resources :welcome, only: :index
get '/help', to: "tags#index", as: "help"
# get '/pair', to: "tags#edit", as: "pair"
# get '/unpair', to: "tags#edit", as: "unpair"
get '/login', to: "new_age#login", as: "login"
get '/signup', to: "new_age#signup", as: "signup"
# post '/sessions', to: "sessions#create", as: "sessions"
delete '/logout', to: "sessions#destroy", as: "logout"
get '/signup', to: "users#new"
get '/search', to: "lessons#search", as: "search"
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
CAMPUSES = ['Alabaster',
'Auburn',
'Fultondale',
'Gadsden',
'Grandview',
'Grants Mill',
'The Chapel',
'Greystone',
'Huntsville',
'McCalla',
'Mobile',
'Montgomery',
'Online',
'Opelika',
'Oxford',
'Riverchase',
'Shoals',
'Tuscaloosa',
'Woodlawn'].freeze
|
module RollbarAPI
class Client
module Connection
def get(path, options = {})
request :get, path, options
end
def post(path, options = {})
request :post, path, options
end
def put(path, options = {})
request :put, path, options
end
def delete(path, options = {})
request :delete, path, options
end
def patch(path, options = {})
request :patch, path, options
end
private
def request(http_method, path, options)
response = self.class.send(http_method, path, options)
data = response.parsed_response
end
end
end
end
|
class MoveIsselectedFromAppointmenttypesToAppointmentTypesUser < ActiveRecord::Migration
def change
remove_column :appointment_types , :is_selected
add_column :appointment_types_users , :is_selected , :boolean
add_column :appointment_types_users , :practi_name , :string
end
end
|
class EventsController < ApplicationController
before_action :set_user, only: [:show]
#respond_to :json
def create
render status: :bad_request, :json => { :msg => "Device ID param not found."} and return unless params[:device_id].present?
@user = User.find_by(:device_id => params[:device_id]) rescue nil
render status: :not_found, :json => { :msg => "Invalid device ID."} and return unless @user.present?
for event in params[:events]
event.permit!
@event = Event.new(event)
if @event.is_blocked(params[:device_id])
@event.increment_counter(params[:device_id])
logger.info("Event blocked : " + params[:device_id] + " " + @event.name)
else
@event.user_id = @user.id
@event.created_at = params[:ts] if params[:ts].present?
if !@event.save
logger.error("Failed to save event : " + @event)
end
end
end
render status: :created, :json => { :msg => "Events saved successfully."}
end
def show
if @user.present?
events = @user.events.order_by(:created_at => 'asc')
render json: events.as_json(:only => [:name, :created_at, :info]), status: :ok
else
render status: :not_found, :json => { :msg => "Device ID not found."}
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find_by(:device_id => params[:id]) rescue nil
end
# Never trust parameters from the scary internet, only allow the white list through.
def event_params
params.require(:event).permit!
end
end
|
require 'spec_helper'
class ExceptionWithContext < StandardError
def sentry_context
{
foo: "bar"
}
end
end
RSpec.describe Sentry::Client do
let(:configuration) do
Sentry::Configuration.new.tap do |config|
config.dsn = Sentry::TestHelper::DUMMY_DSN
config.transport.transport_class = Sentry::DummyTransport
end
end
subject { Sentry::Client.new(configuration) }
let(:transaction) do
hub = Sentry::Hub.new(subject, Sentry::Scope.new)
Sentry::Transaction.new(
name: "test transaction",
hub: hub,
sampled: true
)
end
let(:fake_time) { Time.now }
before do
allow(Time).to receive(:now).and_return fake_time
end
describe "#transport" do
let(:configuration) { Sentry::Configuration.new }
context "when transport.transport_class is provided" do
before do
configuration.dsn = Sentry::TestHelper::DUMMY_DSN
configuration.transport.transport_class = Sentry::DummyTransport
end
it "uses that class regardless if dsn is set" do
expect(subject.transport).to be_a(Sentry::DummyTransport)
end
end
context "when transport.transport_class is not provided" do
context "when dsn is not set" do
subject { described_class.new(Sentry::Configuration.new) }
it "returns dummy transport object" do
expect(subject.transport).to be_a(Sentry::DummyTransport)
end
end
context "when dsn is set" do
before do
configuration.dsn = Sentry::TestHelper::DUMMY_DSN
end
it "returns HTTP transport object" do
expect(subject.transport).to be_a(Sentry::HTTPTransport)
end
end
end
end
describe '#event_from_message' do
let(:message) { 'This is a message' }
it 'returns an event' do
event = subject.event_from_message(message)
hash = event.to_hash
expect(event).to be_a(Sentry::ErrorEvent)
expect(hash[:message]).to eq(message)
expect(hash[:level]).to eq(:error)
end
it "inserts threads interface to the event" do
event = nil
t = Thread.new do
event = subject.event_from_message(message)
end
t.name = "Thread 1"
t.join
hash = event.to_hash
thread = hash[:threads][:values][0]
expect(thread[:id]).to eq(t.object_id)
expect(thread[:name]).to eq("Thread 1")
expect(thread[:crashed]).to eq(false)
expect(thread[:stacktrace]).not_to be_empty
end
end
describe "#event_from_transaction" do
let(:hub) do
Sentry::Hub.new(subject, Sentry::Scope.new)
end
let(:transaction) do
hub.start_transaction(name: "test transaction")
end
before do
configuration.traces_sample_rate = 1.0
transaction.start_child(op: "unfinished child")
transaction.start_child(op: "finished child", timestamp: Time.now.utc.iso8601)
end
it "initializes a correct event for the transaction" do
event = subject.event_from_transaction(transaction)
event_hash = event.to_hash
expect(event_hash[:type]).to eq("transaction")
expect(event_hash[:contexts][:trace]).to eq(transaction.get_trace_context)
expect(event_hash[:timestamp]).to eq(transaction.timestamp)
expect(event_hash[:start_timestamp]).to eq(transaction.start_timestamp)
expect(event_hash[:transaction]).to eq("test transaction")
expect(event_hash[:spans].count).to eq(1)
expect(event_hash[:spans][0][:op]).to eq("finished child")
expect(event_hash[:level]).to eq(nil)
end
it "correct dynamic_sampling_context when incoming baggage header" do
baggage = Sentry::Baggage.from_incoming_header(
"other-vendor-value-1=foo;bar;baz, "\
"sentry-trace_id=771a43a4192642f0b136d5159a501700, "\
"sentry-public_key=49d0f7386ad645858ae85020e393bef3, "\
"sentry-sample_rate=0.01337, "\
"sentry-user_id=Am%C3%A9lie, "\
"other-vendor-value-2=foo;bar;"
)
transaction = Sentry::Transaction.new(name: "test transaction", hub: hub, baggage: baggage, sampled: true)
event = subject.event_from_transaction(transaction)
expect(event.dynamic_sampling_context).to eq({
"sample_rate" => "0.01337",
"public_key" => "49d0f7386ad645858ae85020e393bef3",
"trace_id" => "771a43a4192642f0b136d5159a501700",
"user_id" => "Amélie"
})
end
it "correct dynamic_sampling_context when head SDK" do
event = subject.event_from_transaction(transaction)
expect(event.dynamic_sampling_context).to eq({
"environment" => "development",
"public_key" => "12345",
"sample_rate" => "1.0",
"sampled" => "true",
"transaction" => "test transaction",
"trace_id" => transaction.trace_id
})
end
it "adds explicitly added contexts to event" do
transaction.set_context(:foo, { bar: 42 })
event = subject.event_from_transaction(transaction)
expect(event.contexts).to include({ foo: { bar: 42 } })
end
end
describe "#event_from_exception" do
let(:message) { 'This is a message' }
let(:exception) { Exception.new(message) }
let(:event) { subject.event_from_exception(exception) }
let(:hash) { event.to_hash }
it "sets the message to the exception's value and type" do
expect(hash[:exception][:values][0][:type]).to eq("Exception")
expect(hash[:exception][:values][0][:value]).to match(message)
end
context "with special error messages" do
let(:exception) do
begin
{}[:foo][:bar]
rescue => e
e
end
end
it "sets correct exception message based on Ruby version" do
version = Gem::Version.new(RUBY_VERSION)
case
when version >= Gem::Version.new("3.3.0-dev")
expect(hash[:exception][:values][0][:value]).to eq(
"undefined method `[]' for nil (NoMethodError)\n\n {}[:foo][:bar]\n ^^^^^^"
)
when version >= Gem::Version.new("3.2")
expect(hash[:exception][:values][0][:value]).to eq(
"undefined method `[]' for nil:NilClass (NoMethodError)\n\n {}[:foo][:bar]\n ^^^^^^"
)
when version >= Gem::Version.new("3.1") && RUBY_ENGINE == "ruby"
expect(hash[:exception][:values][0][:value]).to eq(
"undefined method `[]' for nil:NilClass\n\n {}[:foo][:bar]\n ^^^^^^"
)
else
expect(hash[:exception][:values][0][:value]).to eq("undefined method `[]' for nil:NilClass")
end
end
end
it "sets threads interface without stacktrace" do
event = nil
t = Thread.new do
event = subject.event_from_exception(exception)
end
t.name = "Thread 1"
t.join
event_hash = event.to_hash
thread = event_hash[:threads][:values][0]
expect(thread[:id]).to eq(t.object_id)
expect(event_hash.dig(:exception, :values, 0, :thread_id)).to eq(t.object_id)
expect(thread[:name]).to eq("Thread 1")
expect(thread[:crashed]).to eq(true)
expect(thread[:stacktrace]).to be_nil
end
it 'has level ERROR' do
expect(hash[:level]).to eq(:error)
end
it 'does not belong to a module' do
expect(hash[:exception][:values][0][:module]).to eq('')
end
it 'returns an event' do
event = subject.event_from_exception(ZeroDivisionError.new("divided by 0"))
expect(event).to be_a(Sentry::ErrorEvent)
expect(Sentry::Event.get_message_from_exception(event.to_hash)).to match("ZeroDivisionError: divided by 0")
end
context 'for a nested exception type' do
module Sentry::Test
class Exception < RuntimeError; end
end
let(:exception) { Sentry::Test::Exception.new(message) }
it 'sends the module name as part of the exception info' do
expect(hash[:exception][:values][0][:module]).to eq('Sentry::Test')
end
end
describe "exception types test" do
context 'for a Sentry::Error' do
let(:exception) { Sentry::Error.new }
it 'does not create an event' do
expect(subject.event_from_exception(exception)).to be_nil
end
end
context 'for a Sentry::ExternalError' do
let(:exception) { Sentry::ExternalError.new }
it 'does not create an event' do
expect(subject.event_from_exception(exception)).to be_nil
end
end
context 'for an excluded exception type' do
module Sentry::Test
class BaseExc < RuntimeError; end
class SubExc < BaseExc; end
module ExcTag; end
end
let(:config) { subject.configuration }
context "invalid exclusion type" do
it 'returns Sentry::ErrorEvent' do
config.excluded_exceptions << nil
config.excluded_exceptions << 1
config.excluded_exceptions << {}
expect(subject.event_from_exception(Sentry::Test::BaseExc.new)).to be_a(Sentry::ErrorEvent)
end
end
context "defined by string type" do
it 'returns nil for a class match' do
config.excluded_exceptions << 'Sentry::Test::BaseExc'
expect(subject.event_from_exception(Sentry::Test::BaseExc.new)).to be_nil
end
it 'returns nil for a top class match' do
config.excluded_exceptions << '::Sentry::Test::BaseExc'
expect(subject.event_from_exception(Sentry::Test::BaseExc.new)).to be_nil
end
it 'returns nil for a sub class match' do
config.excluded_exceptions << 'Sentry::Test::BaseExc'
expect(subject.event_from_exception(Sentry::Test::SubExc.new)).to be_nil
end
it 'returns nil for a tagged class match' do
config.excluded_exceptions << 'Sentry::Test::ExcTag'
expect(
subject.event_from_exception(Sentry::Test::SubExc.new.tap { |x| x.extend(Sentry::Test::ExcTag) })
).to be_nil
end
it 'returns Sentry::ErrorEvent for an undefined exception class' do
config.excluded_exceptions << 'Sentry::Test::NonExistentExc'
expect(subject.event_from_exception(Sentry::Test::BaseExc.new)).to be_a(Sentry::ErrorEvent)
end
end
context "defined by class type" do
it 'returns nil for a class match' do
config.excluded_exceptions << Sentry::Test::BaseExc
expect(subject.event_from_exception(Sentry::Test::BaseExc.new)).to be_nil
end
it 'returns nil for a sub class match' do
config.excluded_exceptions << Sentry::Test::BaseExc
expect(subject.event_from_exception(Sentry::Test::SubExc.new)).to be_nil
end
it 'returns nil for a tagged class match' do
config.excluded_exceptions << Sentry::Test::ExcTag
expect(subject.event_from_exception(Sentry::Test::SubExc.new.tap { |x| x.extend(Sentry::Test::ExcTag) })).to be_nil
end
end
context "when exclusions overridden with :ignore_exclusions" do
it 'returns Sentry::ErrorEvent' do
config.excluded_exceptions << Sentry::Test::BaseExc
expect(subject.event_from_exception(Sentry::Test::BaseExc.new, ignore_exclusions: true)).to be_a(Sentry::ErrorEvent)
end
end
end
context 'when the exception has a cause' do
let(:exception) { build_exception_with_cause }
it 'captures the cause' do
expect(hash[:exception][:values].length).to eq(2)
end
end
context 'when the exception has nested causes' do
let(:exception) { build_exception_with_two_causes }
it 'captures nested causes' do
expect(hash[:exception][:values].length).to eq(3)
end
end
context 'when the exception has a recursive cause' do
let(:exception) { build_exception_with_recursive_cause }
it 'should handle it gracefully' do
expect(hash[:exception][:values].length).to eq(1)
end
end
if RUBY_PLATFORM == "java"
context 'when running under jRuby' do
let(:exception) do
begin
raise java.lang.OutOfMemoryError, "A Java error"
rescue Exception => e
return e
end
end
it 'should have a backtrace' do
frames = hash[:exception][:values][0][:stacktrace][:frames]
expect(frames.length).not_to eq(0)
end
end
end
context 'when the exception has a backtrace' do
let(:exception) do
e = Exception.new(message)
allow(e).to receive(:backtrace).and_return [
"/path/to/some/file:22:in `function_name'",
"/some/other/path:1412:in `other_function'"
]
e
end
it 'parses the backtrace' do
frames = hash[:exception][:values][0][:stacktrace][:frames]
expect(frames.length).to eq(2)
expect(frames[0][:lineno]).to eq(1412)
expect(frames[0][:function]).to eq('other_function')
expect(frames[0][:filename]).to eq('/some/other/path')
expect(frames[1][:lineno]).to eq(22)
expect(frames[1][:function]).to eq('function_name')
expect(frames[1][:filename]).to eq('/path/to/some/file')
end
context 'with internal backtrace' do
let(:exception) do
e = Exception.new(message)
allow(e).to receive(:backtrace).and_return(["<internal:prelude>:10:in `synchronize'"])
e
end
it 'marks filename and in_app correctly' do
frames = hash[:exception][:values][0][:stacktrace][:frames]
expect(frames[0][:lineno]).to eq(10)
expect(frames[0][:function]).to eq("synchronize")
expect(frames[0][:filename]).to eq("<internal:prelude>")
end
end
context 'when a path in the stack trace is on the load path' do
before do
$LOAD_PATH << '/some'
end
after do
$LOAD_PATH.delete('/some')
end
it 'strips prefixes in the load path from frame filenames' do
frames = hash[:exception][:values][0][:stacktrace][:frames]
expect(frames[0][:filename]).to eq('other/path')
end
end
end
context 'when the exception responds to sentry_context' do
let(:hash) do
event = subject.event_from_exception(ExceptionWithContext.new)
event.to_hash
end
it "merges the context into event's extra" do
expect(hash[:extra][:foo]).to eq('bar')
end
end
end
end
describe "#generate_sentry_trace" do
let(:string_io) { StringIO.new }
let(:logger) do
::Logger.new(string_io)
end
before do
configuration.logger = logger
end
let(:span) { Sentry::Span.new(transaction: transaction) }
it "generates the trace with given span and logs correct message" do
expect(subject.generate_sentry_trace(span)).to eq(span.to_sentry_trace)
expect(string_io.string).to match(
/\[Tracing\] Adding sentry-trace header to outgoing request: #{span.to_sentry_trace}/
)
end
context "with config.propagate_traces = false" do
before do
configuration.propagate_traces = false
end
it "returns nil" do
expect(subject.generate_sentry_trace(span)).to eq(nil)
end
end
end
describe "#generate_baggage" do
before { configuration.logger = logger }
let(:string_io) { StringIO.new }
let(:logger) { ::Logger.new(string_io) }
let(:baggage) do
Sentry::Baggage.from_incoming_header(
"other-vendor-value-1=foo;bar;baz, sentry-trace_id=771a43a4192642f0b136d5159a501700, "\
"sentry-public_key=49d0f7386ad645858ae85020e393bef3, sentry-sample_rate=0.01337, "\
"sentry-user_id=Am%C3%A9lie, other-vendor-value-2=foo;bar;"
)
end
let(:span) do
hub = Sentry::Hub.new(subject, Sentry::Scope.new)
transaction = Sentry::Transaction.new(name: "test transaction",
baggage: baggage,
hub: hub,
sampled: true)
transaction.start_child(op: "finished child", timestamp: Time.now.utc.iso8601)
end
it "generates the baggage header with given span and logs correct message" do
generated_baggage = subject.generate_baggage(span)
expect(generated_baggage).to eq(span.to_baggage)
expect(generated_baggage).to eq(
"sentry-trace_id=771a43a4192642f0b136d5159a501700,"\
"sentry-public_key=49d0f7386ad645858ae85020e393bef3,"\
"sentry-sample_rate=0.01337,"\
"sentry-user_id=Am%C3%A9lie"
)
expect(string_io.string).to match(
/\[Tracing\] Adding baggage header to outgoing request: #{span.to_baggage}/
)
end
context "with config.propagate_traces = false" do
before do
configuration.propagate_traces = false
end
it "returns nil" do
expect(subject.generate_baggage(span)).to eq(nil)
end
end
end
end
|
require 'test_helper'
class Forums::Public::TopicsControllerTest < ActionController::TestCase
setup do
@provider = FactoryBot.create :provider_account
@request.host = @provider.domain
@forum = FactoryBot.create :forum, :account => @provider
@topic = FactoryBot.create :topic, :forum => @forum, :user => @provider.admins.first!
@provider.settings.forum_enabled = true
@provider.settings.forum_public = true
end
context "TopicsController" do
should "create topic" do
login_as @provider.admins.first
# missing title
post :create, topic: { body: 'No idea why I wrote that.' }
assert_response :success
post :create, topic: { title: 'The king has returned!', body: 'No idea why I wrote that.' }
assert_response :redirect
end
should "update topic" do
login_as @provider.admins.first
# empty title
put :update, :id => @topic.permalink, topic: { title: '', body: 'new thing' }
assert_response :success
put :update, :id => @topic.permalink, topic: { title: 'HOT STUFF', body: 'new thing' }
assert_response :redirect
end
context "anonymous posting enabled" do
setup do
@provider.settings.anonymous_posts_enabled = true
@provider.settings.save!
end
should "anonymous have a hidden field" do
get :show, :id => @topic.permalink
assert_match @topic.body, @response.body
assert_select 'input#post_anonymous_user[type=hidden]'
end
should "provider has a field" do
login_as @provider.admins.first
get :show, :id => @topic.permalink
assert_match @topic.body, @response.body
assert_select 'input#post_anonymous_user'
end
should "buyer has a field" do
buyer = FactoryBot.create :buyer_account, :provider_account => @provider
login_as buyer.admins.first
get :show, :id => @topic.permalink
assert_match @topic.body, @response.body
assert_select 'input#post_anonymous_user'
end
end # enabled
context "anonymous posting when disabled" do
setup do
@provider.settings.anonymous_posts_enabled = false
@provider.settings.save!
end
should "not have fields for anonymous" do
get :show, :id => @topic.permalink
assert_match @topic.body, @response.body
assert_select 'input#post_anonymous_user', count: 0
end
should "not have fields when logged in as a provider" do
login_as @provider.admins.first
get :show, :id => @topic.permalink
assert_match @topic.body, @response.body
assert_select 'input#post_anonymous_user', count: 0
end
should "have no field when logged in as a buyer" do
buyer = FactoryBot.create :buyer_account, :provider_account => @provider
login_as buyer.admins.first
get :show, :id => @topic.permalink
assert_match @topic.body, @response.body
assert_select 'input#post_anonymous_user', count: 0
end
end # disabled
end
test 'list posts within topic ascendingly: oldest on the top' do
@topic.posts.delete_all
post1 = FactoryBot.create(:post, topic: @topic, user_id: 99, created_at: 10.days.ago)
post2 = FactoryBot.create(:post, topic: @topic, user_id: 88, created_at: 1.day.ago)
get :show, :id => @topic.permalink
posts = assigns(:posts)
assert_equal [post1, post2], posts.to_a
assert_equal posts.first, post1
assert_equal posts.last, post2
end
end
|
class CreateCategories < ActiveRecord::Migration[5.2]
def change
create_table :categories do |t|
t.string :name
t.references :project, foreign_key: {on_delete: :cascade}
t.integer :taskIds, array: true, default: []
t.timestamps
end
end
end
|
class Stock < ActiveRecord::Base
belongs_to :almacen
belongs_to :item
end
|
# encoding: binary
# frozen_string_literal: true
module RbNaCl
module Boxes
class Curve25519XSalsa20Poly1305
# RbNaCl::Box private key. Keep it safe
#
# This class generates and stores NaCL private keys, as well as providing a
# reference to the public key associated with this private key, if that's
# provided.
#
# Note that the documentation for NaCl refers to this as a secret key, but in
# this library its a private key, to avoid confusing the issue with the
# SecretBox, which does symmetric encryption.
class PrivateKey
include KeyComparator
include Serializable
extend Sodium
sodium_type :box
sodium_primitive :curve25519xsalsa20poly1305
sodium_function :box_curve25519xsalsa20poly1305_keypair,
:crypto_box_curve25519xsalsa20poly1305_keypair,
%i[pointer pointer]
# The size of the key, in bytes
BYTES = Boxes::Curve25519XSalsa20Poly1305::PRIVATEKEYBYTES
# Initializes a new PrivateKey for key operations.
#
# Takes the (optionally encoded) private key bytes. This class can then be
# used for various key operations, including deriving the corresponding
# PublicKey
#
# @param private_key [String] The private key
#
# @raise [TypeError] If the key is nil
# @raise [RbNaCl::LengthError] If the key is not valid after decoding.
#
# @return A new PrivateKey
def initialize(private_key)
@private_key = Util.check_string(private_key, BYTES, "Private key")
end
# Generates a new keypair
#
# @raise [RbNaCl::CryptoError] if key generation fails, due to insufficient randomness.
#
# @return [RbNaCl::PrivateKey] A new private key, with the associated public key also set.
def self.generate
pk = Util.zeros(Boxes::Curve25519XSalsa20Poly1305::PUBLICKEYBYTES)
sk = Util.zeros(Boxes::Curve25519XSalsa20Poly1305::PRIVATEKEYBYTES)
box_curve25519xsalsa20poly1305_keypair(pk, sk) || raise(CryptoError, "Failed to generate a key pair")
new(sk)
end
# The raw bytes of the key
#
# @return [String] the raw bytes.
def to_bytes
@private_key
end
# the public key associated with this private key
#
# @return [PublicKey] the key
def public_key
@public_key ||= PublicKey.new GroupElements::Curve25519.base.mult(to_bytes)
end
# The crypto primitive this PrivateKey is to be used for.
#
# @return [Symbol] The primitive
def primitive
self.class.primitive
end
end
end
end
end
|
module HasSeason
extend ActiveSupport::Concern
included do
belongs_to :season
end
end
|
#
# Cookbook Name:: vim
# Recipe:: default
#
# Copyright 2015, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
%w{
mercurial
gettext
libncurses5-dev
libacl1-dev
libgpm-dev
}.each do |pc|
package pc do
action :install
end
end
def install_vim(repo, branch, build_dir, prefix)
bash "install-vim #{build_dir}" do
user "root"
cwd Chef::Config[:file_cache_path]
code <<-EOH
set -ex
hg clone #{repo} #{build_dir}
cd #{build_dir}
hg pull
hg update -r #{branch}
./configure --with-features=huge --prefix=#{prefix}
make
make install
cd ../
rm -r #{build_dir}
EOH
not_if "test -e #{prefix}/bin/vim"
end
end
def install_vim_git(repo, branch, build_dir, prefix)
bash "install-vim #{build_dir}" do
user "root"
cwd Chef::Config[:file_cache_path]
code <<-EOH
set -ex
git clone #{repo} #{build_dir}
cd #{build_dir}
git reset --hard #{branch}
./configure --with-features=huge --prefix=#{prefix}
make
make install
cd ../
rm -r #{build_dir}
EOH
not_if "test -e #{prefix}/bin/vim"
end
end
install_vim(
'https://vim.googlecode.com/hg/',
'v7-4-729',
'vim-7.4.729',
'/usr/local/vim-7.4.729')
install_vim_git(
'https://github.com/vim/vim.git',
'v7.4.1714',
'vim-7.4.1714',
'/usr/local/vim-7.4.1714')
|
class Enigma
attr_reader :character_set
def initialize
@character_set = ("a".."z").to_a << " "
end
def key(key_string)
key_array = []
key_sep = key_string.chars
4.times do |index|
key_array << (key_sep[index] + key_sep[index + 1]).to_i
end
key_array
end
def offset(date)
offset = (date.to_i ** 2).to_s[-4..-1]
offset_sep = offset.chars
offset_sep.map do |number|
number.to_i
end
end
def shift(key, offset)
shifts = []
4.times do |index|
shifts << offset[index] + key[index]
end
shifts
end
def encrypt_message(message, shift)
message = message.downcase
array = message.split("").map do |character|
character
end
array.map.with_index do |letter, index|
if @character_set.index(letter) == nil
letter
else
letter_index = @character_set.index(letter)
rotated = @character_set.rotate(shift[index % 4])
rotated[letter_index]
end
end.join
end
def date_to_string
date = Time.now.strftime("%d%m%y").to_i
last_digits = (date.to_s)[-4..-1]
end
def encrypt(message, key = '%05d' % rand(100000), date = date_to_string)
key_code = key(key)
offset_code = offset(date)
shift_code = shift(key_code, offset_code)
encrypted_message = encrypt_message(message, shift_code)
hash = {:encryption => encrypted_message,
:key => key,
:date => date}
end
def decrypt_message(message, shift)
array = message.split("").map do |character|
character
end
array.map.with_index do |letter, index|
if @character_set.index(letter) == nil
letter
else
letter_index = @character_set.index(letter)
rotated = @character_set.rotate(-(shift[index % 4]))
rotated[letter_index]
end
end.join
end
def decrypt(message, key, date)
key_code = key(key)
offset_code = offset(date)
shift_code = shift(key_code, offset_code)
decrypted_message = decrypt_message(message, shift_code)
hash = {:decryption => decrypted_message,
:key => key,
:date => date}
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Flat.create!(
name: 'Light & Spacious Garden Flat London',
address: '10 Clifton Gardens London W9 1DT',
description: 'A lovely summer feel for this spacious garden flat. Two double bedrooms, open plan living area, large kitchen and a beautiful conservatory',
price_per_night: 75,
number_of_guests: 3
)
Flat.create!(
name: 'Charm at the Steps of the Sacre Coeur/Montmartre',
address: '12 rue de la Liberte 75019 Paris France',
description: 'A lovely summer feel for this lovely flat. One double bedroom, fully-equiped kitchen',
price_per_night: 65,
number_of_guests: 2
)
Flat.create!(
name: 'Villa with Sunny Pateo and amazing River View',
address: '10 Rua das Escolas Gerais 1100-080 Lisboa',
description: 'Lovely villa, ideal for youth groups and families with a unique spacious outdoor area!',
price_per_night: 180,
number_of_guests: 5
)
Flat.create!(
name: 'Romantic, Lakeside Home with Views of Lake Como',
address: '14 Via Gianella, 1 22011 Griante CO Italia',
description: 'Wake up to stunning views of Lake Como from every window of this romantic home.',
price_per_night: 120,
number_of_guests: 4
)
|
class AddColumnItemtypeToBillableItem < ActiveRecord::Migration
def change
add_column :billable_items , :item_type , :boolean , :default=> true
add_column :billable_items , :concession_price , :text
end
end
|
require 'rails_helper'
#
# Property's route path is to account
# Tests for creating charges onto a property have been moved to
# charge_create_spec.rb
#
RSpec.describe 'Property#Update', type: :system do
let(:account) { AccountPage.new }
context 'when Agentless' do
before do
log_in
property_create id: 1,
human_ref: 80,
account: account_new,
client: client_new(human_ref: 90)
end
it 'opens valid page', js: true, elasticsearch: true do
account.load id: 1
expect(account.title).to eq 'Letting - Edit Account'
account.expect_property self,
property_id: '80',
client_id: Client.first.id
account.expect_address self,
type: '#property_address',
address: address_new
account.expect_entity self, type: 'property', **person_attributes
end
it 'updates account', js: true, elasticsearch: true do
new_client = client_create(human_ref: 101)
account.load id: 1
account.property property_id: '81', client_ref: '101'
account.address selector: '#property_address', address: address_new
account.entity type: 'property', **company_attributes
account.button('Update').successful?(self).load id: 1
account.expect_property self, property_id: '81', client_id: new_client.id
account.expect_address self,
type: '#property_address',
address: address_new
account.expect_entity self, type: 'property', **company_attributes
end
it 'adds agent', js: true, elasticsearch: true do
account.load id: 1
check 'Agent'
account.address selector: '#agent', address: address_new
account.entity type: 'property_agent_attributes', **company_attributes
account.button('Update').successful?(self).load id: 1
expect(find_field('Agent')).to be_checked
account.expect_address self,
type: '#property_agent_address',
address: address_new
account.expect_entity self,
type: 'property_agent_attributes',
**company_attributes
end
it 'displays form errors' do
account.load id: 1
account.address selector: '#property_address',
address: address_new(road: '')
account.button 'Update'
expect(page).to have_css '[data-role="error_messages"]'
end
end
context 'when Agentless with charge' do
before { log_in }
it 'can be set to dormant', js: true, elasticsearch: true do
property_create \
id: 1, account: account_new(charges: [charge_new(activity: 'active')])
account.load id: 1
activity =
'//*[@id="property_account_attributes_charges_attributes_0_activity"]'
expect(find(:xpath, activity).value).to eq 'active'
find(:xpath, activity).select 'dormant'
account.button('Update').successful?(self).load id: 1
expect(find(:xpath, activity).value).to eq 'dormant'
end
end
context 'with Agent' do
before do
log_in
agent = agent_new entities: [Entity.new(name: 'Willis')],
address: address_new(road: 'Wiggiton')
property_create id: 1, account: account_new, agent: agent
account.load id: 1
end
it 'opens property with agent', js: true, elasticsearch: true do
expect(find_field('Agent')).to be_checked
account.expect_address self,
type: '#property_agent_address',
address: address_new(road: 'Wiggiton')
account.expect_entity(self,
type: 'property_agent_attributes',
name: 'Willis')
end
it 'updates agent' do
account.address(selector: '#agent', address: address_new)
account.entity(type: 'property_agent_attributes', **company_attributes)
account.button('Update').successful?(self).load id: 1
account.expect_address self,
type: '#property_agent_address',
address: address_new
account.expect_entity(self,
type: 'property_agent_attributes',
**company_attributes)
end
it 'removes agent' do
uncheck 'Agent'
account.button('Update').successful?(self).load id: 1
expect(find_field('Agent')).not_to be_checked
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
########################
# #
# Database Cleaning #
# #
########################
puts "Cleaning database..."
User.destroy_all
Question.destroy_all
puts "Database cleaned! "
########################
# #
# 'Manual' Questions #
# #
########################
puts "Making default 'seeded from humor sites' questions... "
quest = Question.new(content: 'learn how to code')
quest.save!
answers = []
answers << ['for free', 1]
answers << ['online', 2]
answers << ['apps', 3]
answers << ['python', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'shark vs')
quest.save!
answers[0] = ['octopus', 1]
answers[1] = ['eagle', 2]
answers[2] = ['dyson', 3]
answers[3] = ['orca', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'coke is better than')
quest.save!
answers[0] = ['pepsi', 1]
answers[1] = ['coal', 2]
answers[2] = ['water', 3]
answers[3] = ['crack', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'can i eat my')
quest.save!
answers[0] = ['poop', 1]
answers[1] = ['salt lamp', 2]
answers[2] = ['aloe plant', 3]
answers[3] = ['steak medium while preg...', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'why isn\'t 11')
quest.save!
answers[0] = ['a prime number', 1]
answers[1] = ['pronounced onety one', 2]
answers[2] = ['pronounced oneteen', 3]
answers[3] = ['pronounced onety one meme', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
puts "Five so far."
quest = Question.new(content: 'why can\'t')
quest.save!
answers[0] = ['we live together', 1]
answers[1] = ['we be friends', 2]
answers[2] = ['this be love', 3]
answers[3] = ['i cry', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'why I always')
quest.save!
answers[0] = ['feel tired', 1]
answers[1] = ['feel sleepy', 2]
answers[2] = ['fart', 3]
answers[3] = ['feel cold', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'where to donate a')
quest.save!
answers[0] = ['mattress', 1]
answers[1] = ['car', 2]
answers[2] = ['couch', 3]
answers[3] = ['piano', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'when i jump i')
quest.save!
answers[0] = ['wet myself', 1]
answers[1] = ['can hear water', 2]
answers[2] = ['pee a little', 3]
answers[3] = ['hear water', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'why is my gold')
quest.save!
answers[0] = ['-fish turning black', 1]
answers[1] = ['-fish floating', 2]
answers[2] = ['-fish dying', 3]
answers[3] = ['-fish swimming sideways', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
puts "We're up to 10 now."
quest = Question.new(content: 'what\'s a boyfriend')
quest.save!
answers[0] = ['jeans', 1]
answers[1] = ['and where can i download', 2]
answers[2] = ['supposed to do', 3]
answers[3] = ['shirt', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'what if google was')
quest.save!
answers[0] = ['a guy', 1]
answers[1] = ['a person', 2]
answers[2] = ['deleted', 3]
answers[3] = ['not there', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'how do i convert to')
quest.save!
answers[0] = ['islam', 1]
answers[1] = ['judaism', 2]
answers[2] = ['pdf', 3]
answers[3] = ['catholicism', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'how come a ')
quest.save!
answers[0] = ['bed has four legs but ...', 1]
answers[1] = ['baby doesn\'t drown in ..', 2]
answers[2] = ['snowman\'s never dressed', 3]
answers[3] = ['website won\'t load', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'help I\'m a p')
quest.save!
answers[0] = ['-risoner in the library', 1]
answers[1] = ['-risoner in a chinese', 2]
answers[2] = ['-arent', 3]
answers[3] = ['-risoner in a toothpaste', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
puts "15 woop woop"
quest = Question.new(content: 'don\'t you hate it when a')
quest.save!
answers[0] = ['sentence doesn\'t end ...', 1]
answers[1] = ['llama named carl', 2]
answers[2] = ['chinchilla eats the ...', 3]
answers[3] = ['velociraptor throws', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'is it normal to')
quest.save!
answers[0] = ['cry everyday', 1]
answers[1] = ['have suicidal thoughts', 2]
answers[2] = ['feel your heartbeat', 3]
answers[3] = ['be attracted to numbers', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'my girlfriend')
quest.save!
answers[0] = ['is a gal', 1]
answers[1] = ['is alien', 2]
answers[2] = ['is a gumiho', 3]
answers[3] = ['is a big magnet', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'dinosaurs were')
quest.save!
answers[0] = ['made up by the cia', 1]
answers[1] = ['birds', 2]
answers[2] = ['the dominant land animal', 3]
answers[3] = ['definitely cold blooded', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
quest = Question.new(content: 'is it bad')
quest.save!
answers[0] = ['that i never made love', 1]
answers[1] = ['to crack your neck', 2]
answers[2] = ['to swallow gum', 3]
answers[3] = ['to crack your back', 4]
answers.each do |answer|
ansi = Answer.new(rank: answer[1], content: answer[0], question_id: quest.id)
ansi.save!
end
puts "20 Seeds - Done basic questions one!"
#########################
# #
# 'Dynamic' Questions #
# #
#########################
puts 'Time to dynamically seed questions!'
puts 'Preparing required libaries...'
require 'nokogiri'
require 'open-uri'
# URL for getting the suggestions
autocomplete_url = 'https://www.google.com/complete/search?output=toolbar&q='
puts '...done!'
#------------------#
# Animal Questions #
#------------------#
used_questions = []
puts 'Making animal-themed questions now... '
# Animal Seed Data
animals = ['dog', 'cat', 'elephant', 'bear',
'ostrich', 'alligator', 'crocodile',
'horse', 'zebra', 'crab', 'lion', 'fish' ]
animals_plural = animals.map { |animal| animal.pluralize }
animal_plural_appends = ['are', 'do', 'vs', 'have']
# ----
# 10 times with with prepends...
# ----
animal_prepends = ['baby', 'cute', 'flying']
10.times do
# Build new search query, create question, and save it.
test_query = "#{animal_prepends.sample} #{animals.sample} "
while used_questions.include?("#{test_query}")
test_query = "#{question_words.sample} #{question_word_appends.sample} "
end
new_question = Question.new(content: "#{test_query}", category: "Animal")
new_question.save!
# get autocomplete results, parse them, and extract relevant data.
suggestions = open("#{autocomplete_url}#{test_query}").read
suggestions = Nokogiri::XML(suggestions)
suggestions = suggestions.root.xpath("CompleteSuggestion")[1..4]
suggestions = suggestions.map { |suggestion| suggestion.xpath('suggestion')[0]["data"] }
# Create new answers with the extracted data, and save them too.
suggestions.each_with_index do |suggestion, index|
my_rank = index + 1
suggestion = suggestion.delete_prefix(test_query)
if suggestion.length > 25
suggestion = suggestion[0, 22] + "..."
else
suggestion
end
Answer.create!(rank: my_rank, content: suggestion,
question_id: new_question.id)
end
end
puts "... completed 10 animal prepend questions..."
# ----
# 10 times, singular with w/ appends
# ----
animal_appends = ['with', 'vs', 'in', 'wearing']
10.times do
# Build new search query, create question, and save it.
test_query = "#{animals.sample} #{animal_appends.sample} "
while used_questions.include?("#{test_query}")
test_query = "#{question_words.sample} #{question_word_appends.sample} "
end
new_question = Question.new(content: "#{test_query}", category: "Animal")
new_question.save!
# get autocmplete results, parse them, and extract relevant data.
suggestions = open("#{autocomplete_url}#{test_query}").read
suggestions = Nokogiri::XML(suggestions)
suggestions = suggestions.root.xpath("CompleteSuggestion")[1..4]
suggestions = suggestions.map { |suggestion| suggestion.xpath('suggestion')[0]["data"] }
# Create new answers with the extracted data, and save them too.
suggestions.each_with_index do |suggestion, index|
my_rank = index + 1
suggestion = suggestion.delete_prefix(test_query)
if suggestion.length > 25
suggestion = suggestion[0, 22] + "..."
else
suggestion
end
Answer.create!(rank: my_rank, content: suggestion,
question_id: new_question.id)
end
end
puts "... completed 10 animals singular w/ append questions..."
# ----
# 10 times, plural w/ appends
# ----
animal_plural_appends = ['are', 'do', 'vs', 'have']
10.times do
# Build new search query, create question, and save it.
test_query = "#{animals_plural.sample} #{animal_plural_appends.sample} "
while used_questions.include?("#{test_query}")
test_query = "#{question_words.sample} #{question_word_appends.sample} "
end
new_question = Question.new(content: "#{test_query}", category: "Animal")
new_question.save!
# get autocmplete results, parse them, and extract relevant data.
suggestions = open("#{autocomplete_url}#{test_query}").read
suggestions = Nokogiri::XML(suggestions)
suggestions = suggestions.root.xpath("CompleteSuggestion")[1..4]
suggestions = suggestions.map { |suggestion| suggestion.xpath('suggestion')[0]["data"] }
# Create new answers with the extracted data, and save them too.
suggestions.each_with_index do |suggestion, index|
my_rank = index + 1
suggestion = suggestion.delete_prefix(test_query)
if suggestion.length > 25
suggestion = suggestion[0, 22] + "..."
else
suggestion
end
Answer.create!(rank: my_rank, content: suggestion,
question_id: new_question.id)
end
end
puts "... completed 10 animals plural w/ append questions..."
puts "done seeding animal questions!"
#--------------------------------#
# "General Knowledge" Questions #
#--------------------------------#
# General Knowledge Seed Data
question_words = ['how', 'what', 'where', 'why', 'when', 'who']
question_word_appends = ['can', 'do', 'did', 'are', 'is', 'was',
'do we', 'did we', 'are you', 'was i']
15.times do
# Build new search query, create question, and save it.
test_query = "#{question_words.sample} #{question_word_appends.sample} "
while used_questions.include?("#{test_query}")
test_query = "#{question_words.sample} #{question_word_appends.sample} "
end
used_questions << test_query
new_question = Question.new(content: "#{test_query}", category: "Open-Ended")
new_question.save!
# get autocmplete results, parse them, and extract relevant data.
suggestions = open("#{autocomplete_url}#{test_query}").read
suggestions = Nokogiri::XML(suggestions)
suggestions = suggestions.root.xpath("CompleteSuggestion")[1..4]
suggestions = suggestions.map { |suggestion| suggestion.xpath('suggestion')[0]["data"] }
# Create new answers with the extracted data, and save them too.
suggestions.each_with_index do |suggestion, index|
my_rank = index + 1
suggestion = suggestion.delete_prefix(test_query)
if suggestion.length > 25
suggestion = suggestion[0, 22] + "..."
else
suggestion
end
Answer.create!(rank: my_rank, content: suggestion,
question_id: new_question.id)
end
end
puts "... completed 15 general knowledge questions ..."
puts "Done with ALL questions!"
puts "#{Question.all.count} total questions!"
puts "#{Answer.all.count} total answers! Yay!"
# # Question Generation Loop
# test_query = "#{animals.sample} #{animal_appends.sample} "
# suggestions_xml = open("#{autocomplete_url}#{test_query}").read
# parsed_xml = Nokogiri::XML(suggestions_xml)
# complete_suggestions = parsed_xml.root.xpath("CompleteSuggestion")
# complete_suggestions.each do |c_suggest|
# puts c_suggest.xpath('suggestion')[0]["data"]
# end
# p suggestions_xml
# p parsed_xml
###########
# #
# Users #
# #
###########
puts "Making users ... "
seed_users = ['tryout_guy',
'Lassie',
'Flipper',
'Secretariat',
'Billy',
'Brownie',
'Big_Bird',
'Willy',
'KingKong']
seed_users.each do |name|
User.create!(email: "#{name}@partly.com",
username: "#{name}",
password: '111111')
end
puts 'Done with Users!'
####################
# #
# Games / Rounds #
# #
####################
puts 'Creating empty games for users...'
puts '...'
puts '(... psttt... skipping games... go play yourself!! :D! ...)'
puts '...'
# # Config options...
# allowed_game_types = ['Try Out']
# number_of_games = 15
# # Prep...
# all_users = User.all
# questions = Question.all.sample(number_of_games)
# seed_games = []
# p 'Creating empty games... '
# number_of_games.times do
# seed_games << Game.create!(game_mode: allowed_game_types.sample,
# user_id: all_users.sample.id)
# end
# puts '... done!'
# p 'Creating rounds for games, getting answers, and scoring them...'
# seed_games.each do |game|
# question = questions.pop
# answer = question.answers.sample
# duration = rand(95000) + 500 # ==> Random time from .5 to 10 seconds,in ms
# user = all_users.sample
# Round.create!( game_id: game.id,
# question_id: question.id,
# answer_id: answer.id,
# duration: duration)
# game.score = answer.rank == 1 ? 1 : 0
# end
puts '... done! Happy testing!'
|
# Fact: infiniband_hcas
#
# Purpose: Determine list of Infiniband HCAs
#
# Resolution:
# Returns Array of HCA names.
#
require 'facter/util/infiniband'
Facter.add(:infiniband_hcas) do
confine has_infiniband: true
setcode do
hcas = Facter::Util::Infiniband.hcas
if hcas.empty?
nil
else
hcas
end
end
end
|
require File.join(File.dirname(__FILE__), '..', "spec_helper")
require "rspec/matchers/dm/has_property"
describe DataMapperMatchers::HasProperty do
it "should pass with the property type" do
Post.should has_property :title, String
end
it "should fail with improper property type" do
lambda {Post.should has_property :title, Integer}.should fail_with("expected title to have type of Integer but has String")
end
end |
# == Schema Information
#
# Table name: players
#
# id :integer not null, primary key
# session_id :integer not null
# player_number :integer
# name :string(255)
# logged_in :integer
# updated_at :datetime
# chosen_card :integer
#
class Player < ActiveRecord::Base
belongs_to :game
has_many :messages
end
|
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/xenial64"
config.vm.provider "virtualbox" do |vb|
# Display the VirtualBox GUI when booting the machine
vb.gui = true
# Customize the amount of memory and CPU on the VM:
vb.cpus = 2
vb.memory = "2048"
end
config.vm.provision "shell" do |s|
s.inline = "timedatectl set-timezone Asia/Tokyo"
s.inline = "sudo apt-get update"
end
config.vm.provision "shell", path: "provision/user_add.sh"
config.vm.provision "shell", path: "provision/git.sh"
config.vm.provision "shell", path: "provision/ubuntu_mate_desktop.sh"
end
|
require 'mysql'
# A few bits to make Mysql easier to use
#
class Mysql
alias :raw_query :query
def query(sql, &block)
begin
if block.nil?
raw_query(sql)
else
raw_query(sql) { |result| block.call(result) }
end
rescue => err
puts err
puts sql
raise
end
end
def self.open(u, pw, db, host = 'localhost')
begin
mysql = self.new(host, u, pw, db)
yield mysql
ensure
mysql.close if mysql
end
end
class Result
def fetch_all(flat = true)
collection = []
self.each do |array|
collection << array
end
flat ? collection.flatten : collection
end
end
end
|
#!/usr/bin/env ruby
# Signal that we're starting Rails for the Log analyser
# Which will mean the plugin init will do the requires
$LOG_ANALYSER = true
# How we signal the analyser to stop when a signal is received
$RUNNING = true
# Flag for File::Tail library
# $DEBUG = true
# Start rails environment; need to find environment.rb
rails_root = "#{File.dirname(__FILE__)}/../../../../.."
require "#{rails_root}/config/environment"
# Include support methods for the analyser
include Daemons::AnalyserSupport
TRACKER_LOG_FORMAT = [:ip_address, :remote, :user, :time, :request, :status, :size, :referer, :user_agent, :forwarded_for, :request_time]
logger.info "[Log Analyser] Starting at #{Time.now}."
tailer = LogTailer.new
parser = Analytics::LogParser.new(:format => TRACKER_LOG_FORMAT)
# This is where the real work begins. Tail the log, parse each entry into
# a hash and pass the hash to the analyser. The analyser builds an object
# that is then passed for serializing to the database into Session and Event
tailer.tail do |log_line|
parser.parse(log_line) do |log_attributes|
next if log_attributes[:datetime] < last_logged_entry
ActiveRecord::Base.verify_active_connections!
Analytics::TrackEvent.analyse(log_attributes) do |track|
begin
Session.transaction do
raise Trackster::InvalidSession unless session = Session.find_or_create_from(track)
# extract_internal_search_terms!(track, session, web_analyser)
raise Trackster::InvalidEvent unless event = session.events.create_from(track)
end
rescue Trackster::InvalidEvent
logger.error "[Log Analyser] Event could not be created. URL: #{track.url}"
rescue Trackster::InvalidSession
logger.error "[Log Analyser] Sesssion was not found or created. Unknown web property? URL: '#{track.url}'"
rescue Mysql::Error => e
logger.warn "[Log Analyser] Database could not save this data: #{e.message}"
logger.warn track.inspect
rescue ActiveRecord::RecordInvalid => e
logger.error "[Log Analyser] Invalid record detected: #{e.message}"
logger.error track.inspect
end
end
end
end
logger.info "[Log Analyser] Ending at #{Time.now}." |
class CreateProductImages < ActiveRecord::Migration
def up
create_table "product_images" do |t|
t.integer "product_id"
t.integer "image_file_size"
t.string "image_file_name"
t.string "image_content_type"
t.integer "list_order"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "product_images", ["list_order"], :name => "index_product_images_on_list_order"
add_index "product_images", ["product_id"], :name => "index_product_images_on_product_id"
end
def down
drop_table :product_images
end
end |
class DashboardsController < ApplicationController
def show
@counts = {}
@counts[:companies] = Company.count
end
end
|
require File.join(File.dirname(__FILE__), '..', 'question_1.rb')
describe CharacterFrequency do
context "given an array of charactes" do
let(:input){ ['a', 'a', 'b', 'c', 'b', 'd', 'c', 'c'] }
it "shows frequency of each character" do
expect(CharacterFrequency.new(input).to_hash).to eq({'a' => 2, 'b' => 2, 'c' => 3, 'd' => 1})
end
end
context "given an input that is not an array" do
let(:input) { "string" }
it "raise InvalidParameter error" do
expect{CharacterFrequency.new(input)}.to raise_error(CharacterFrequency::InvalidParameter)
end
end
end
|
require 'spec_helper'
module OCR
describe AccountReader do
Given(:input_io) { StringIO.new(input) }
Given(:reader) { AccountReader.new(input_io) }
context "with a single scanned number" do
When(:result) { reader.read_account_number }
context "terminated by an end of file" do
Given(:input) {
" _ \n" +
"|_ \n" +
" _|\n"
}
Then { expect(result).to eq ScannedNumber.from_digits("5") }
end
context "terminated by a a blank line" do
Given(:input) {
" _ \n" +
"|_ \n" +
" _|\n" +
"\n"
}
Then { expect(result).to eq ScannedNumber.from_digits("5") }
end
context "with some lines shortened due to trailing blanks" do
Given(:input) {
" _\n" +
"|_ \n" +
" _|\n" +
"\n"
}
Then { expect(result).to eq AccountNumber.from_digits("5") }
end
context "beginning with a line containing spaces" do
Given(:input) {
" \n" +
" |\n" +
" |\n" +
"\n"
}
Then { expect(result).to eq AccountNumber.from_digits("1") }
end
context "containing multiple numerals" do
Given(:input) {
" _ _ \n" +
" | _| _|\n" +
" ||_ _|\n" +
"\n"
}
Then { expect(result).to eq AccountNumber.from_digits("123") }
end
context "when there is no scanned number" do
Given(:input) { "" }
Then { expect(result).to be_nil }
end
end
context "with multiple account numbers" do
Given(:validate) { true }
Given(:input) {
" _ _ _ _ _ _ _ \n" +
" | _| _||_||_ |_ ||_||_|\n" +
" ||_ _| | _||_| ||_| _|\n" +
"\n" +
" _ _ _ _ _ _ _ _ \n" +
"| || || || || || || ||_ |\n" +
"|_||_||_||_||_||_||_| _| |\n" +
"\n"
}
When(:result) { reader.to_a }
Then { expect(result).to eq [
AccountNumber.from_digits("123456789"),
AccountNumber.from_digits("000000051"),
]
}
end
end
end
|
FactoryGirl.define do
factory :office, class: Office do
name "Sede Iuvare"
address "Corporativo Nápoles"
latitude "19.3838687"
longitude "-99.1807992"
description "Oficinas Corporativas"
schedule "Lunes a Viernes - 8:00pm"
end
end
|
require 'rails_helper'
RSpec.describe PlaceOrderService do
before :each do
stub_price_limit
stub_place_order
stub_order_info
stub_contract_info
stub_contract_balance
stub_user_current_position
stub_user_history
@trader = Trader.create!(webhook_token: 'oo', email: 'a@b.com', password: 'oooppp')
@user = User.create!(
email: 'foo@bar.com',
password: 'abcdabcd',
huobi_access_key: 'oo',
huobi_secret_key: 'ooo',
trader_id: @trader.id
)
end
context '.lever_rate' do
it 'works' do
order_execution = OrderExecution.create!(
currency: 'BTC',
direction: 'buy',
user_id: @user.id,
exchange_id: 'huobi',
trader_id: @trader.id,
action: 'open_position'
)
exchange = Exchange::Huobi.new(@user, 'BTC')
service = PlaceOrderService.new(@user, order_execution)
expect(service.lever_rate).to eq(100)
expect(service.balance).to eq('68.839155724155396568'.to_d)
expect(service.open_position_service.open_order_percentage).to eq('0.005'.to_d)
expect(service.open_position_service.contract_price).to eq('38.5672'.to_d)
expect(service.open_position_service.calculate_open_position_volume).to eq(1)
end
end
it 'no position' do
stub_user_no_current_position
order_execution = OrderExecution.create!(
currency: 'BTC',
direction: 'buy',
user_id: @user.id,
exchange_id: 'huobi',
trader_id: @trader.id,
action: 'open_position'
)
PlaceOrderService.new(@user, order_execution).execute
# order
expect(UsdtStandardOrder.count).to eq(1)
order = UsdtStandardOrder.last
expect(order.direction).to eq('buy')
expect(order.remote_status).to eq(6)
expect(order.remote_order_id).to eq(845810451073155072)
# order execution
order_execution = OrderExecution.last
expect(order_execution.status).to eq('done')
log = OrderExecutionLog.find_by(action: 'open_position')
expect(log.meta).to eq({"balance"=>"68.839155724155396568", "lever_rate"=>100, "contract_price"=>"38.5672", "open_order_percentage"=>"0.005"})
end
it 'works' do
order_execution = OrderExecution.create!(
currency: 'BTC',
direction: 'buy',
user_id: @user.id,
exchange_id: 'huobi',
trader_id: @trader.id,
action: 'open_position'
)
PlaceOrderService.new(@user, order_execution).execute
log = OrderExecutionLog.last
expect(log.action).to eq('skip_execution_same_direction')
end
it 'has open order' do
first_order = UsdtStandardOrder.create!(
volume: 3,
client_order_id: 3323,
remote_order_id: 232332,
order_execution_id: nil,
contract_code: 'BTC-USDT',
direction: 'buy',
offset: 'open',
lever_rate: 5,
order_price_type: 'opponent',
open_price: 10,
close_price: 20,
user_id: @user.id,
exchange_id: 'huobi'
)
order_execution = OrderExecution.create!(
currency: 'BTC',
direction: 'sell',
user_id: @user.id,
exchange_id: 'huobi',
trader_id: @trader.id,
action: 'open_position'
)
exchange = Exchange::Huobi.new(@user, 'BTC')
PlaceOrderService.new(@user, order_execution).execute
# update exist open order
first_order.reload
expect(first_order.offset).to eq('open')
expect(first_order.direction).to eq('buy')
# close exist order
second_order = UsdtStandardOrder.all.order(:id)[1]
expect(second_order.offset).to eq('close')
expect(second_order.direction).to eq('sell')
expect(second_order.remote_status).to eq(6)
expect(second_order.profit).to eq(-0.3854.to_d)
expect(second_order.order_execution_id).to eq(order_execution.id)
# place new order
last_order = UsdtStandardOrder.all.order(:id)[2]
expect(last_order.parent_order_id).to eq(nil)
expect(last_order.remote_status).to eq(6)
expect(last_order.offset).to eq('open')
expect(last_order.direction).to eq('sell')
end
context 'open_order_percentage' do
it 'works' do
UsdtStandardOrder.create!(
volume: 3,
client_order_id: 3323,
remote_order_id: 232332,
order_execution_id: nil,
contract_code: 'BTC-USDT',
direction: 'buy',
offset: 'close',
lever_rate: 5,
order_price_type: 'opponent',
open_price: 10,
close_price: 20,
real_profit: -3,
user_id: @user.id,
status: 'done',
exchange_id: 'huobi'
)
UsdtStandardOrder.create(
volume: 3,
client_order_id: 33231,
remote_order_id: 232332,
order_execution_id: nil,
contract_code: 'BTC-USDT',
direction: 'sell',
offset: 'close',
lever_rate: 5,
order_price_type: 'opponent',
open_price: 10,
close_price: 20,
real_profit: 3,
user_id: @user.id,
status: 'done',
exchange_id: 'huobi'
)
UsdtStandardOrder.create(
volume: 3,
client_order_id: 332323,
remote_order_id: 232332,
order_execution_id: nil,
contract_code: 'BTC-USDT',
direction: 'sell',
offset: 'close',
lever_rate: 5,
order_price_type: 'opponent',
open_price: 10,
close_price: 20,
real_profit: -3,
user_id: @user.id,
status: 'done',
exchange_id: 'huobi'
)
order_execution = OrderExecution.create!(
currency: 'BTC',
direction: 'buy',
user_id: @user.id,
exchange_id: 'huobi',
trader_id: @trader.id,
action: 'open_position'
)
service = PlaceOrderService.new(@user, order_execution)
expect(service.open_position_service.send(:open_order_percentage)).to eq(0.005.to_d)
end
end
end
|
class DissectionsController < ApplicationController
respond_to :html, :js
def index
@dissections = Dissection.all
end
def show
@dissection = Dissection.find(params[:id])
end
def new
@dissection = Dissection.new
end
def edit
@dissection = Dissection.find(params[:id])
end
def create
@dissection = Dissection.new(dissection_params)
if @dissection.save
flash[:success] = "Successfully added #{find_trail(print_if_present(@dissection.topic.name))}"
redirect_to :back
else
flash[:danger] = "Please re-check information: #{@dissection.errors.full_messages}"
end
end
def update
@dissection = Dissection.find(params[:id])
if @dissection.update(dissection_params)
flash[:success] = "Successfully updated dissection #{find_trail(@dissection.topic_id)}"
redirect_to session[:back_to] ||= request.referer
else
flash[:danger] = "Error updating dissection: #{@dissection.errors.full_messages}"
redirect_to edit_dissection_path(@dissection.id)
end
end
def destroy
@dissection = Dissection.find(params[:id])
@dissection.destroy
flash[:success] = "Dissection #{@dissection.id} for #{find_trail(@dissection.topic_id)} deleted from record"
redirect_to session[:back_to] ||= request.referer
end
def back_url
request.referer
end
private
def dissection_params
params.require(:dissection).permit(
:patient_id,
:visit_id,
:topic_id,
:date,
:time_ago_amount,
:time_ago_scale,
:transcript,
:protein,
:variant,
:exons,
:lab_classification,
:clinical_classification,
:predictive_testing_recommended,
:lab_name,
:attachment,
:note
)
end
def current_dissection
@dissection = dissection.find(params[:id])
end
end
|
module Api
module V1
class ProfilController < ApplicationController
before_action :set_profil, only: [:show, :edit, :update, :destroy]
# GET /profils
# GET /profils.json
def index
@profil = Profil.find(params[:user_id])
render json: @profil
end
# POST /profils
# POST /profils.json
def create
@profil = Profil.new(profil_params)
respond_to do |format|
if @profil.save
format.html { redirect_to @profil, notice: 'Profil was successfully created.' }
format.json { render :show, status: :created, location: @profil }
else
format.html { render :new }
format.json { render json: @profil.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_profil
@profil = Profil.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def profil_params
params[:profil]
end
end
end
end |
class User < ActiveRecord::Base
has_secure_password
attr_accessible :login, :password_digest
validates :login, presence: true,
uniqueness: true,
length: { within: 4..32 }
validates :password, presence: true,
length: { within: 5..64 },
on: :create
def name
login.to_s.capitalize
end
def quizzes
Quizzes.where(user_id: id)
end
end
|
class RemoveFileAndFileFileNameFromBooks < ActiveRecord::Migration
def up
remove_column :books, :file
remove_column :books, :file_file_name
end
def down
end
end
|
class OrderDecorator < Draper::Decorator
decorates_association :orderable
delegate_all
def client_info
client.try{|c| c.decorate.admin_link }
end
def orderable_info
if source.orderable
h.link_to source.orderable.class.model_name.underscore.humanize, h.url_for([:admin,source])
end
end
def executors_info
h.link_to 'Исполнители', h.admin_specialists_path(order: source.id)
end
def time_to_finish
source.completion_time ? h.distance_of_time_in_words(Time.now, source.completion_time) : 'Время завершения неизвестно'
end
# Define presentation-specific methods here. Helpers are accessed through
# `helpers` (aka `h`). You can override attributes, for example:
#
# def created_at
# helpers.content_tag :span, class: 'time' do
# source.created_at.strftime("%a %m/%d/%y")
# end
# end
def border_class
orderable.border_class
end
def border_class_mild
orderable.border_class_mild
end
def completion_time
source.completion_time && I18n.l(source.completion_time)
end
end
|
# run with:
# rails new my_app -m ./lti_starter_app/template.rb
# rails new my_app -m https://raw.githubusercontent.com/atomicjolt/lti_starter_app/master/template.rb
require "fileutils"
require "securerandom"
# repo = "git@github.com:atomicjolt/lti_starter_app.git"
repo = "https://github.com/atomicjolt/lti_starter_app.git"
# repo = "git@bitbucket.com:atomicjolt/lti_starter_app.git"
# keep track if the initial directory
@working_dir = destination_root
###########################################################
#
# Overrides
#
def source_paths
paths = Array(super) +
[__dir__]
paths << @working_dir
paths
end
###########################################################
#
# Helper methods
#
def git_repo_url
@git_repo_url ||= ask_with_default("What is the Github or bitbucket remote URL for this project?", :blue, "skip")
end
def git_repo_specified?
git_repo_url != "skip" && !git_repo_url.strip.empty?
end
def gsub_file(path, regexp, *args, &block)
content = File.read(path).gsub(regexp, *args, &block)
File.open(path, "wb") { |file| file.write(content) }
end
def ask_with_default(question, color, default)
return default unless $stdin.tty?
question = (question.split("?") << " [#{default}]?").join
answer = ask(question, color)
answer.to_s.strip.empty? ? default : answer
end
def app_dir
@working_dir.split("/").last
end
###########################################################
#
# Gather information
#
app_name = app_dir
url_safe_name = app_name.parameterize.gsub("-", "").gsub("_", "")
git_repo_url
rails_port = ask_with_default("Port for Rails?", :blue, 3000)
assets_port = ask_with_default("Port for assets server?", :blue, 8000)
###########################################################
#
# Clone and add remote
#
FileUtils.rm_rf("#{@working_dir}/.") # Get rid of the rails generated code.
run "cd .. && git clone #{repo} #{@working_dir}" # Replace it with our repo.
git remote: "set-url origin #{git_repo_url}" if git_repo_specified?
git remote: "add upstream #{repo}"
###########################################################
#
# Database.yml
#
inside "config" do
copy_file "database.yml.example", "database.yml"
end
###########################################################
#
# secrets.yml
#
inside "config" do
copy_file "secrets.yml.example", "secrets.yml"
gsub_file("secrets.yml", "<Run rake secret to get a value to put here>") do |_match|
SecureRandom.hex(64)
end
end
###########################################################
#
# .env
#
create_file ".env" do
<<~EOF
APP_SUBDOMAIN=#{url_safe_name}
APP_ROOT_DOMAIN=atomicjolt.xyz
APP_PORT=#{rails_port}
PORT=#{rails_port}
APP_DEFAULT_CANVAS_URL=https://atomicjolt.instructure.com
# Get developer id and key from canvas
CANVAS_DEVELOPER_ID=1234
CANVAS_DEVELOPER_KEY=1234
# This helps support developer features like byebug by handling concurrency
# issues that come along with puma
RAILS_MAX_THREADS=2
WEB_CONCURRENCY=2
WEB_TIMEOUT=1000
EOF
end
###########################################################
#
# Modify application name
#
allowed = [".rb", ".js", ".yml", ".erb", ".json", ".md", ".jsx", ".example"]
modify_files = Dir.glob("#{@working_dir}/**/*").reject { |f| File.directory?(f) || allowed.exclude?(File.extname(f)) }
modify_files << ".env"
modify_files << "Gemfile"
modify_files << ".ruby-gemset"
modify_files << "./bin/bootstrap"
modify_files.each do |f|
gsub_file(f, "lti_starter_app") do |_match|
app_name.underscore
end
gsub_file(f, "ltistarterapp") do |_match|
app_name.titleize.gsub(" ", "")
end
gsub_file(f, "LtiStarterApp") do |_match|
app_name.titleize.gsub(" ", "")
end
gsub_file(f, "ltistarterapp") do |_match|
url_safe_name
end
gsub_file(f, "LTI Starter App") do |_match|
app_name.titleize
end
gsub_file(f, "HelloWorld") do |_match|
app_name.titleize.gsub(" ", "")
end
gsub_file(f, "Hello World") do |_match|
app_name.titleize
end
gsub_file(f, "HELLOWORLD") do |_match|
app_name.underscore.upcase
end
gsub_file(f, "hello_world") do |_match|
app_name.underscore
end
gsub_file(f, "helloworld") do |_match|
url_safe_name
end
end
def rename_file(f)
if f.include?("hello_world")
File.rename(f, f.gsub("hello_world", app_name.underscore))
end
end
# Rename dirs
Dir.glob("#{@working_dir}/**/*").each do |f|
if File.directory?(f)
rename_file(f)
end
end
# Renname File
Dir.glob("#{@working_dir}/**/*").each do |f|
unless File.directory?(f)
rename_file(f)
end
end
###########################################################
#
# Install Gems
#
begin
require "rvm"
RVM.gemset_create url_safe_name
begin
RVM.gemset_use! url_safe_name
run "gem install bundler"
run "bundle install"
rescue StandardError => e
puts "Unable to use gemset #{url_safe_name}: #{e}"
end
rescue LoadError
puts "RVM gem is currently unavailable."
end
###########################################################
#
# npm install
#
run "yarn"
###########################################################
#
# Initialize the database
#
rake("db:create")
rake("db:setup")
rake("db:seed")
###########################################################
#
# Commit changes to git
#
git add: "."
git commit: "-a -m 'Initial Project Commit'"
git push: "origin master" if git_repo_specified?
###########################################################
#
# Notes
#
puts "***********************************************"
puts "*"
puts "* Notes "
puts "*"
puts "Start application:"
puts "rails server"
puts "yarn hot"
if !git_repo_specified?
puts "To set your git remote repository run:"
puts "git remote set-url origin [URL_OF_YOUR_GIT_REPOSITORY]"
end
puts "If you need API access you will need to get a Canvas ID and Secret from your Canvs instance."
puts "Get keys from here: https://atomicjolt.instructure.com/accounts/1/developer_keys"
puts "** Replace atomicjolt with your Canvas subdomain"
puts "* *"
puts "***********************************************"
|
module Web
class VideosController < Web::BaseController
before_action :authenticate_user!, except: [ :index ]
before_action :correct_user, only: [ :destroy, :update ]
#def edit
#
#end
#
#def show
#
#end
#
#def new
# @video = Video.new
#end
#
#def delete
#
#end
def create
@video = current_user.video.build(video_params)
if !@video.save
flash[:notice] = "Простите, но что-то пошло не так"
end
redirect_to users_video_path
end
def destroy
@video.destroy
redirect_to users_video_path
end
def update
if !@video.update_attributes(video_params)
flash[:notice] = "Простите, но что-то пошло не так!"
end
redirect_to users_video_path
end
private
def video_params
params.require(:video).permit(:title)
end
def correct_user
@video = current_user.videos.find_by(user_id: params[:user_id])
access_denied if (@video.nil? and !current_user.admin?)
end
end
end
|
namespace :riders do
desc 'Destroy all teams and riders, and load new from the riders file'
task :reset => :environment do
Team.destroy_all
update_riders
end
desc 'Only update the riders with new information'
task :update => :environment do
update_riders
end
# Load new teams and riders or update them
def update_riders
riders_file = Rails.root.join("vendor", "files", "rennerslijst_2014.txt")
RiderTextParser.new(File.new(riders_file, 'r').read).parse
end
end
|
# Author: Jim Noble
# jimnoble@xjjz.co.uk
#
# desserts.rb
#
# A bit of basic object oriented programming
#
require './Dessert'
require './JellyBean'
d1 = Dessert.new("Bread and Butter Pudding", 1000)
d1.name = "Sticky Toffee Pudding"
d1.calories = 10000
puts d1
jb1 = JellyBean.new("Jelly bean", 10, "black licorice")
jb1.name = "Big Jelly bean"
jb1.calories = 15
puts jb1
|
require 'spec_helper'
RSpec.describe Aucklandia::Routes do
let(:client) { Aucklandia::Client.new(ENV['AUCKLANDIA_SECRET']) }
describe '#get_routes' do
context 'successful response' do
it 'returns a collection of bus routes', vcr: true do
expect(client.get_routes).to be_a Array
end
end
end
describe '#get_routes_by_short_name' do
let(:short_name) { 'OUT' }
context 'available short name' do
it 'responds with routes matching short name', vcr: true do
client.get_routes_by_short_name(short_name).each do |route|
expect(route['route_short_name']).to eq short_name
end
end
end
context 'short name does not match any routes' do
let(:short_name) { 'blahblahblah' }
it 'responds with an empty collection of routes', vcr: true do
expect(client.get_routes_by_short_name(short_name)).to be_empty
end
end
end
describe '#get_route_by_id' do
context 'route id exists' do
let(:id) { '73902-20181026152814_v71.31' } # route_short_name: 739
it 'responds with the route', vcr: true do
response = client.get_route_by_id(id)
expect(response['route_id']).to eq id
end
end
context 'route id does not exist' do
let(:id) { 'wutangagain?' }
it 'responds with nothing', vcr: true do
response = client.get_route_by_id(id)
expect(response).to be_nil
end
end
end
end |
# frozen_string_literal: true
require "bundler/gem_tasks"
require "rake/clean"
CLEAN.include("**/*.o", "**/*.so", "**/*.bundle", "pkg", "tmp")
require "rake/extensiontask"
%w[precomputed ref10].each do |provider|
next if provider == "precomputed" && RUBY_PLATFORM !~ /x86_64|x64/
Rake::ExtensionTask.new("x25519_#{provider}") do |ext|
ext.ext_dir = "ext/x25519_#{provider}"
end
end
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new
require "rubocop/rake_task"
RuboCop::RakeTask.new
task default: %w[compile spec rubocop]
|
require "spec_helper"
describe "CLI" do
let!(:course_index_array) {[{:name=>"Carlin Weld County Park", :location=>"Palmyra, WI ", :distance=>" 5.8 Miles ", :hole_count=>"18", :course_page, "https://www.dgcoursereview.com/course.php?id=8090"}]}
let!(:course_hash) {{:length=>"5186 ft.", :sse>" 44.5 ", :par>" 54 "}}
let!(:course) {Course.new({:name=>"Carlin Weld County Park", :location=>"Palmyra, WI ", :distance=>" 5.8 Miles ", :hole_count=>"18", :course_page, "https://www.dgcoursereview.com/course.php?id=8090"})}
after(:each) do
Student.class_variable_set(:@@all, [])
end
describe "#new" do
it "takes in an argument of a hash and sets that new course's attributes using the key/value pairs of that hash." do
expect{Student.new({:name => "Miniwaukan Park", :location => "
Mukwonago, WI "})}.to_not raise_error
expect(student.name).to eq("Carlin Weld County Park")
expect(student.location).to eq("Palmyra, WI ")
end
it "adds that new student to the Student class' collection of all existing students, stored in the `@@all` class variable." do
expect(Student.class_variable_get(:@@all).first.name).to eq("Alex Patriquin")
end
end
describe ".create_from_collection" do
it "uses the Scraper class to create new students with the correct name and location." do
Student.class_variable_set(:@@all, [])
Student.create_from_collection(student_index_array)
expect(Student.class_variable_get(:@@all).first.name).to eq("Alex Patriquin")
end
end
describe "#add_student_attributes" do
it "uses the Scraper class to get a hash of a given students attributes and uses that hash to set additional attributes for that student." do
student.add_student_attributes(student_hash)
expect(student.bio).to eq("I was in southern California for college (sun and In-n-Out!), rural Oregon for high school (lived in a town with 1500 people and 3000+ cows), and Tokyo for elementary/middle school.")
expect(student.blog).to eq("someone@blog.com")
expect(student.linkedin).to eq("someone@linkedin.com")
expect(student.profile_quote).to eq("\"Forget safety. Live where you fear to live. Destroy your reputation. Be notorious.\" - Rumi")
expect(student.twitter).to eq("someone@twitter.com")
end
end
describe '.all' do
it 'returns the class variable @@all' do
Student.class_variable_set(:@@all, [])
expect(Student.all).to match_array([])
end
end
end
|
class AddAuthToAppInstanceAndCourse < ActiveRecord::Migration[5.0]
def change
unless column_exists? :authentications, :application_instance_id
add_column :authentications, :application_instance_id, :integer
end
unless column_exists? :authentications, :canvas_course_id
add_column :authentications, :canvas_course_id, :integer
end
end
end
|
require 'faker'
FactoryGirl.define do
factory :order do
name { Faker::Name.name }
address { Faker::Address.street_address }
city { Faker::Address.city }
county { Faker::Address.state }
postcode { Faker::Address.zip }
email { Faker::Internet.email }
end
end |
require 'test_helper'
class ProductsControllerTest < ActionController::TestCase
setup do
@product = products(:keyword_search1)
@products = [
products(:keyword_search2),
products(:product1)
]
end
test "should show product" do
get :show, id: @product.ean
assert_response :success
assert_equal @product, assigns(:product)
end
test '複数商品表示' do
get :show, :id => @product.ean, :ean => @products.map(&:ean)
assert_response :success
assert_equal @product, assigns(:product)
assert_equal @products, assigns(:products)
end
test "Amazonへのリダイレクト" do
get :to_amazon, :id => @product.ean
assert_response :redirect
assert @response.header['Location'] == @product.a_url
end
test "楽天ブックスへのリダイレクト" do
get :to_rakuten, :id => @product.ean
assert_response :redirect
assert @response.header['Location'] == @product.r_url
end
end
|
require_relative "code"
class Mastermind
def initialize(number)
@secret_code = Code.random(number)
end
def print_matches(code)
exact = code.num_exact_matches(@secret_code)
near = code.num_near_matches(@secret_code)
puts "Exact matches: #{exact}"
puts "Near matches: #{near}"
end
def ask_user_for_guess
puts "Enter a code"
code = gets.chomp
guess = Code.from_string(code)
print_matches(guess)
if guess.num_exact_matches(@secret_code) == @secret_code.length
true
else
false
end
end
end
|
# Their solution
class PokerHand
def initialize(cards)
@cards = []
@rank_count = Hash.new(0)
5.times do
card = cards.draw
@cards << card
@rank_count[card.rank] += 1
end
end
def print
puts @cards
end
def evaluate
if royal_flush? then 'Royal flush'
elsif straight_flush? then 'Straight flush'
elsif four_of_a_kind? then 'Four of a kind'
elsif full_house? then 'Full house'
elsif flush? then 'Flush'
elsif straight? then 'Straight'
elsif three_of_a_kind? then 'Three of a kind'
elsif two_pair? then 'Two pair'
elsif pair? then 'Pair'
else 'High card'
end
end
private
def flush?
suit = @cards.first.suit
@cards.all? { |card| card.suit == suit }
end
def straight?
return false if @rank_count.any? { |_, count| count > 1 }
@cards.min.value == @cards.max.value - 4
end
def n_of_a_kind?(number)
@rank_count.one? { |_, count| count == number }
end
def straight_flush?
flush? && straight?
end
def royal_flush?
straight_flush? && @cards.min.rank == 10
end
def four_of_a_kind?
n_of_a_kind?(4)
end
def full_house?
n_of_a_kind?(3) && n_of_a_kind?(2)
end
def three_of_a_kind?
n_of_a_kind?(3)
end
def two_pair?
@rank_count.select { |_, count| count == 2 }.size == 2
end
def pair?
n_of_a_kind?(2)
end
end
# My solution
class PokerHand
attr_reader :starting_cards, :hand
def initialize(starting_cards)
@hand = []
if starting_cards.is_a?(Deck)
@starting_cards = starting_cards.deck_cards
5.times { |i| @hand << @starting_cards.draw}
else
@hand = starting_cards
end
end
def print
puts hand
end
def evaluate
case
when royal_flush? then 'Royal flush'
when straight_flush? then 'Straight flush'
when four_of_a_kind? then 'Four of a kind'
when full_house? then 'Full house'
when flush? then 'Flush'
when straight? then 'Straight'
when three_of_a_kind? then 'Three of a kind'
when two_pair? then 'Two pair'
when pair? then 'Pair'
else 'High card'
end
end
def rank_counts
rank_counts = Hash.new(0)
hand.each { |card| rank_counts[card.rank] += 1 }
rank_counts
end
private
def royal_flush?
sorted_hand = hand.sort
flush? && straight? && sorted_hand[4].rank == 'Ace'
end
def straight_flush?
flush? && straight?
end
def four_of_a_kind?
return true if rank_counts.key(4)
end
def full_house?
return true if rank_counts.key(3) && rank_counts.key(2)
end
def flush?
map_hand = hand.map(&:suit)
map_hand.uniq.size == 1
end
def straight?
sorted = hand.sort
1.upto(4) do |card_num|
return false if sorted[card_num].rank_value != sorted[card_num - 1].rank_value + 1
end
# if
true
end
def three_of_a_kind?
return true if rank_counts.key(3)
end
def two_pair?
counts_array = rank_counts.to_a
counts = 0
counts_array.each { |rank| counts += 1 if rank[1] == 2 }
counts == 2
end
def pair?
return true if rank_counts.key(2)
end
end
class Array
alias_method :draw, :pop
end
class Card
include Comparable
attr_reader :rank, :suit
RANKS = ((2..10).to_a + %w(Jack Queen King Ace))
RANK_VALUES = { 'Jack' => 11, 'Queen' => 12, 'King' => 13, 'Ace' => 14 }
SUITS = %w(Diamonds Clubs Hearts Spades)
ranks_and_suits = RANKS.product(SUITS).map { |rank, suit| [rank, suit] }
CARD_VALUES = ranks_and_suits.zip(1..52).to_h
# VALUES = { 'Jack' => 11, 'Queen' => 12, 'King' => 13, 'Ace' => 14 } # used in their solution
def initialize(rank, suit)
@rank = rank
@suit = suit
end
def rank_value # rank_value will just return value from 2 to 14 based on rank
RANK_VALUES.fetch(rank, rank)
end
def card_value # card_value will return value from 1 to 52 based on rank and suit
# i.e. [2, 'Diamonds'] => 1, [2, 'Clubs'] => 2 ... ['Ace', 'Hearts'] => 51, ['Ace', 'Spades'] => 52
CARD_VALUES[[rank, suit]]
end
def <=>(other)
card_value <=> other.card_value
end
def to_s
"#{rank} of #{suit}"
end
end
class Deck
attr_reader :deck_cards
# RANKS = ((2..10).to_a + %w(Jack Queen King Ace))
# SUITS = %w(Hearts Clubs Spades Diamonds)
def initialize
reset
end
def draw
reset if @deck_cards.empty?
@deck_cards.pop
end
private
def reset # using product makes it easier than what I did above
@deck_cards = Card::RANKS.product(Card::SUITS).map do |rank, suit|
Card.new(rank, suit)
end
@deck_cards.shuffle!
end
end
# a = Deck.new
# puts a.is_a?(Deck)
hand = PokerHand.new([
Card.new(10, 'Hearts'),
Card.new(8, 'Spades'),
Card.new(9, 'Diamonds'),
Card.new(10, 'Spades'),
Card.new('Ace', 'Clubs')
])
puts hand.rank_counts
puts hand.evaluate
hand.print
# hand2 = PokerHand.new(Deck.new)
# puts hand2.starting_cards
# puts ""
# hand2.print
|
class PanelProvider < ApplicationRecord
has_many :target_groups, foreign_key: 'panel_provider_id'
has_many :countries, foreign_key: 'panel_provider_id'
has_many :location_groups, foreign_key: 'panel_provider_id'
has_many :users, foreign_key: 'panel_provider_id'
validates :code, presence: true, uniqueness: true
end
|
class Child < ApplicationRecord
has_many :vaccines
end
|
class TransactionProcessingWorker
include Sidekiq::Worker
def perform(uuid, params)
from = Account.find(params['from_account_id'])
to = Account.find(params['to_account_id'])
amount = BigDecimal(params['amount'])
transaction = Transaction.new(amount: amount, from_account: from, to_account: to, uuid: uuid)
Account.transaction do
# why do I perform 2 #lock! calls here? I just want to make it more generic (for some reason) haha.
# There's no necessity for the second #lock! with sqlite (since it doesn't have any row locking mechanism, the whole file is locked instead)
# The table has already been locked, so it'll be just ignored.
#
# But for pg (for example) #lock! obtains FOR UPDATE row lock to prevent race conditions, that's why we would need both.
# with pg/mysql this style of locking may lead to a deadlock condition
# so it does make sense to set appropriate lock timeout
# sidekiq will restart job automatically
from.lock!
return transaction.insuficient_funds! unless from.hold(amount)
to.lock!
to.top_up(amount)
from.save!
to.save!
transaction.done!
end
end
end
|
describe Importers::MenuPageForm do
it 'valid' do
correct_row = FactoryGirl.attributes_for(:menu_page_import_row)
form = described_class.new(correct_row)
expect(form.valid?).to eq(true)
end
context 'invalid' do
it 'id: presence' do
incorrect_row = FactoryGirl.attributes_for(:menu_page_import_row, id: '')
form = described_class.new(incorrect_row)
expect(form.valid?).to eq(false)
expect(form.errors[:id]).to include("can't be blank")
end
it 'menu_id: presence' do
incorrect_row = FactoryGirl.attributes_for(:menu_page_import_row, menu_id: '')
form = described_class.new(incorrect_row)
expect(form.valid?).to eq(false)
expect(form.errors[:menu_id]).to include("can't be blank")
end
it 'id: numericality' do
incorrect_row = FactoryGirl.attributes_for(:menu_page_import_row, id: 'a')
form = described_class.new(incorrect_row)
expect(form.valid?).to eq(false)
expect(form.errors[:id]).to include("is not a number")
end
it 'menu_id: numericality' do
incorrect_row = FactoryGirl.attributes_for(:menu_page_import_row, menu_id: 'a')
form = described_class.new(incorrect_row)
expect(form.valid?).to eq(false)
expect(form.errors[:menu_id]).to include("is not a number")
end
end
end
|
class ChangeColumenNameOfComments < ActiveRecord::Migration
def change
rename_column :comments, :parent_id, :commentable_id
rename_column :comments, :parent_type, :commentable_type
end
end
|
class ProductImage < Attachment
mount_uploader :file, ProductImageUploader
validates :file, file_size: { maximum: 4.megabyte },
image_size: { max_width: 2048 }
end
|
class RemovefieldsfromDevices < ActiveRecord::Migration
def change
remove_column :devices, :last_lat
remove_column :devices, :last_lon
remove_column :devices, :last_fix
end
end
|
require './canhelplib'
require 'securerandom'
require 'pry'
module CanhelpPlugin
include Canhelp
def delete_enrollment(token, canvas_url, course_id, enrollment_id, task = "delete")
canvas_delete("#{canvas_url}/api/v1/courses/#{course_id}/enrollments/#{enrollment_id}", token,
{
task: task
})
end
def self.remove_enrollment(subdomain=nil, user_id=nil)
token = get_token
subdomain ||= prompt(:subdomain)
user_id ||= prompt(:user_id)
canvas_url = "https://#{subdomain}.instructure.com"
puts canvas_url
puts "#{canvas_url}/api/v1/users/#{user_id}/enrollments"
puts "Finding enrollments..."
enrollment_list = get_json_paginated(token,"#{canvas_url}/api/v1/#{user_id}/enrollments")
puts "#{enrollment_list.count} enrollments found. Deleting..."
enrollment_id = []
enrollment_list.each do |e|
enrollment_id << e['id']
delete_enrollment(token, canvas_url, e['course_id'], e['id'], task = "delete")
print "."
end
puts "Removed enrollment id(s):(#{enrollment_id})."
end
end
|
require 'lib/Recursive_Open_Struct'
$cfg = Recursive_Open_Struct.new
$cfg.app.name = "fxri - Instant Ruby Enlightenment"
$cfg.delayed_loading = false
$cfg.search_paths = ENV['FXRI_SEARCH_PATH'] if ENV.has_key?('FXRI_SEARCH_PATH')
# uses the first font that is available
$cfg.app.font.name = ["Bitstream Vera Sans", "Verdana", "Trebuchet MS", "Tahoma", "Arial"]
$cfg.ri_font = ["Bitstream Vera Sans Mono", "Courier New", "Courier"]
$cfg.app.font.size = 8
$cfg.app.width = 760
$cfg.app.height = 480
$cfg.search_delay = 0.1
$cfg.minimum_letters_per_line = 20
$cfg.packet_list_width = 160
$cfg.irb_height = 300
$cfg.status_line_update_interval = 0.1
$cfg.list.opts = ICONLIST_SINGLESELECT|ICONLIST_DETAILED|LAYOUT_FILL_X|LAYOUT_FILL_Y|ICONLIST_AUTOSIZE
# icons, are automatically loaded from Icon_Loader.
$cfg.icons_path = File.join("lib","icons")
$cfg.icons.klass = "class.png"
$cfg.icons.class_method = "module.png"
$cfg.icons.instance_method = "method.png"
# all texts
$cfg.text.search = "%d / %d entries"
$cfg.text.search_field = "What do you want to know?"
$cfg.text.method_name = "name"
# IRB
$cfg.launch_irb = true
$cfg.text.help = %|This is <b>fxri</b>, a graphical interface to the <em>Ruby</em> documentation. Fxri comes with a search engine with quite a few features. Here are several examples:
'<em>Array</em>': Lists all classes with the name <em>Array</em>. Note that upcase words are treated case sensitive, lowercase words insensitive.
'<em>array sort</em>': Everything that contains both <em>array</em> and <em>sort</em> (case insensitive).
'<em>array -Fox</em>': Everything that contain the name <em>array</em> (case insensitive), but not <em>Fox</em> (case sensitive).
After searching just press <em>down</em> to browse the search results. Press <em>Tab</em> to move back into the search field.
If you have any questions, suggestions, problems, please contact the current maintainer with <b>markus.prinz@qsig.org</b>.
Original author: Martin Ankerl (<b>martin.ankerl@gmail.com</b>).|
# prevent further modifications
$cfg.close
|
class User
attr_reader :name, :password
def initialize(name:, password:)
@name = name
@password = password
end
def self.create(name:, password:)
if ENV['ENVIRONMENT'] == 'test'
conn = PG.connect(dbname: 'chitter_challenge_test')
else
conn = PG.connect(dbname: 'chitter_challenge')
end
result = conn.exec("INSERT INTO users (name, password) VALUES('#{name}', '#{password}') RETURNING name, password")
User.new(name: result[0]['name'], password: result[0]['password'])
end
end
|
RSpec.describe Simple::Search do
it "has a version number" do
expect(Simple::Search::VERSION).not_to be nil
end
it "normalizes a string" do
string = "The broken window shatters across the ground!"
expected = "the broken window shatters across the ground"
expect(Simple::Search::normalize(string)).to eq(expected)
end
it "has the correct word frequency count" do
string = "There is that one person and only that one person"
record = Simple::Search::Record.new(string)
expect(record.term_frequency["person"]).to eq(2)
expect(record.term_frequency["there"]).to eq(1)
end
it "finds correct results" do
store = Simple::Search::Store.new()
Simple::Search::QUOTES.each do |record|
store.add(record)
end
expect(store.search("GrEaTeST").count).to eq(1)
expect(store.search("life").count).to eq(4)
expect(store.search("life!").count).to eq(4)
expect(store.search(",life,").count).to eq(4)
end
end
|
FactoryGirl.define do
factory :organization_address, class: Organization::Address do
country 'Country'
state 'State'
city 'City'
neighborhood 'Neighborhood'
street 'Street'
number '100'
association :organization, strategy: :build
end
end
|
require 'forwardable'
module SubParser
class Subtitle
extend Forwardable
attr_reader :timespan, :text
def_delegator :timespan, :start_time, :start_time
def_delegator :timespan, :end_time, :end_time
def initialize timespan, text
@timespan, @text = timespan, text
end
def to_s
"%s\n%s" % [timespan, text]
end
def self.parse raw
if raw =~ /\d+\n(.*)\n((?:.|\n)*)/
Subtitle.new Timespan.parse($1), $2
end
end
end
end
|
FactoryGirl.define do
factory :review do
skip_create
rating 5
text 'It was great'
restaurant_name 'Pizza Hut'
restaurant_url 'http://pizzahut.com'
date Time.now
user_name 'Mr. Pizza'
end
end |
# coding: utf-8
require "minitest/autorun"
require "mywn"
# Mmem = Meronyms - Member
class TestWnMmem < MiniTest::Test
def setup
@canis = "canis"
end
def test_wn_mmem_class
assert_kind_of Array, @canis.wn_mmem
end
def test_word_match
canis_mmem = [
"canis_familiaris", "wolf", "jackal"
]
canis_mmem.each do |w|
assert_equal @canis.wn_mmem.include?(w), true
end
end
end
|
require 'vizier/argument-decorators/base'
require 'orichalcum/completion-response'
module Vizier
#Most common decorator. Tags a argument as omitable. Otherwise, the
#interpreter will return an error to the user if they leave out an
#argument. Optional arguments that aren't provided are set to nil.
class Optional < ArgumentDecoration
register_as "optional"
def state_consume(state, subject)
state.unsatisfied_arguments.shift
state_with = state.dup
state_with.unsatisfied_arguments.unshift(decorated)
return [state_with, state]
end
def state_complete(state, subject)
return Orichalcum::NullCompletion.singleton
end
def completing_states(state, subject)
state_consume(state, subject)
end
def required?
false
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.