text stringlengths 10 2.61M |
|---|
module IGMarkets
class DealingPlatform
# Provides methods for working with client sentiment. Returned by {DealingPlatform#client_sentiment}.
class ClientSentimentMethods
# Initializes this helper class with the specified dealing platform.
#
# @param [DealingPlatform] dealing_platform The dealing platform.
def initialize(dealing_platform)
@dealing_platform = WeakRef.new dealing_platform
end
# Returns the client sentiment for a market.
#
# @param [String] market_id The ID of the market to return client sentiment for.
#
# @return [ClientSentiment]
def [](market_id)
result = @dealing_platform.session.get "clientsentiment/#{market_id}"
@dealing_platform.instantiate_models(ClientSentiment, result).tap do |client_sentiment|
if client_sentiment.long_position_percentage == 0.0 && client_sentiment.short_position_percentage == 0.0
raise ArgumentError, "unknown market '#{market_id}'"
end
end
end
end
end
end
|
require 'grpc/errors'
require 'google/cloud/errors'
module GRPC
module Kit
module Communication
module Resilient
DEFAULT_RESCUED_ERRORS = [
GRPC::BadStatus,
Google::Cloud::UnavailableError,
Google::Cloud::InternalError
].freeze
def resilient(limit: 16, also_rescue: [])
tries ||= 0
yield
# From Datastore documentation:
# - UNAVAILABLE;
# - Server returned an error;
# - Retry using exponential backoff.
rescue *(DEFAULT_RESCUED_ERRORS | Array(also_rescue))
tries += 1
exponential_backoff(tries, limit: limit) && retry
raise
end
# See: https://en.wikipedia.org/wiki/Exponential_backoff
def exponential_backoff(tries, limit:)
# Retry few times before going exponential
return true if tries <= 3
# Check whether it's reached the ceiling
if tries < limit
retry_time = 0.1 * rand(1 << tries) # random number between 0 and 2**N − 1
sleep(retry_time)
end
end
end
end
end
end
|
class EntriesController < ApplicationController
before_filter :get_organization
def create
Entry.transaction do
credit_account = @organization.accounts.where(id: params.require(:credit_account_id)).first
debit_account = @organization.accounts.where(id: params.require(:debit_account_id)).first
if credit_account && debit_account
credit = credit_account.credits.create(value: params.require(:value)).becomes(Credit)
debit = debit_account.debits.create(value: params.require(:value)).becomes(Debit)
@organization.entries.create!(debit: debit, credit: credit)
render nothing: true, status: 201
else
render nothing: true, status: 400
end
end
end
private
def get_organization
@organization = Organization.where(id: params.require(:organization_id)).first
render nothing: true, status: 400 unless @organization
end
end
|
class Paginator
DEFAULT_PAGE = 1
def self.paginate_relation(kaminari_relation, params)
map_from_relation_to_hash(
kaminari_relation,
params[:page].try(:to_i) || DEFAULT_PAGE,
params[:per_page].try(:to_i) || kaminari_relation.default_per_page,
kaminari_relation.total_count
)
end
def self.map_from_relation_to_hash(items, page, per_page, total_items)
{
items: items,
meta: {
page: page,
per_page: per_page,
total_items: total_items
}
}
end
end
|
require File.dirname(__FILE__) + '/../../../spec_helper'
require File.dirname(__FILE__) + '/../../../../lib/fog/google/models/storage/directory'
describe 'Fog::Google::Storage::Directory' do
describe "#initialize" do
it "should remap attributes from parser" do
now = Time.now
directory = Fog::Google::Storage::Directory.new(
'CreationDate' => now,
'Name' => 'directorykey'
)
directory.creation_date.should == now
directory.key.should == 'directorykey'
end
end
describe "#collection" do
it "should be the directories the directory is related to" do
directories = Google[:storage].directories
directories.new.collection.should == directories
end
end
describe "#destroy" do
it "should return true if the directory is deleted" do
directory = Google[:storage].directories.create(:key => 'fogmodeldirectory')
directory.destroy.should be_true
end
it "should return false if the directory does not exist" do
directory = Google[:storage].directories.new(:key => 'fogmodeldirectory')
directory.destroy.should be_false
end
end
describe "#reload" do
before(:each) do
@directory = Google[:storage].directories.create(:key => 'fogmodeldirectory')
@reloaded = @directory.reload
end
after(:each) do
@directory.destroy
end
it "should reset attributes to remote state" do
@directory.attributes.should == @reloaded.attributes
end
end
describe "#save" do
before(:each) do
@directory = Google[:storage].directories.new(:key => 'fogmodeldirectory')
end
it "should not exist in directories before save" do
Google[:storage].directories.all.map {|directory| directory.key}.include?(@directory.key).should be_false
end
it "should return true when it succeeds" do
@directory.save.should be_true
@directory.destroy
end
it "should exist in directories after save" do
@directory.save
Google[:storage].directories.all.map {|directory| directory.key}.include?(@directory.key).should be_true
@directory.destroy
end
end
end
|
class Commissionerd
require 'socket'
attr_reader :server, :configfile
attr_accessor :config
def initialize
require 'yaml'
@configfile = "config/commissionerd.yml"
@config = YAML.load_file(@configfile)
if @config["socket"] && ! @config["tcpip"]
@server = UNIXServer.new(@config["socketfile"])
elsif @config["tcpip"] && ! @config["socket"]
@server = TCPServer.new(@config["ip"], @config["port"])
elsif @config["tcpip"] && @config["socket"]
raise ArgumentError, "Both tcpip and socket cannot be true"
else
raise ArgumentError, "Either tcpip or socket must be true"
end
end
def server_loop
loop do
begin
client = @server.accept
Thread.start(client.read) do |s|
error = s
case error
when /^\[NOTICE\]/
error = notice(error)
when /^\[WARNING\]/
error = warning(error)
when /^\[CRITICAL\]/
error = critical(error)
else
s.close
end
print(error, "\n")
s.close
end
rescue SystemExit, Interrupt, IRB::Abort
if @config["socket"]
File.unlink(@config["socketfile"])
end
exit!
end
end
end
def alert(alert_string)
return "Alert received"
end
def warning(warning_string)
return "Warning received"
end
def critical(critical_string)
return "Critical received"
end
def update_config
File.open(@configfile,'w') { |f| f.puts @config.to_yaml }
end
end |
module RailsSettings
class SettingObject < ActiveRecord::Base
self.table_name = 'settings'
belongs_to :target, :polymorphic => true
validates_presence_of :var, :target_type
validate do
errors.add(:value, "Invalid setting value") unless value.is_a? Hash
unless _target_class.default_settings[var.to_sym]
errors.add(:var, "#{var} is not defined!")
end
end
serialize :value, Hash
if RailsSettings.can_protect_attributes?
# attr_protected can not be used here because it touches the database which is not connected yet.
# So allow no attributes and override <tt>#sanitize_for_mass_assignment</tt>
attr_accessible
end
REGEX_SETTER = /\A([a-z]\w*)=\Z/i
REGEX_GETTER = /\A([a-z]\w*)\Z/i
def respond_to?(method_name, include_priv=false)
super || method_name.to_s =~ REGEX_SETTER || _setting?(method_name)
end
def method_missing(method_name, *args, &block)
if block_given?
super
else
if attribute_names.include?(method_name.to_s.sub('=',''))
super
elsif method_name.to_s =~ REGEX_SETTER && args.size == 1
_set_value($1, args.first)
elsif method_name.to_s =~ REGEX_GETTER && args.size == 0
_get_value($1)
else
super
end
end
end
protected
if RailsSettings.can_protect_attributes?
# Simulate attr_protected by removing all regular attributes
def sanitize_for_mass_assignment(attributes, role = nil)
attributes.except('id', 'var', 'value', 'target_id', 'target_type', 'created_at', 'updated_at')
end
end
private
def _get_value(name)
if value[name].nil?
default_value = _get_default_value(name)
_deep_dup(default_value)
else
value[name]
end
end
def _get_default_value(name)
default_value = _target_class.default_settings[var.to_sym][name]
if default_value.respond_to?(:call)
default_value.call(target)
else
default_value
end
end
def _deep_dup(nested_hashes_and_or_arrays)
Marshal.load(Marshal.dump(nested_hashes_and_or_arrays))
end
def _set_value(name, v)
if value[name] != v
value_will_change!
if v.nil?
value.delete(name)
else
value[name] = v
end
end
end
def _target_class
target_type.constantize
end
def _setting?(method_name)
_target_class.default_settings[var.to_sym].keys.include?(method_name.to_s)
end
end
end
|
pkgs = value_for_platform(
[ "centos", "redhat", "fedora" ] => {
"default" => %w{ php53-cli php-pear }
},
[ "debian", "ubuntu" ] => {
"default" => %w{ php5-cgi php5-cli php-pear }
},
"default" => %w{ php5-cgi php5-cli php-pear }
)
pkgs.each do |pkg|
package pkg do
action :install
end
end
if node[:web_app][:system].has_key?("backend")
Chef::Log.info "not need to install php5 with apache module"
else
package "php5" do
action :install
end
end
node['php']['service'] = nil
node['php']['service'] = node["apache2"]['service'] if node[:web_app][:system][:name] == "lamp"
node['php']['service'] = node["php"]['fpm_service'] if node[:web_app][:system][:name] == "lemp"
template "#{node['php']['conf_dir']}/php.ini"
service "php-fpm" do
pattern "php-fpm"
start_command "/usr/sbin/invoke-rc.d php5-fpm start && sleep 1"
stop_command "/usr/sbin/invoke-rc.d php5-fpm stop && sleep 1"
restart_command "/usr/sbin/invoke-rc.d php5-fpm restart && sleep 1"
reload_command "/usr/sbin/invoke-rc.d php5-fpm reload && sleep 1"
supports value_for_platform(
"default" => { "default" => [:restart, :reload ] }
)
action :nothing
only_if { ::File.exists?("/etc/init.d/php5-fpm") }
subscribes :restart, resources(:template => "#{node['php']['conf_dir']}/php.ini"), :immediately
end
service "php5-fpm" do
pattern "php-fpm"
start_command "/usr/sbin/invoke-rc.d php5-fpm start && sleep 1"
stop_command "/usr/sbin/invoke-rc.d php5-fpm stop && sleep 1"
restart_command "/usr/sbin/invoke-rc.d php5-fpm restart && sleep 1"
reload_command "/usr/sbin/invoke-rc.d php5-fpm reload && sleep 1"
supports value_for_platform(
"default" => { "default" => [:restart, :reload ] }
)
action :nothing
only_if { ::File.exists?("/etc/init.d/php5-fpm") }
subscribes :restart, resources(:template => "#{node['php']['conf_dir']}/php.ini"), :immediately
end
template "#{node['php']['conf_dir']}/php.ini" do
source "php.ini.erb"
owner "root"
group "root"
mode "0644"
variables (:memory_limit => node[:php][:memory_limit])
end
|
class FileList
include Enumerable
attr_reader :store
def initialize(file)
file = File.new(file) if file.is_a?(String)
file.each_line do |line|
parse(line)
end
end
def each
store.each { |elm| yield elm }
end
def each_pair
store.each_pair do |k,v|
yield k, v
end
end
end
|
# frozen_string_literal: true
# require 'matrix'
class Board
attr_reader :board
def initialize(board = Array.new(6) { Array.new(7, '-') })
@board = board
end
def get_move(piece)
# p 'getting move'
row = player_input
column = calculate_column(row)
if valid_move?(row, column)
add_move(row, column, piece)
else
puts 'Invalid slot. Try again.'
get_move(piece)
end
end
def to_s
@board.transpose.reverse.each_with_index do |row, _index|
row.each_with_index do |column, index|
print column
print ' '
puts '' if index == 5
end
end
end
def check_win(piece)
true if
check_column(piece) ||
check_row(piece) ||
check_diagonal(piece)
end
private
def check_column(piece)
@board.each do |row|
count = []
row.each do |column|
count << column
end
return true if counter(count, piece, 7)
end
false
end
def check_row(piece)
@board.transpose.reverse.each do |row|
count = []
row.each do |column|
count << column
end
return true if counter(count, piece, 6)
end
false
end
def check_diagonal(piece)
reconstructed_array = []
@board.each do |row|
# puts "row is #{row}"
row.each_with_index do |slot, index|
# puts "slot is #{slot}"
# puts "index is #{index}"
reconstructed_array[index] = piece if slot == piece
end
current_piece = reconstructed_array.count(piece)
opponent_piece = piece == 'W' ? reconstructed_array.count('B') : reconstructed_array.count('W')
return true if (current_piece - opponent_piece) >= 4
end
false
end
def counter(count, piece, limit)
# p count
(0..limit).each do |number|
return true if (count[number] == piece) &&
(count[number + 1] == piece) &&
(count[number + 2] == piece) &&
(count[number + 3] == piece)
end
false
end
def player_input
p 'Which row to drop the piece? (0-6 for now)'
gets.chomp.to_i
end
def valid_move?(row, column)
# p row
# p column
@board[row][column] == '-'
end
def add_move(row, column, piece)
# p 'adding'
@board[row][column] = piece
# p 'added'
end
def calculate_column(row)
@board[row].each_with_index do |column, index|
return index if column == '-'
end
# p 'column is full'
99 # return an invalid integer to avoid returning a string and causing a mess
end
end
|
class HistoryBarQuery
def self.main_query(options = {})
@transactions_bar = TransactionBar.where(input_bar_id: options[:id_order]).order("input_bar_id DESC")
end
def self.inputs(options = {})
reset_query_state
@inputs_bar = inputs_bar.where.not(date_out: :NULL).order("date_in DESC")
if options[:date_range].present?
initial_date = Time.parse("#{options[:date_range].split('-')[0]} 00:00:00")
end_date = Time.parse("#{options[:date_range].split('-')[1]} 23:59:59")
@inputs_bar = inputs_bar.where(date_in: (initial_date..end_date))
end
if options[:tables].present?
@inputs_bar = inputs_bar.includes(:table_bar).where(table_bars: { id: options[:tables] })
end
if options[:employee].present?
@inputs_bar = inputs_bar.where(employee_id: options[:employee].to_i )
end
if options[:payment_method] == 'money'
@inputs_bar = inputs_bar.where(payment_method: 0)
elsif options[:payment_method] == 'visa_credit'
@inputs_bar = inputs_bar.where(payment_method: 1)
elsif options[:payment_method] == 'visa_debit'
@inputs_bar = inputs_bar.where(payment_method: 2)
elsif options[:payment_method] == 'master_credit'
@inputs_bar = inputs_bar.where(payment_method: 3)
elsif options[:payment_method] == 'master_debit'
@inputs_bar = inputs_bar.where(payment_method: 4)
elsif options[:payment_method] == 'dinners_credit'
@inputs_bar = inputs_bar.where(payment_method: 5)
elsif options[:payment_method] == 'dinners_debit'
@inputs_bar = inputs_bar.where(payment_method: 6)
elsif options[:payment_method] == 'amex_credit'
@inputs_bar = inputs_bar.where(payment_method: 7)
elsif options[:payment_method] == 'amex_debit'
@inputs_bar = inputs_bar.where(payment_method: 8)
elsif options[:payment_method] == 'check'
@inputs_bar = inputs_bar.where(payment_method: 9)
elsif options[:payment_method] == 'elo_debit'
@inputs_bar = inputs_bar.where(payment_method: 10)
elsif options[:payment_method] == 'elo_credit'
@inputs_bar = inputs_bar.where(payment_method: 11)
elsif options[:payment_method] == 'bank_deposit'
@inputs_bar = inputs_bar.where(payment_method: 12)
elsif options[:payment_method] == 'credit_authorized'
@inputs_bar = inputs_bar.where(payment_method: 13)
end
@inputs_bar || InputBar.none
end
def self.products(options = {})
if options[:date_range].present?
@totalProd = TransactionBar.group('product_code').order(:created_at).where.not(status_t: :undone)
initial_date = Time.parse("#{options[:date_range].split('-')[0]} 00:00:00")
end_date = Time.parse("#{options[:date_range].split('-')[1]} 23:59:59")
@totalProd = @totalProd.includes(:input_bar).where(input_bars: { date_in: (initial_date..end_date) })
end
if options[:employee].present?
@totalProd = @totalProd.includes(:input_bar).where(input_bars: {employee_id: options[:employee].to_i} )
end
@totalProd || TransactionBar.none
end
private
def self.inputs_bar
@inputs_bar || InputBar
end
def self.reset_query_state
@inputs_bar = nil
end
end |
require './src/reporter'
require './src/interface'
require './src/router'
class Robot < Interface
attr_accessor :x, :y, :facing, :router
def initialize(x = 0, y = 0, facing = :north, router = Router)
@router = router.new x, y, facing
@facing = @router.facing
@x = @router.x
@y = @router.y
@directions = @router.directions
end
def x
@router.x
end
def y
@router.y
end
def facing
@router.facing
end
def do(command, arguments=[])
send command, *arguments if respond_to? command
end
end
|
require 'nokogiri'
require 'open-uri'
class Scraper
def self.scrape_index_page(index_url)
doc = Nokogiri::HTML(open(index_url))
students = doc.css("div.student-card")
students_array = []
students.each{|student|
students_array.push({
:name => student.css("div.card-text-container h4.student-name").text,
:location => student.css("div.card-text-container p.student-location").text,
:profile_url => index_url + "/" + student.css("a").attribute("href").value
})
}
students_array
end
def self.scrape_profile_page(profile_url)
student = Nokogiri::HTML(open(profile_url))
student_profile = {}
links = student.css("div.social-icon-container a")
links.each{|link|
student_profile[:twitter] = link.attribute("href").value if link.attribute("href").value.include?("twitter.com")
student_profile[:linkedin] = link.attribute("href").value if link.attribute("href").value.include?("linkedin.com")
student_profile[:github] = link.attribute("href").value if link.attribute("href").value.include?("github.com")
student_profile[:blog] = link.attribute("href").value if link.children.attribute("src").value == "../assets/img/rss-icon.png"
}
student_profile[:profile_quote] = student.css("div.profile-quote").text
student_profile[:bio] = student.css("div.bio-content div.description-holder p").text
student_profile
end
end
|
class AddImageColumnsToEndUsers < ActiveRecord::Migration[5.2]
def change
add_column :end_users, :twitter_image, :string
add_column :end_users, :profile_image_id, :string
end
end
|
class User < ActiveRecord::Base
belongs_to :address
has_many :mytimeslots, :as=>:booker, :order=>"myorder ASC"
validates_confirmation_of :password, :on=>:create
validates_presence_of :first_name, :last_name, :email, :password
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
validates_uniqueness_of :email
end
|
# -*- encoding : utf-8 -*-
class ChangeReadedTimesFromNotifies < ActiveRecord::Migration
def up
change_column :notifies, :readed_times, :integer, :default => 0
end
def down
change_column :notifies, :readed_times, :integer, :default => :null;
end
end
|
class ChartQuery
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_reader :start_date, :end_date, :shareholder_id
def self.grouped_shareholders
result = {'All' => [['Anyone',nil]],'Active' => [], 'Inactive' => []}
Shareholder.order(:name).each do |sh|
result[sh.status].push([sh.name, sh.id])
end
[['All',result['All']], ['Active', result['Active']], ['Inactive', result['Inactive']]]
end
def initialize(params, session, user, account)
params ||= {}
if params[:start_date].present?
@start_date = Date.strptime(params[:start_date],'%m-%d-%Y')
else
@start_date = Date.today.beginning_of_month - 1.year
end
if params[:end_date].present?
@end_date = Date.strptime(params[:end_date],'%m-%d-%Y')
else
@end_date = Date.today.end_of_month
end
if params[:shareholder_id].present?
@shareholder_id = params[:shareholder_id].to_i
else
@shareholder_id = user.shareholder_for_account(account).id
end
end
def persisted?
false
end
def apply_conditions(model)
model = model.starting_on(start_date) if start_date
model = model.ending_on(end_date) if end_date
model
end
end
class ChartsController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource :account
def bill_types_by_month
bills = @account.bills.accessible_by(current_ability)
authorize! :show, Bill
@q = ChartQuery.new(params[:q], session, current_user, @account)
bills_to_display = @q.apply_conditions(bills).sum_of_bills_by_type_and_month_for_shareholder(@q.shareholder_id)
@values = Hash.new
@months = Hash.new(0)
@bill_types = Hash.new(0)
bills_to_display.each do |b|
@values[[b.bill_type, [b['year'].to_i ,b['month'].to_i]]] = b.amount
@months[[b['year'].to_i,b['month'].to_i]] += b.amount
@bill_types[b.bill_type] += b.amount
end
end
def balance_line_chart
balance_entries = @account.balance_entries.accessible_by(current_ability)
authorize! :show, BalanceEvent
balance_entries_to_display = query.apply_conditions(balance_entries)
@shareholders = Shareholder.find(balance_entries_to_display.uniq.pluck(:shareholder_id)).sort_by{|sh| sh.name }
@starting_balances = balance_entries.
select("shareholder_id, SUM(amount) AS amount").
group("shareholder_id").
where(shareholder_id: @shareholders.map{|sh| sh.id }).
where("date < ?",query.start_date).
includes(:shareholder)
balances = {}
@starting_balances.each {|sb| balances[sb.shareholder] = sb.amount }
@shareholders.each {|sh| balances[sh] ||= 0 }
@change_entries = balance_entries_to_display.
select("date, shareholder_id, SUM(amount) AS amount").
group("date, shareholder_id").
includes(:shareholder)
changes = {}
@change_entries.each do |ce|
changes[ce.shareholder] ||= {}
changes[ce.shareholder][ce.date] = ce.amount
end
end_date = query.end_date || @change_entries.map{|c| c.date }.max
columns = [['string','Date']]
@shareholders.each {|sh| columns << ['number',sh.name] }
rows = []
this_date = query.start_date
begin
row = [this_date]
@shareholders.each do |sh|
balances[sh] += changes[sh][this_date] if changes[sh][this_date].present?
row << balances[sh].to_f
end
rows << row
this_date += 1.day
end while this_date < end_date
render json: {
type: 'LineChart',
cols: columns,
rows: rows,
options: {
chartArea: { width: '90%', height: '90%' },
legend: { position: :in }
}
}
end
def bill_types_by_month_line_chart
bills = @account.bills.accessible_by(current_ability)
authorize! :show, BalanceEvent
query = ChartQuery.new(params[:query],session,current_user,@account)
bills_to_display = query.apply_conditions(bills).
select ('bill_type_id, extract(month from date) AS month, extract(year from date) AS year, sum(amount) as amount').
group ('bill_type_id, extract(month from date), extract(year from date)').
order ('extract(year from date), extract(month from date)').
includes(:bill_type)
values = {}
months = []
bill_types = []
bills_to_display.each do |b|
values[b.bill_type.name] ||= {}
values[b.bill_type.name][[b['year'],b['month']]] = b.amount
months << [b['year'],b['month']] unless months.include? [b['year'],b['month']]
bill_types << b.bill_type.name unless bill_types.include? b.bill_type.name
end
bill_types.sort!
columns = [['string','Month']]
bill_types.each {|bt| columns << ['number', bt] }
rows = []
months.each do |month|
row = ["#{month[1]}-#{month[0]}"]
bill_types.each {|bt| row << (values[bt][month].to_f || 0) }
rows << row
end
render json: {
type: 'LineChart',
cols: columns,
rows: rows,
options: {
chartArea: { width: '90%', height: '90%' },
legend: { position: :in },
curveType: 'function'
}
}
end
def bill_types_by_month_for_current_user_line_chart
bills = @account.bills.accessible_by(current_ability)
authorize! :show, Bill
@q = ChartQuery.new(params[:q],session,current_user,@account)
bills_to_display = @q.apply_conditions(bills).sum_of_bills_by_type_and_month_for_shareholder(@q.shareholder_id)
values = {}
months = []
bill_types = []
bills_to_display.each do |b|
values[b.bill_type.name] ||= {}
values[b.bill_type.name][[b['year'],b['month']]] = b.amount
months << [b['year'],b['month']] unless months.include? [b['year'],b['month']]
bill_types << b.bill_type.name unless bill_types.include? b.bill_type.name
end
bill_types.sort!
months.sort!
columns = [['string','Month']]
bill_types.each {|bt| columns << ['number', bt] }
rows = []
months.each do |month|
row = ["#{month[1].to_i}-#{month[0].to_i}"]
bill_types.each {|bt| row << (values[bt][month].to_f || 0) }
rows << row
end
render json: {
type: 'LineChart',
cols: columns,
rows: rows,
options: {
chartArea: { width: '90%', height: '90%' },
legend: { position: :in },
}
}
end
end
|
=begin
Write your code for the 'Beer Song' exercise in this file. Make the tests in
`beer_song_test.rb` pass.
To get started with TDD, see the `README.md` file in your
`ruby/beer-song` directory.
=end
class BeerSong
def self.recite(starting, count)
case count
when 1
verse(starting)
else
starting.downto(starting - (count - 1)).map {|n| verse(n)}.join("\n")
end
end
def self.verse(num)
case num
when 0
"No more bottles of beer on the wall, " +
"no more bottles of beer.\n" +
"Go to the store and buy some more, " +
"99 bottles of beer on the wall.\n"
when 1
"1 bottle of beer on the wall, " +
"1 bottle of beer.\n" +
"Take it down and pass it around, " +
"no more bottles of beer on the wall.\n"
when 2
"2 bottles of beer on the wall, " +
"2 bottles of beer.\n" +
"Take one down and pass it around, " +
"1 bottle of beer on the wall.\n"
else
# lyrics for bottles 99 to 3
"#{num} bottles of beer on the wall, " +
"#{num} bottles of beer.\n" +
"Take one down and pass it around, " +
"#{num - 1} bottles of beer on the wall.\n"
end
end
end
|
Rails.application.routes.draw do
get "categories/index"
root "static_pages#home"
get '/introduction', to: 'static_pages#introduction'
get '/contact', to: 'static_pages#contact'
get '/help', to: 'static_pages#help'
get '/login', to: "sessions#new"
post '/login', to: "sessions#create"
delete '/logout', to: "sessions#destroy"
get '/signup', to: "users#new"
get '/carts', to: "carts#index"
post '/carts', to: "carts#create"
put '/carts', to: "carts#update"
delete '/carts', to: "carts#destroy"
resources :users do
resources :suggested_products
resources :orders, only: [:show]
end
resources :products do
resources :ratings, only: :create
resources :comments
end
resources :carts, only: :index
resources :orders
resources :order_confirmations, only: :edit
namespace :admin do
resources :products do
collection {post :import}
resources :comments
end
resources :users, only: [:index, :destroy]
resources :orders
resources :suggested_products, only: [:index, :destroy]
resources :categories
end
end
|
# Abstract the process of killing dialog boxes. Kills them
# until closed, for a given PID.
#
# Author: Ben Nagy
# Copyright: Copyright (c) Ben Nagy, 2006-2013.
# License: The MIT License
# (See http://www.opensource.org/licenses/mit-license.php for details.)
require 'ffi'
require 'bm3-core'
module BM3
module Win32
module Dialog
# Window message constants etc
BMCLICK = 0x00F5
WM_DESTROY = 0x0010
WM_COMMAND = 0x111
IDOK = 1
IDCANCEL = 2
IDNO = 7
IDCLOSE = 8
GW_ENABLEDPOPUP = 0x0006
extend FFI::Library
ffi_lib 'user32'
ffi_convention :stdcall
callback :enum_callback, [:ulong, :ulong], :bool
attach_function :EnumDesktopWindows, [:pointer, :enum_callback, :ulong], :bool
attach_function :PostMessageA, [:ulong, :int, :ulong, :ulong], :bool
attach_function :GetWindowThreadProcessId, [:ulong, :pointer], :ulong
attach_function :GetWindow, [:ulong, :int], :ulong
def dialogs_killed?
@dialogs_killed
end
def reset
@dialogs_killed = false
end
def kill_dialogs target_pid
pid = FFI::MemoryPointer.new :ulong
@kill_popups ||= Proc.new {|handle, param|
# This won't get ALL the windows, eg with Word it sometimes
# pops up a toplevel dialog box that is not a popup of the
# parent pid.
GetWindowThreadProcessId handle, pid
if pid.read_ulong == param
# Window belongs to this pid
# Does it have any popups?
popup = GetWindow handle, GW_ENABLEDPOPUP
unless popup.zero?
@dialogs_killed = true
PostMessageA popup, WM_COMMAND, IDCANCEL, 0
PostMessageA popup, WM_COMMAND, IDNO, 0
PostMessageA popup, WM_COMMAND, IDCLOSE, 0
PostMessageA popup, WM_COMMAND, IDOK, 0
PostMessageA popup, WM_DESTROY, 0, 0
end
end
true # keep enumerating
}
EnumDesktopWindows( nil, @kill_popups, target_pid )
end
end
class DialogKiller
include Dialog
extend Dialog
include BM3::Logger
def initialize sleeptime = 3, debug = false
@sleeptime = sleeptime
@debug = debug
end
def start pid
@pid = pid
debug_info "Starting to kill dialogs for #{pid}"
start_dk_thread pid
end
def stop
return unless @dk_thread
@dk_thread.kill
@dk_thread = nil
debug_info "No longer killing dialogs for #{@pid}"
end
private
def start_dk_thread pid
# This might be leaky on JRuby on Win7 x64 when used within another
# Thread, so you you're seeing handle / USER object leaks, add it to your
# list of suspects. The workaround is to repeatedly just call the
# kill_dialogs method.
@dk_thread = Thread.new do
loop do
begin
kill_dialogs pid
sleep @sleeptime
rescue
sleep @sleeptime
debug_info "Error in DK thread: #{$!}"
retry
end
end
end
end
end
end
end
|
class ChangeColumnsForCategory < ActiveRecord::Migration
def change
remove_column :categories, :subcategory_id, :integer
add_reference :subcategories, :category, index: true
end
end
|
class Api::V1::BaseController < ActionController::Base
respond_to :json
before_filter :authenticate_user
private
def authenticate_user
@current_user = User.where(authentication_token: params[:token]).first
unless @current_user
respond_with({ error: "Token is invalid." })
end
end
def current_user
@current_user
end
end |
# frozen_string_literal: true
require "spec_helper"
RSpec.describe PatternStore do
subject(:pattern_store) { PatternStore.new }
it { expect(pattern_store).not_to be_nil }
describe "#[]" do
context "when a known pattern is requested" do
context "as string" do
let(:pattern_name) { "xes" }
it_behaves_like "a known pattern name"
end
context "as klass" do
let(:pattern_name) { XesPattern }
it_behaves_like "a known pattern name"
end
context "as symbol" do
let(:pattern_name) { :xes }
it_behaves_like "a known pattern name"
end
end
context "when an unknown pattern is requested" do
context "as string" do
let(:pattern_name) { "unknown" }
it_behaves_like "an unknown pattern name"
end
context "as klass" do
let(:pattern_name) do
stub_const("UnknownPattern", Class.new)
UnknownPattern
end
it_behaves_like "an unknown pattern name"
end
context "as symbol" do
let(:pattern_name) { :unknown }
it_behaves_like "an unknown pattern name"
end
end
end
end
|
# == Schema Information
# Schema version: 3
#
# Table name: categories
#
# id :integer(11) not null, primary key
# name :string(255)
#
class Category < ActiveRecord::Base
has_many :posts
def Category.find_select_options
[[ '-- Select a Category --', '' ]] + Category.find(:all).map { |cat| [ cat.name, cat.id ] }
end
NAMES_IDS = find_select_options
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
root 'students#index'
resources :students do
get '/entries/ids', :to => 'entries#get_ids'
resources :entries, except: [:index]
get '/entries/:id/entry_data', :to => 'entries#entry_data'
end
get '/more_students', :to => 'students#more'
resources :rehearsals
resources :events do
resources :rehearsals, only: [:index]
end
resources :comments, only: [:create]
get '*a', :to => 'errors#routing'
end
|
require 'fileutils'
class Subject < ActiveRecord::Base
include ContentManagement::Model
include PublicActivity::Model
tracked
RESERVED_NAMES = ["homepage_header", "index", "promotion", "homepage"]
include Liquid::Rails::Droppable
enum status: [ :open, :close ]
acts_as_punchable
class_attribute :default_templates
has_many :templates, as: :templable, dependent: :destroy
validates :title, presence: true
validates :name, uniqueness: true
validates :start_at, presence: true
validates :end_at, presence: true
before_validation :default_values
after_create :create_subject_files
after_commit :remove_templates_folder, on: :destroy
paginates_per 10
scope :availables, -> do
where("start_at <= ? and end_at >= ? and status = ?", Time.now, Time.now, 0)
end
def name_reserved?(name)
RESERVED_NAMES.include? name
end
def content_root
File.join(Rails.root, Settings.sites.system.root, "subjects")
end
protected
def default_values
if self.name.blank?
py_name = Pinyin.t(self.title, splitter: '_').downcase
py_name.succ! if same_name?(py_name)
self.name = py_name
end
end
def same_name?(name)
self.class.where(name: name).last.present?
end
def create_subject_files
SubjectService.build(name)
end
private
def remove_templates_folder
return if persisted?
puts "尝试删除专题文件夹:#{content_path}"
if FileUtils.remove_dir content_path, true
puts "专题文件夹删除成功!"
else
puts "专题文件夹删除失败!"
end
end
end
Subject.default_templates = [
PageTemplate.new(name: 'index', filename: 'views/subjects/index.html.liquid', templable: Subject.new),
PartialTemplate.new(name: 'promotion', filename: 'views/promotions/_promotion.html.liquid', templable: Subject.new),
HomepageTemplate.new(name: 'homepage_header', filename: 'views/promotions/_homepage_header.html.liquid', templable: Subject.new)
]
|
#
class LinkedList
attr_reader :size
def initialize
clear
end
def empty?
@size.zero?
end
def clear
@head = nil
@tail = nil
@size = 0
end
def add(data)
link_head(data)
end
# def get
# validate(1)
# @head.element
# end
def get_first
validate(1)
@head.element
end
def get_last
validate(1)
@tail.element
end
def get(arg)
if args.nil
return get_first
else arg.is_a? Integer
result = find_position(arg)
return result.nil?
end
end
def remove
validate(1)
unlink_head
end
def remove_first
validate(1)
unlink_head
end
def remove_last
validate(1)
unlink_tail
end
def set(data)
validate(1)
set_data(data)
end
def set_first(data)
validate(1)
set_data(data, @head)
end
def set_last(data)
validate(1)
set_data(data, @tail)
end
private
# private Node<E> find(int position)
# {
# // Create the node to be returned, starts off as the head
# Node<E> current = head;
#
# // i is the counter
# int i = 1;
#
# // While i is less than position get the next node
# while(i < position){
# // Get the next node
# current = current.getNext();
#
# // increment the counter
# ++i;
# }
#
# //return the found node
# return current;
# }
def find(data)
result = find_position
end
def find_position(i)
current = @head
i.each { current = current.next }
current
end
def find_data(data)
current = @head
until current.nil? || current.element == data { current = current.next }
current
end
def set_data(data, current)
old_data = current.element
current.element = data
old_data
end
def link_head(data)
to_add = Node.new({element: data, previous: nil, next: @head})
if @head.nil?
@tail = to_add
else
@head.previous = to_add
end
@head = to_add
@size += 1
end
def link_tail(data)
to_add = Node.new({element: data, previous: @tail, next: nil})
if @tail.nil?
@head = to_add
else
@tail.next = to_add
end
@head = to_add
@size += 1
end
def unlink_head
current = @head
@head = @head.next
if @head.nil?
@tail = nil
else
@head.previous = nil
end
@size -= 1
current.element
end
def unlink_tail
current = @tail
@tail = @tail.next
if @tail.nil?
@head = nil
else
@tail.next = nil
end
@size -= 1
current.element
end
def validate(i)
raise ArgumentError, 'No such element' if (i > @size)
end
class Node
attr_accessor :element, :next, :previous
def initialize(args = nil)
@element = nil
@next = nil
@previous = nil
unless args.nil?
@element = args[:element] if args.key? :element
@next = args[:next] if args.key? :next
@prevouse = args[:previous] if args.key? :previous
end
end
end
end
|
class Tweet < ActiveRecord::Base
validates_length_of :tweet, :in => 1..140
belongs_to :user
end
|
json.array!(@entries) do |entry|
json.extract! entry, :id, :nick, :r1, :r2, :r3, :r4, :r5, :r6, :tournament_id
json.url entry_url(entry, format: :json)
end
|
module Intent
class Combat < Action
attr_reader :attack
attr_reader :defend
attr_accessor :mo_delta
def initialize(attack, defend)
super attack.entity, {encumbrance: false, status_tick: false, unhide: false, alive: false} # checks get done in Attack intent
@mo_delta = 0
@attack = attack
@defend = defend
@attack.hit_chance -= defend.attack_penalty?(DefenceType::CLOSE_COMBAT_AVOIDANCE) if @attack.close_combat?
@attack.hit_chance -= defend.attack_penalty?(DefenceType::RANGED_COMBAT_AVOIDANCE) if @attack.ranged_combat?
end
def apply_costs
@attack.apply_costs
Entity::Status.tick(@attack.target, StatusTick::STATUS)
end
def possible?
unless @attack.possible?
debug 'Not possible to attack'
end
@attack.possible?
end
def take_action
attacker_hooks = collate_combat_hooks @attack.entity
defender_hooks = collate_combat_hooks @attack.target
debug "Effective hit % after close/ranged avoidance: #{@attack.hit_chance}"
@attack.hit_chance = 0 if @defend.avoided?
debug 'Missed due to generic avoidance!' if @defend.avoided?
if @attack.hit?
debug 'Attack hit!'
attacker_hooks.each {|hook| hook.intent_combat_hook self, :attack_hit, :attacker}
defender_hooks.each {|hook| hook.intent_combat_hook self, :attack_hit, :defender}
@defend.take_hit(@attack)
case @attack.target.alignment
when :good
@mo_delta = @defend.damage_taken * -2
# -3 MO for goods hitting goods
@mo_delta -= 30 if @attack.entity.alignment == :good
# -1 MO for goods killing goods (total -4)
@mo_delta -= 10 if @attack.entity.dead?
when :neutral
@mo_delta = -@defend.damage_taken
# -2 MO for goods killing neutrals
@mo_delta -= 20 if @attack.entity.dead? && @attack.entity.alignment == :good
when :evil
unless @attack.entity.alignment == :evil
@mo_delta = @defend.damage_taken unless @attack.entity.alignment == :evil # TODO: unless @attack.target.faction.alignment == :evil || @attack.target.is_demon
# +1 MO for non-evil killing evil
@mo_delta += 10 if @attack.target.dead?
end
end
attacker_hooks.each {|hook| hook.intent_combat_hook self, :took_damage, :attacker}
defender_hooks.each {|hook| hook.intent_combat_hook self, :took_damage, :defender}
@attack.entity.mo += @mo_delta
end
end
def broadcast_results
#TODO: Split into Intent::Attack and Intent::Defend
message_death = nil
attack_text = @attack.describe(BroadcastScope::SELF, @defend)
if @attack.target.dead?
notify = Array.new
@attack.entity.location.characters.each do |char|
notify << char.id unless char == @attack.entity || char == @attack.target
end
message_death = Entity::Message.new({characters: notify, type: MessageType::COMBAT_ATTACK, message: @attack.describe(BroadcastScope::TILE, @defend)}) unless notify.count == 0
end
message_atk = Entity::Message.new({characters: [@attack.entity.id], type: MessageType::COMBAT_ATTACK, message: attack_text})
message_def = Entity::Message.new({characters: [@attack.target.id], type: MessageType::COMBAT_DEFEND, message: @attack.describe(BroadcastScope::TARGET, @defend)})
@attack.entity.broadcast_self BroadcastScope::TILE
@attack.target.broadcast_self BroadcastScope::TILE
message_atk.save
message_def.save
message_death.save unless message_death === nil
weapon = attack.weapon
alters = []
if weapon.respond_to? :weapon_intent
entity.each_applicable_effect do |effect|
alters << effect if effect.respond_to?(:alter_attack_intent)
end
intent = weapon.weapon_intent(Intent::Attack.new(entity, attack.target))
alters.each do |alter|
intent = alter.alter_attack_intent(intent)
end
weaps_hash = {}
weaps_hash[weapon.object_id] = intent.to_hash
entity.broadcast BroadcastScope::SELF, {packets: [{type: 'actions', mode: 'update', actions: {attacks: weaps_hash}}]}.to_json
end
end
private
def collate_combat_hooks(entity)
hooks = []
entity.each_applicable_effect do |effect|
hooks << effect if effect.respond_to? :intent_combat_hook
end
return hooks
end
end
end |
class ChangeUsersToEmbedPerson < ActiveRecord::Migration[5.2]
def change
remove_reference :users, :person, foreign_key: true
add_column :users, :full_name, :string
add_column :users, :ic, :string
add_reference :users, :person_type, foreign_key: true
add_reference :users, :ic_type, foreign_key: true
end
end
|
class Memory < ActiveRecord::Base
belongs_to :creator, class_name: "User"
has_many :comments
has_many :pending_replies,
-> { where approved: false },
class_name: "Comment"
has_many :approved_comments,
-> { where approved: true },
class_name: "Comment"
has_and_belongs_to_many :keyword_associations, class_name: "Keyword"
has_many :related_memories,
->(m) { where.not(id: m.id) },
through: :keyword_associations,
source: :memories
has_attached_file :image, styles: { large: "600x600>", medium: "450x450>" },
default_url: "/img-300-placeholder.gif"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
validates :name, presence: true
validates :keywords, presence: true
validates :description, presence: true
def related_memories_sorted
related_memories.group("memories.id").count.sort_by { |_, v| v }.reverse.map { |k, _| Memory.find(k) }
end
def update_keyword_associations(new_keywords_string, old_keywords_string = "")
new_keywords = to_keyword_array(new_keywords_string)
old_keywords = to_keyword_array(old_keywords_string)
add_keyword_associations(new_keywords - old_keywords)
remove_keyword_associations(old_keywords - new_keywords)
end
def to_keyword_array(keyword_string)
keyword_string.split(",").map(&:strip).map(&:downcase)
end
def remove_keyword_associations(removed_keyword_strings)
removed_keyword_strings.each do |keyword|
assoc = Keyword.find_by(word: keyword)
keyword_associations.delete(assoc) if assoc
end
end
def add_keyword_associations(added_keyword_strings)
added_keyword_strings.each do |keyword|
assoc = Keyword.find_or_create_by(word: keyword)
keyword_associations << assoc unless keyword_associations.include? assoc
end
end
end
|
require 'rails_helper'
require 'spec_helper'
RSpec.describe User, type: :model do
it { should have_many(:feedbacks) }
it { should validate_presence_of(:first_name) }
it { should validate_presence_of(:last_name) }
it { should validate_presence_of(:email) }
it { should validate_presence_of(:password) }
end
|
class User
include HyperMapper::Document
attr_accessor :password
# Determines, as in Rails, which attributes can be modified via mass assignment
attr_accessible :username, :bio, :password
# HyperMapper will generate a unique ID the first time this
# User is saved
autogenerate_id
# Create two attributes, :username, and :bio
attribute :username
attribute :bio
# Things we'll need for authentication
attribute :salt
attribute :hashed_password
attribute :session_id
# Maintain :created_at and :updated_at timestamps
timestamps
has_many :posts
validates :username, presence: true,
format: /[a-zA-Z\s]+/
validates :password, presence: true, if: "hashed_password.blank?"
before_save :encrypt_password, if: "!password.nil?"
def encrypt_password
self.salt ||= Digest::SHA256.hexdigest("#{Time.now.to_s}-#{username}")
self.hashed_password = encrypt(password)
end
def encrypt(raw_password)
Digest::SHA256.hexdigest("-#{salt}-#{raw_password}")
end
def has_password?(raw_password)
hashed_password == encrypt(raw_password)
end
def self.authenticate(username, plain_text_password)
user = User.where(username: username)[0]
return nil unless user && user.has_password?(plain_text_password)
user
end
end |
# frozen_string_literal: true
require "digest"
# This class creates/mines a block with necessary information
class Block
def initialize(timestamp:, transactions:)
@timestamp = timestamp
@transactions = transactions
@nonce = 0
end
def mine_block(difficulty)
difficulty_string = "0" * difficulty
nonce = 0
loop do
hash = calculate_hash
if hash.start_with?(difficulty_string)
puts "Block mined: #{hash}"
break
else
nonce += 1
end
end
end
def valid_transactions?
transactions.each do |transaction|
return false unless transaction.valid?
end
true
end
private
attr_reader :previous_hash, :hash, :transactions, :nonce
def calculate_hash
payload = @timestamp.to_s + @transactions.to_s + @previous_hash.to_s + @nonce.to_s
Digest::SHA256.hexdigest(payload)
end
end
|
# frozen_string_literal: true
class AuthService
def initialize(config)
@config = config
@registry = PolicyRegistry.setup!(config)
end
attr_reader :config
include GRPC::GenericService
self.marshal_class_method = :encode
self.unmarshal_class_method = :decode
self.service_name = 'envoy.service.auth.v2.Authorization'
# Performs authorization check based on the attributes associated with the incoming request,
# and returns status `OK` or not `OK`.
rpc :Check, Envoy::Service::Auth::V2::CheckRequest, Envoy::Service::Auth::V2::CheckResponse
def check(req, rest)
GRPC.logger.debug(req.class.name) { req.to_json(emit_defaults: true) }
host = req.attributes.request.http.host
case service = config.for_host(host)
when Config::Service
context = Context.new(req, service)
context.evaluate!
if context.valid?
return ok_response(req, service)
else
return denied_response('Not authorized')
end
end
denied_response('Service not found', status: :not_found)
end
protected
RESPONSE_CODES = {
not_found: { grpc: GRPC::Core::StatusCodes::NOT_FOUND, envoy: Envoy::Type::StatusCode::NotFound },
forbidden: { grpc: GRPC::Core::StatusCodes::PERMISSION_DENIED, envoy: Envoy::Type::StatusCode::Forbidden }
}.freeze
def ok_response(req, service)
Envoy::Service::Auth::V2::CheckResponse.new(
status: Google::Rpc::Status.new(code: GRPC::Core::StatusCodes::OK),
ok_response: Envoy::Service::Auth::V2::OkHttpResponse.new(
headers: [
# TODO: add headers
]
)
)
end
def denied_response(message, status: :forbidden)
Envoy::Service::Auth::V2::CheckResponse.new(
status: Google::Rpc::Status.new(code: RESPONSE_CODES.dig(status, :grpc)),
denied_response: Envoy::Service::Auth::V2::DeniedHttpResponse.new(
status: Envoy::Type::HttpStatus.new(code: RESPONSE_CODES.dig(status, :envoy)),
body: message,
headers: [
Envoy::Api::V2::Core::HeaderValueOption.new(header: Envoy::Api::V2::Core::HeaderValue.new(key: 'x-ext-auth-reason', value: status.to_s)),
]
)
)
end
end
require_relative 'auth_service/policy_registry'
require_relative 'auth_service/context'
|
class TriangleMovesCounting
def initialize(n)
@n = n
end
# This probably isn't the right way to go, but it will work for now.
def each_position(&block)
(0...@n).flat_map do |x|
(0..x).map { |y| yield(x, y) }
end
end
def count_moves(positions)
each_position { |x, y| count_position(x, y, positions) }.reduce(:+)
end
def count_position(x, y, positions)
return 0 unless positions.include?([x, y])
directions
.map { |d| count_in_direction(0, x, y, positions, d) }
.reduce(:+)
end
def count_in_direction(current_count, x, y, positions, direction)
return current_count - 1 if y > x || x >= @n || [x, y].min < 0
x_1, y_1 = direction[x, y]
return current_count if positions.include?([x_1, y_1])
count_in_direction(current_count + 1, x_1, y_1, positions, direction)
end
def directions
[
->(x, y){[x, y + 1]}, # -
->(x, y){[x, y - 1]}, # -
->(x, y){[x - 1, y]}, # /
->(x, y){[x + 1, y]}, # /
->(x, y){[x + 1, y + 1]}, # \
->(x, y){[x - 1, y - 1]}, # \
]
end
end
|
class ContactsController < ApplicationController
# before_action :authenticate_user, except: [:index, :show]
def index
# contacts = Contact.all.order(:id => :asc) #shows all contacts from the database
contacts = Contact.all.where(user_id: current_user.id)
if params[:first_name_search]
contacts = contacts.where("first_name ILIKE ?", "%#{params[:first_name_search]}%")
end
if params[:middle_name_search]
contacts = contacts.where("middle_name ILIKE ?", "%#{params[:middle_name_search]}%")
end
if params[:last_name_search]
contacts = contacts.where("last_name ILIKE ?", "%#{params[:last_name_search]}%")
end
if params[:email_search]
contacts = contacts.where("email ILIKE ?", "%#{params[:email_search]}%")
end
if params[:phone_number_search]
contacts = contacts.where("phone_number ILIKE ?", "%#{params[:phone_number_search]}%")
end
render json: contacts.as_json
end
def create
contact = Contact.new(
first_name:params["first_name"],
middle_name:params["middle_name"],
last_name:params["last_name"],
email:params["email"],
phone_number:params["phone_number"],
bio:params["bio"],
user_id: current_user.id
)
if contact.save
render json: contact.as_json
else
render json: {errors: contact.errors.full_messages}, status: :bad_request
end
end
def show
contact = Contact.find_by(id: params["id"])
render json: contact.as_json
end
def update
contact = Contact.find_by(id: params["id"])
contact.first_name = params["first_name"] || contact.first_name
contact.last_name = params["last_name"] || contact.last_name
contact.middle_name = params["middle_name"] || contact.middle_name
contact.email = params["email"] || contact.email
contact.phone_number = params["phone_number"] || contact.phone_number
contact.bio = params["bio"] || contact.bio
if contact.save
render json: contact.as_json
else
render json: {errors: contact.errors.full_messages}, status: :bad_request
end
end
def destroy
contact_id = params["id"]
contact = Contact.find_by(id: contact_id)
contact.destroy
render json: {message: "Contact has been deleted."}
end
end
|
module Api::V1::Agents
class ProposalsController < AgentUsersController
include Serializable
before_action :set_job, only: %i[create destroy]
before_action :set_proposal, only: %i[destroy]
def index
proposals = current_user.proposals
set_response(
200, 'Propuestas listadas exitosamente',
serialize_proposal_for_agents(proposals)
)
end
def create
if @job
if @job.proposals.where(agent: current_user).exists?
set_response(422, 'Ya te has postulado para este trabajo')
else
proposal = Proposal.new(
job: @job, agent: current_user, status: 'pending'
)
if proposal.save
set_response(200, 'Se ha postulado exitosamente')
else
set_response(422, proposal.errors.messages.values.join(', '))
end
end
else
set_response(404, 'El trabajo no existe')
end
end
def destroy
if @job
if @proposal
@proposal.destroy
set_response(200, 'La propuesta ha sido eliminada exitosamente')
else
set_response(404, 'La propuesta no existe')
end
else
set_response(404, 'El trabajo no existe')
end
end
private
def set_proposal
@proposal = Proposal.find_by(hashed_id: params[:id])
end
def set_job
@job = Job.find_by(hashed_id: params[:job_id])
end
end
end
|
# frozen_string_literal: true
module Jiji::Composing::Configurators
class IconConfigurator < AbstractConfigurator
include Jiji::Model
def configure(container)
container.configure do
object :icon_repository, Icons::IconRepository.new
end
end
end
end
|
module Endpoints
class Versions < Base
namespace "/versions" do
get do
versions = Version.reverse(:number)
versions = versions.where(platform: params['platform']) if params['platform']
encode serialize(versions)
end
get "/:identity" do |identity|
version = Version[number: identity]
begin
version = Version[id: identity] unless version
rescue
raise Pliny::Errors::NotFound
end
raise Pliny::Errors::NotFound unless version
encode serialize(version)
end
private
def serialize(data, structure = :default)
Serializers::Version.new(structure).serialize(data)
end
end
end
end
|
Given(/^a node "(.*?)" started with a votenotify script$/) do |arg1|
name = arg1
options = {
image: "nunet/empty",
links: @nodes.values.map(&:name),
args: {
debug: true,
timetravel: timeshift,
votenotify: "/shared/votenotify.sh",
},
}
node = CoinContainer.new(options)
@nodes[name] = node
node.wait_for_boot
end
Given(/^the votenotify script of node "(.*?)" is written to dump the vote and sign it with address "(.*?)"$/) do |arg1, arg2|
node = @nodes[arg1]
script = <<-EOF.gsub(/^ /, "")
#!/bin/bash
set -x
NUD=/code/nud
ARGS="--datadir=/root/.nu"
VOTE_PATH=#{node.shared_path_in_container("vote.json")}
SIGNATURE_PATH=#{node.shared_path_in_container("vote.json.signature")}
ADDRESS=#{@addresses[arg2]}
$NUD $ARGS getvote >$VOTE_PATH
$NUD $ARGS signmessage $ADDRESS <$VOTE_PATH >$SIGNATURE_PATH
chmod 666 $VOTE_PATH $SIGNATURE_PATH
EOF
script_path = node.shared_path("votenotify.sh")
File.open(script_path, "w") { |f| f.write(script) }
File.chmod 0755, script_path
end
When(/^the data feed "(.*?)" returns the content of the dumped vote and signature on node "(.*?)"$/) do |arg1, arg2|
data_feed = @data_feeds[arg1]
node = @nodes[arg2]
vote_path = node.shared_path("vote.json")
signature_path = node.shared_path("vote.json.signature")
wait_for do
raise "no vote" unless File.exist?(vote_path)
vote = File.read(vote_path)
raise "no signature" unless File.exist?(signature_path)
signature = File.read(signature_path)
raise "empty vote" if vote.empty?
raise "empty signature" if signature.empty?
data_feed.set(vote)
data_feed.set_signature(signature)
true
end
end
|
class Item < ActiveRecord::Base
belongs_to :package
belongs_to :user
validates :name, presence: true
validates :brand, presence: true
validates :unit_price, presence: true
validates :quantity, presence: true
def self.unpacked_items(userid)
where("user_id == #{userid} and package_id is null")
end
end
|
module Cultivation
class UpdateTrayPlans
prepend SimpleCommand
attr_reader :current_user, :batch_id
def initialize(current_user, args = {})
args = {
batch_id: nil, # BSON::ObjectId, Batch.id
}.merge(args)
@batch_id = args[:batch_id].to_bson_id
@current_user = current_user
end
def call
if valid_params?
tray_plans.each do |plan|
schedule = booking_schedules.detect { |t| t.phase == plan.phase }
if schedule
plan.start_date = schedule.start_date
plan.end_date = schedule.end_date
plan.save
end
end
end
end
private
def batch
@batch ||= Cultivation::Batch.includes(:facility,
:tasks,
:tray_plans).find(@batch_id)
end
def tray_plans
@tray_plans ||= batch.tray_plans
end
def facility
@facility ||= batch.facility
end
def booking_schedules
@booking_schedules ||= Cultivation::QueryBatchPhases.call(batch).booking_schedules
end
def valid_params?
if @current_user.nil?
errors.add(:current_user, 'current_user is required')
end
if @batch_id.nil?
errors.add(:batch_id, 'batch_id is required')
end
errors.empty?
end
end
end
|
# source: https://launchschool.com/exercises/66216db8
# Q: Write a minitest assertion that will fail if the value.odd? is not true.
def test_odd_question
assert_equal(true, value.odd?)
end |
When /^(\d+) of (\d+) attacks succeed$/ do |success, total|
deaths = [true] * success + (all - count) * [false]
@attacker.kill_armies(@defender, deaths)
end
Then /^then attacker should have (\d+) armies left$/ do |d|
@attacker.game_player_country.armies.should == d.to_i
end
Then /^then defender should have (\d+) armies left$/ do |d|
@defender.game_player_country.armies.should == d.to_i
end
Then /^the defender should be owned by the attacker$/ do
@defender.game_player_country.game_player.should == @attacker.game_player_country.game_player
end
|
# frozen_string_literal: true
RSpec.describe ZoomSlack::ProcessDetector::Base do
describe ".for_platform" do
it "should return Mac instance" do
expect(ZoomSlack::ProcessDetector.for_platform).to be_instance_of(ZoomSlack::ProcessDetector::Mac)
end
end
describe "#running" do
it "should raise exception" do
expect { subject.running? }.to raise_error(NotImplementedError)
end
end
describe "#clean" do
it "should raise exception" do
expect { subject.clean }.to raise_error(NotImplementedError)
end
end
end
|
require 'spec_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by the Rails when you ran the scaffold generator.
describe CupsController do
def mock_cup(stubs={})
@mock_cup ||= mock_model(Cup, stubs).as_null_object
end
describe "GET index" do
it "assigns all cups as @cups" do
Cup.stub(:all) { [mock_cup] }
get :index
assigns(:cups).should eq([mock_cup])
end
end
describe "GET show" do
it "assigns the requested cup as @cup" do
Cup.stub(:find).with("37") { mock_cup }
get :show, :id => "37"
assigns(:cup).should be(mock_cup)
end
end
describe "GET new" do
it "assigns a new cup as @cup" do
Cup.stub(:new) { mock_cup }
get :new
assigns(:cup).should be(mock_cup)
end
end
describe "GET edit" do
it "assigns the requested cup as @cup" do
Cup.stub(:find).with("37") { mock_cup }
get :edit, :id => "37"
assigns(:cup).should be(mock_cup)
end
end
describe "POST create" do
describe "with valid params" do
it "assigns a newly created cup as @cup" do
Cup.stub(:new).with({'these' => 'params'}) { mock_cup(:save => true) }
post :create, :cup => {'these' => 'params'}
assigns(:cup).should be(mock_cup)
end
it "redirects to the created cup's user plot" do
Cup.stub(:new) { mock_cup(:drank_by => :somebody, :save => true) }
post :create, :cup => {:drank_by => :somebody}
response.should redirect_to(user_plot_url(:drank_by => :somebody))
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved cup as @cup" do
Cup.stub(:new).with({'these' => 'params'}) { mock_cup(:save => false) }
post :create, :cup => {'these' => 'params'}
assigns(:cup).should be(mock_cup)
end
it "re-renders the 'new' template" do
Cup.stub(:new) { mock_cup(:save => false) }
post :create, :cup => {}
response.should render_template("new")
end
end
end
describe "PUT update" do
describe "with valid params" do
it "updates the requested cup" do
Cup.stub(:find).with("37") { mock_cup }
mock_cup.should_receive(:update_attributes).with({'these' => 'params'})
put :update, :id => "37", :cup => {'these' => 'params'}
end
it "assigns the requested cup as @cup" do
Cup.stub(:find) { mock_cup(:update_attributes => true) }
put :update, :id => "1"
assigns(:cup).should be(mock_cup)
end
it "redirects to the cup" do
Cup.stub(:find) { mock_cup(:update_attributes => true) }
put :update, :id => "1"
response.should redirect_to(cup_url(mock_cup))
end
end
describe "with invalid params" do
it "assigns the cup as @cup" do
Cup.stub(:find) { mock_cup(:update_attributes => false) }
put :update, :id => "1"
assigns(:cup).should be(mock_cup)
end
it "re-renders the 'edit' template" do
Cup.stub(:find) { mock_cup(:update_attributes => false) }
put :update, :id => "1"
response.should render_template("edit")
end
end
end
describe "DELETE destroy" do
it "destroys the requested cup" do
Cup.stub(:find).with("37") { mock_cup }
mock_cup.should_receive(:destroy)
delete :destroy, :id => "37"
end
it "redirects to the cups list" do
Cup.stub(:find) { mock_cup }
delete :destroy, :id => "1"
response.should redirect_to(cups_url)
end
end
end
|
class AddCustomerToFormatType < ActiveRecord::Migration[5.0]
def change
add_reference :format_types, :customer, index: true
add_reference :format_types, :environment, index: true
end
end
|
# @param {Integer[]} nums1
# @param {Integer[]} nums2
# @return {Float}
def find_median_sorted_arrays(nums1, nums2)
array = (nums1 + nums2).sort
mid = array.length.to_f / 2
if array.length.odd?
return array[mid.floor]
else
return (array[mid-1] + array[mid]).to_f / 2
end
end
|
class BusinessesController < ApplicationController
before_action :signed_in_user, only: [:index]
before_action :admin_user, only: [:new, :create, :edit, :update, :destroy]
# GET /businesses
# GET /businesses.json
def index
@businesses = Business.all
end
# GET /businesses/1
# GET /businesses/1.json
def show
require 'open-uri'
require 'nokogiri'
@business = Business.find(params[:id])
url = "http://www.iconosquare.com/#{@business.name}"
data = Nokogiri::HTML(open(url))
unless data.at_css(".bio-user").nil?
@description = data.at_css(".bio-user").text.strip
end
@description ||= "For this business's Description please visit their instagram page"
unless data.at_css(".fullname").nil?
@title = data.at_css(".fullname").text.strip
end
@title ||= "This user is Private on Instagram :("
unless data.at_css(".bio-user").nil?
@image = data.xpath("//img/@src")[5].to_s
end
@image ||= "https://d13yacurqjgara.cloudfront.net/users/22251/screenshots/803201/no-photo-grey_1x.png"
end
# GET /businesses/new
def new
@business = Business.new
end
# GET /businesses/1/edit
def edit
@business = Business.find(params[:id])
end
# POST /businesses
# POST /businesses.json
def create
@business = Business.new(business_params)
respond_to do |format|
if @business.save
format.html { redirect_to @business, notice: 'Business was successfully created.' }
format.json { render :show, status: :created, location: @business }
else
format.html { render :new }
format.json { render json: @business.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /businesses/1
# PATCH/PUT /businesses/1.json
def update
@business = Business.find(params[:id])
if @business.update_attributes(business_params)
flash[:success] = "Business info updated"
redirect_to @business
else
render 'edit'
end
end
# DELETE /businesses/1
# DELETE /businesses/1.json
def destroy
Business.find(params[:id]).destroy
flash[:success] = "Business deleted."
redirect_to businesses_url
end
private
# Use callbacks to share common setup or constraints between actions.
def set_business
@business = Business.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def business_params
params.require(:business).permit(:name)
end
def signed_in_user
unless signed_in?
store_location
redirect_to signin_url, notice: "please sign in"
end
end
def admin_user
redirect_to(root_url) unless signed_in? && current_user.admin?
end
end
|
module Boilerpipe::SAX::TagActions
# for inline elements, which triggers some LabelAction on the
# generated TextBlock.
class InlineTagLabel
def initialize(label_action)
@label_action = label_action
end
def start(handler, name, attrs)
handler.append_space
handler.add_label_action(@label_action)
false
end
def end_tag(handler, name)
handler.append_space
false
end
def changes_tag_level?
false
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Actions::CreatePayment do
let(:user) { create :user }
let(:event) { create :event }
let(:reservation) { create :reservation, event: event, user: user }
describe 'call' do
let(:amount) { 100 }
let(:token) { 'token' }
let(:instance) { described_class.new(reservation_id: reservation.id, amount: amount, token: token) }
context 'valid operation' do
before do
result = Adapters::Payment::Gateway::Result.new(amount, 'EUR')
allow(Adapters::Payment::Gateway).to receive(:charge).and_return(result)
end
it 'creates payment record' do
expect { instance.call }.to change { Payment.count }.from(0).to(1)
end
it 'creates payment with proper attributes' do
instance.call
payment = Payment.first
expect(payment.reservation_id).to eq(reservation.id)
expect(payment.amount).to eq(amount)
expect(payment.currency).to eq('EUR')
end
it 'returns success response object' do
expect(instance.call).to be_instance_of(Actions::Response::Success)
end
it 'updates reservation status to paid' do
expect{ instance.call }.to change{ reservation.reload.state }.from('initialized').to('paid')
end
end
context 'operation raises error' do
it 'returns error response object' do
allow(Adapters::Payment::Gateway).to receive(:charge)
.and_raise(Adapters::Payment::Gateway::PaymentError)
expect(instance.call).to be_instance_of(Actions::Response::Error)
end
end
context 'error occured durring save payment record' do
let(:reservation) { double(id: 'fake_id') }
it 'returns error response object' do
expect(instance.call).to be_instance_of(Actions::Response::Error)
end
end
end
end
|
# encoding: utf-8
# language: ru
module NavigationHelpers
# Maps a name to a path. Used by the
#
# When /^I go to (.+)$/ do |page_name|
#
# step definition in web_steps.rb
#
def path_to(page_name)
case page_name
when /Главная/
'/'
when /Авторизация/
'/sign_in'
when /Регистрация/
'/sign_up'
when /Восстановление пароля/
'/recovery_passwd'
when /Вход/
'/sign_in'
when /Выход/
'/sign_out'
when /Новый пользователь/
'/users/new'
when /Профиль/, /Страница пользователя/
'/profile'
when /Пользователи/
'/users'
when /пользователя "(.+)"/
user_path(User.find_by_email $1)
when /Редактировать профиль "(.+)"/
edit_user_path(User.find_by_email $1)
when /Новая задача/
'/tasks/new'
when /Список задач/
'/tasks'
when /Выбор исполнителя/
'/tasks/executors'
when /редактирование задачи "(.+)"/
edit_task_path(Task.find_by_name $1)
when /задачи "(.+)"/
task_path(Task.find_by_name $1)
else
raise "Can't find mapping from \"#{page_name}\" to a path.\n" +
"Now, go and add a mapping in #{__FILE__}"
end
end
end
World(NavigationHelpers)
|
require 'spec_helper'
# There is no User class within Forem; this is testing the dummy application's class
# More specifically, it is testing the methods provided by Forem::DefaultPermissions
describe User do
subject { User.new }
describe Forem::DefaultPermissions do
it "can read forums" do
assert subject.can_read_forem_forums?
end
it "can read a given forum" do
assert subject.can_read_forem_forum?(Forem::Forum.new)
end
end
describe "Profile methods" do
context "with custom methods" do
describe "#forem_email" do
it "responds to our own email method" do
subject.should receive :email
subject.forem_email
end
end
describe "#forem_name" do
it "responds to our own name method" do
subject.should receive :login
subject.forem_name
end
end
end
context "with defaults" do
# Using a class without custom methods
subject { Refunery::Yooser.new }
before do
@original_class_name = Forem.user_class
Forem.user_class = "Refunery::Yooser"
Forem.decorate_user_class!
end
after do
Forem.user_class = @original_class_name.to_s
end
describe "#forem_email" do
it "defaults with 'email'" do
subject.should respond_to :forem_email
subject.should receive(:email)
subject.forem_email
end
end
describe "#forem_name" do
it "defaults with 'to_s'" do
subject.should respond_to :forem_name
subject.should receive :to_s
subject.forem_name
end
end
end
end
end
|
require 'sinatra'
require "sinatra/reloader" if development?
set :bind, ENV['VCAP_APP_HOST'] || "0.0.0.0"
set :port, ENV['PORT'] || "4567"
def greeting
ENV['GREETING'] || 'Howdy'
end
get '/' do
"#{greeting}!"
end
get '/:name' do
"#{greeting}, #{params[:name]}!"
end
|
require 'benchmark'
module RabbitJobs
# Module to include in client jobs.
module Job
attr_accessor :created_at
def expired?
exp_in = self.class.expires_in.to_i
return false if exp_in == 0 || created_at.nil?
Time.now.to_i > created_at + exp_in
end
def to_ruby_string(*params)
rs = self.class.name + params_string(*params)
rs << ", created_at: #{created_at}" if created_at
rs
end
private
def params_string(*params)
if params.count > 0
"(#{params.map(&:to_s).join(', ')})"
else
''
end
end
def log_job_error(error, *params)
RabbitJobs.logger.error(
short_message: (error.message.presence || 'rj_worker job error'),
_job: to_ruby_string,
_exception: error.class,
full_message: error.backtrace.join("\r\n"))
Airbrake.notify(error, session: { args: to_ruby_string(*params) }) if defined?(Airbrake)
end
def run_perform(*params)
ret = nil
execution_time = Benchmark.measure { ret = perform(*params) }
RabbitJobs.logger.info(
short_message: "Completed: #{to_ruby_string(*params)}",
_execution_time: execution_time.to_s.strip)
rescue ScriptError, StandardError
log_job_error($!, *params)
run_on_error_hooks($!, *params)
end
def run_on_error_hooks(error, *params)
return unless self.class.on_error_hooks.try(:present?)
self.class.on_error_hooks.each do |proc_or_symbol|
proc = if proc_or_symbol.is_a?(Symbol)
method(proc_or_symbol)
else
proc_or_symbol
end
begin
case proc.arity
when 0
proc.call
when 1
proc.call(error)
else
proc.call(error, *params)
end
rescue
RJ.logger.error($!)
end
end
end
class << self
def parse(payload)
encoded = JSON.parse(payload)
job_klass = encoded['class'].to_s.constantize
job = job_klass.new
job.created_at = encoded['created_at']
[job, encoded['params']]
rescue NameError
[:not_found, encoded['class']]
rescue JSON::ParserError
[:parsing_error, payload]
rescue
[:error, $!, payload]
end
def serialize(klass_name, *params)
{
'class' => klass_name.to_s,
'created_at' => Time.now.to_i,
'params' => params
}.to_json
end
def included(base)
base.extend(ClassMethods)
base.queue(:jobs)
end
# DSL method for jobs
module ClassMethods
def expires_in(seconds = nil)
@expires_in = seconds.to_i if seconds
@expires_in
end
attr_reader :on_error_hooks
def on_error(*hooks)
@on_error_hooks ||= []
hooks.each do |proc_or_symbol|
unless proc_or_symbol.is_a?(Proc) || proc_or_symbol.is_a?(Symbol)
fail ArgumentError.new, 'Pass proc or symbol to on_error hook'
end
@on_error_hooks << proc_or_symbol
end
end
def queue(routing_key)
fail ArgumentError, 'routing_key is blank' if routing_key.blank?
@rj_queue = routing_key.to_sym
end
def perform_async(*args)
RJ::Publisher.publish_to(@rj_queue, self, *args)
end
def perform(*params)
new.perform(*params)
end
end
end
end
end
|
FreshTomato::Application.routes.draw do
resources:movies
root :to => redirect('/movies')
end
|
json.type @folder.class.name
json.description 'A FavoriteFolder helps organize Submissions for a Profile.'
json.folder {
json.name {
json.description 'Folder name.'
json.type 'String'
json.required true
json.max_length 80
}
json.is_private {
json.description 'The Folder will be visiable only to the owning Profile.'
json.type 'Boolean'
json.default false
json.required false
}
}
json.example {
json.submission_folder {
json.name 'Baseball'
json.is_private false
}
}
json.post_url "#{imaginate_host_url}/profiles/{profile_id}/favorite_folders" |
require "spec_helper"
describe Song do
it "should have basic information" do
song =Song.create()
song.should respond_to :title
song.should respond_to :description
song.should respond_to :duration
song.should respond_to :track
song.should respond_to :file_location
end
it "Album can have many songs" do
album = Album.create()
album.song.create(:title => 'mysong')
album.song.create(:title => 'mysong2')
album.song.count.should == 2
end
it "belongs to song" do
should belong_to(:album)
end
end |
require 'rails_helper'
describe ServerController do
describe 'GET show' do
let(:action) { get :show }
it 'returns server data' do
action
end
end
end
|
class CreateLocationRelationships < ActiveRecord::Migration
def change
create_table :location_relationships do |t|
t.integer :location_id, null: false
t.integer :locatable_id, null: false
t.string :locatable_type, null: false
t.timestamps
end
add_index :location_relationships, [:locatable_id, :locatable_type],
{ name: 'locatable_index' }
end
end
|
class ProbesGrid
include Datagrid
scope do
Probe.order(:movie).order(:customer)
end
filter(:movie)
filter(:customer)
filter(:rating)
include ActionView::Helpers::UrlHelper
column(:movie) do |p|
ActionController::Base.helpers.link_to(p.movie, Rails.application.routes.url_helpers.movie_path(p.movie))
end
column(:title) do |p|
Movie.find(p.movie).title
end
column(:customer)
column(:date)
column(:rating)
Model.all.each do |m|
if m.state == "scored"
column(:"#{m.klass} prediction") do |p|
pred = Prediction.where(model: m.id, movie: p.movie, customer: p.customer).take
pred.nil? ? 0.0 : pred.prediction
end
end
end
end
|
class EventrinfosController < ApplicationController
before_action :load_user
before_action :ensure_proper_user, only: [:create, :edit, :update, :destroy]
def new
@eventrinfo = Eventrinfo.new
end
def create
# @eventrinfo = @user.eventrinfo.build(eventrinfo_params)
@eventrinfo = Eventrinfo.new(:first_name => eventrinfo_params[:first_name], :last_name => eventrinfo_params[:last_name],:bio => eventrinfo_params[:bio])
@eventrinfo.user = @cuser
if eventrinfo_params[:avatar] != nil
@user.avatar = eventrinfo_params[:avatar]
@user.save
end
if @eventrinfo.save
flash[:notice] = 'Eventr profile updated succesfully!'
redirect_to events_url
else
render :new
end
end
def edit
@eventrinfo = User.find(params[:id]).eventrinfo
end
def update
@eventrinfo = Eventrinfo.find(params[:id])
if @eventrinfo.update_attributes(:first_name => eventrinfo_params[:first_name], :last_name => eventrinfo_params[:last_name],:bio => eventrinfo_params[:bio])
if eventrinfo_params[:avatar] != nil
@user.avatar = eventrinfo_params[:avatar]
@user.save
end
redirect_to user_path(@user)
else
render :edit
end
end
def destroy
@eventrinfo = Eventrinfo.find(params[:id])
@eventrinfo.destroy
end
private
def eventrinfo_params
params.require(:eventrinfo).permit(:first_name, :last_name, :bio, :avatar)
end
def load_user
@user = User.find(params[:user_id])
end
def ensure_proper_user
@user = User.find(params[:user_id])
if @user != @cuser
flash[:alert] = "you do not have permission to access that page"
redirect_to root_path
end
end
end
|
ActiveAdmin.register VendorCode do
menu :priority => 7
permit_params :email, :code, :user_name, :name
index do
column "User Name", :user_name
column :email
column :code
column "Vendor", :name
column :created_at
column "" do |vendor_code|
links = ''.html_safe
links += link_to I18n.t('active_admin.edit'), edit_resource_path(vendor_code), :class => "member_link edit_link"
links += link_to I18n.t('active_admin.delete'), resource_path(vendor_code), :method => :delete, :confirm => I18n.t('active_admin.delete_confirmation'), :class => "member_link delete_link"
links
end
end
form do |f|
f.inputs "Vendor Code Details" do
f.input :user_name
f.input :email
f.input :code
f.input :name
end
f.actions
end
# filter :name, label: "Vendor", :as => :select, :collection => Vendor.all.map{|u| ["#{u.name}", u.name]}
filter :name, label: "Vendor"
filter :user_name, label: "User Name"
filter :email
filter :code
end
|
# Have the function ThirdGreatest(strArr) take the array of
# strings stored in strArr and return the third largest word
# within in. So for example: if strArr is ["hello", "world",
# "before", "all"] your output should be world because "before"
# is 6 letters long, and "hello" and "world" are both 5, but
# the output should be world because it appeared as the last 5
# letter word in the array. If strArr was ["hello", "world",
# "after", "all"] the output should be after because the first
# three words are all 5 letters long, so return the last one.
# The array will have at least three strings and each string
# will only contain letters.
def ThirdGreatest(strArr)
size = strArr.sort_by(&:length)[-3].length
strArr.group_by(&:size)[size].last
end
|
# Tealeaf Academy Prep Course
# Intro to Programming
# Exercises
# Exercise 16
a = ['white snow', 'winter wonderland', 'melting ice',
'slippery sidewalk', 'salted roads', 'white trees']
a_parsed = a.map {|phrase| phrase.split}.flatten
|
class Apcl < ActiveRecord::Base
self.table_name = "apcls"
self.primary_key = "apclsid"
has_many :apxs
end
|
class TweetsController < ApplicationController
before_action :set_tweet, only: %i[edit update destroy]
def index
@tweets = Tweet.all.select { |tweet| tweet.parent_id.nil? }
@tweet = Tweet.new
end
def show
@tweet = Tweet.find(params[:id])
@tweets = @tweet.replies
end
def create
@tweets = Tweet.all
@tweet = current_user.tweets.create(tweet_params)
if @tweet.save
redirect_to root_path
else
redirect_to root_path, notice: @tweet.errors.full_messages.join(', ')
end
end
def create_reply
@tweet = Tweet.find(params[:tweet_id])
@tweet_reply = @tweet.replies.new
@tweet_reply.body = params[:body]
@tweet_reply.user_id = current_user.id
if @tweet_reply.save
redirect_to @tweet
else
redirect_to @tweet, notice: @tweet_reply.errors.full_messages.join(', ')
end
end
# def edit; end
def update
if @tweet.update(tweet_params)
redirect_to root_path
else
render :edit, notice: @tweet.errors.full_messages.join(', ')
end
end
def destroy
@tweet.destroy
redirect_to root_path
end
private
def tweet_params
params.require(:tweet).permit(:body, :username, :name, :replies_count, :likes_count, :parent_id)
end
def set_tweet
@tweet = current_user.tweets.find(params[:id])
end
end
|
# Desenvolva uma classe que abstraia o funcionamento de uma conta bancária.
# Deve ser possivel:
# - Criar contas com no mínimo 50 reais
# - Depositar dinheiro
# - Sacar dinheiro
# - Transferir dinheiro
# Não deve ser possível:
# - Sacar mais so que se tem
# - Sacar ou depositar valores negativos
require 'test/unit'
class Conta
@saldo = 0
def saldo
@saldo
end
def initialize(valor)
validar_valor_para_criar_conta valor
@saldo = valor
end
def depositar(valor)
validar_valor_para_deposito valor
@saldo += valor
end
def sacar(valor)
validar_valor_para_saque valor
@saldo -= valor
end
def transferir(valor, conta)
self.sacar valor
conta.depositar valor
end
private
def validar_valor_para_saque(valor)
if valor < 0
raise ValorInvalidoError
end
if valor > @saldo
raise ValorNaoDisponivelError
end
end
def validar_valor_para_deposito(valor)
if valor < 0
raise ValorInvalidoError
end
end
def validar_valor_para_criar_conta(valor)
if valor < 50
raise ValorMinimoError
end
end
end
class ContaTest < Test::Unit::TestCase
def test_deve_criar_conta_com_valor
assert_raise ArgumentError do
Conta.new
end
end
def test_ao_criar_conta_com_30_ValorMinimoError
assert_raise ValorMinimoError do
Conta.new 30
end
end
def test_ao_criar_conta_com_10_ValorMinimoError
assert_raise ValorMinimoError do
Conta.new 10
end
end
def test_deve_criar_conta_com_50
assert_not_nil Conta.new 50
end
def test_deve_mostrar_saldo
@conta = Conta.new 50
assert_equal 50, @conta.saldo
end
def test_ao_depositar_20_saldo_fica_70
@conta = Conta.new 50
@conta.depositar 20
assert_equal 70, @conta.saldo
end
def test_ao_depositar_30_saldo_fica_80
@conta = Conta.new 50
@conta.depositar 30
assert_equal 80, @conta.saldo
end
def test_ao_depositar_20_depois_30_saldo_fica_100
@conta = Conta.new 50
@conta.depositar 20
@conta.depositar 30
assert_equal 100, @conta.saldo
end
def test_ao_depositar_negativo_ValorInvalidoError
@conta = Conta.new 50
assert_raise ValorInvalidoError do
@conta.depositar -30
end
end
def test_ao_sacar_10_saldo_fica_40
@conta = Conta.new 50
@conta.sacar 10
assert_equal 40, @conta.saldo
end
def test_ao_sacar_30_saldo_fica_20
@conta = Conta.new 50
@conta.sacar 30
assert_equal 20, @conta.saldo
end
def test_ao_sacar_negativo_ValorInvalidoError
@conta = Conta.new 50
assert_raise ValorInvalidoError do
@conta.sacar -30
end
end
def test_ao_sacar_60_ValorNaoDisponivelError
@conta = Conta.new 50
assert_raise ValorNaoDisponivelError do
@conta.sacar 60
end
end
def test_ao_sacar_70_ValorNaoDisponivelError
@conta = Conta.new 50
assert_raise ValorNaoDisponivelError do
@conta.sacar 70
end
end
def test_ao_transferir_20_contaA_fica_com_30_e_contaB_com_70
@contaA = Conta.new 50
@contaB = Conta.new 50
@contaA.transferir(20, @contaB)
assert_equal(30, @contaA.saldo)
assert_equal(70, @contaB.saldo)
end
def test_ao_transferir_70_ValorNaoDisponivelError
@contaA = Conta.new 50
@contaB = Conta.new 50
assert_raise ValorNaoDisponivelError do
@contaA.transferir(70, @contaB)
end
end
def test_ao_transferir_negativo_ValorInvalidoError
@contaA = Conta.new 50
@contaB = Conta.new 50
assert_raise ValorInvalidoError do
@contaA.transferir(-70, @contaB)
end
end
def test_ao_depositar_30_sacar_20_depsitar_80_transferir_100_emA_contaA_40_contaB_150
@contaA = Conta.new 50
@contaB = Conta.new 50
@contaA.depositar 30
@contaA.sacar 20
@contaA.depositar 80
@contaA.transferir 100, @contaB
assert_equal 40, @contaA.saldo
assert_equal 150, @contaB.saldo
end
end
class ValorMinimoError < RuntimeError
end
class ValorInvalidoError < RuntimeError
end
class ValorNaoDisponivelError < RuntimeError
end |
class Forms
class Session
include ActiveAttr::Model
attribute :email
attribute :password
validates :email, presence: true
validates :password, presence: true
end
end
|
# Build a program that randomly generates and prints Teddy's age. To get the age,
# you should generate a random number between 20 and 200.
# Understand the problem:
# Call the method
# Generate a rand num 20..200
# Print the number in a string
# Return value isn't used
# Test cases:
# "Teddy is 69 years old!"
# Inputs: none
# Outputs: String
# Data Structures:
# Random for generating number
# Integer for rand num
# String to print the num
# Logical Syntax
# START
# SET random num 20..200
# PRINT string including random number
# END
def teddy_age
puts "Give us a name!:"
name = gets.chomp.capitalize
name = 'Teddy' if name == ''
puts "#{name} is #{rand(20..200)} years old!"
end
teddy_age |
#!/usr/bin/env ruby
require 'pathname'
require 'fileutils'
TESTING = true
TVSHOWS_FOLDERS = [
"/Volumes/Data/Videos/TV\ Shows"
].freeze
ALLOWED_CHARS = /[^0-9A-Za-z]/
files = [
"/Volumes/Downloads/TV Shows/TV Shows - Favorites/The.Walking.Dead.S03E10.HDTV.XviD-AFG.avi",
]
$stdout.reopen('filemover-shows.log','a') unless TESTING
files.each do |file|
file_clean = file.gsub(ALLOWED_CHARS, '').downcase
moved = false
error = "No show folder founded for #{File.basename(file)}"
Pathname.new(TVSHOWS_FOLDERS[0]).children.select do |dir|
if dir.directory?
show_name = dir.basename.to_s.gsub(ALLOWED_CHARS, '').downcase
if file_clean.match(show_name)
season_number = file.scan(/\.S(\d{2})E\d{2}\./)[0]
if season_number
FileUtils.mkdir dir.to_s + "/Season #{season_number[0].to_i}", :noop => TESTING, :verbose => true unless File.directory?(dir.to_s + "/Season #{season_number[0].to_i}")
dest = dir.to_s + "/Season #{season_number[0].to_i}/#{File.basename(file)}"
FileUtils.cp file, dest, :noop => TESTING, :verbose => true
puts "#{Time.new.to_s} -- Moved! #{File.basename(file)} --> #{dest}"
moved = true
else
error = "No season number founded in #{File.basename(file)}"
end
break
end
end
end
if moved == false
puts "#{Time.new.to_s} -- ERROR: #{error}"
end
end |
include Bootcamp
describe Bootcamp::Book do
before :each do
@file_path = 'text.out'
@file = "sdfsd ds fsdf sdf \n sdf sdfsdf s dfg df g d\n df"
File.stub(:read).and_return(@file)
allow(File).to receive(:exist?).with(@file_path).and_return(true)
end
it 'performs valid operations with book file' do
book = Book.new
expect(book.createBook(@file_path)).to eq(true)
expect(book.getPage(1)).to eq("sdfsd ds\n======= page number 1 ========")
end
it 'corectly bookmarks the book' do
book = Book.new
book.createBook(@file_path)
book.bookMarkPage
book.skipPages(1)
book.bookMarkPage
expect(book.getBookmarks).to eq([1, 3])
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)
# Create a main sample user.
40.times do |m|
fake_name = Faker::Name.name
fake_email = Faker::Internet.email
fake_pw = Faker::University.name
poll_title = fake_name + "'s Poll"
@harry = User.create!(name: fake_name, email: fake_email, password: fake_pw, password_confirmation: fake_pw)
@harry_poll = Poll.create!(title: poll_title, user_id: @harry.id)
fake_name = Faker::Name.name
fake_email = Faker::Internet.email
fake_pw = Faker::University.name
@hermione = User.create!(name: fake_name, email: fake_email, password: fake_pw, password_confirmation: fake_pw)
4.times do |n|
quote = Faker::Movies::HarryPotter.quote
@q = Question.create!(text: "Who from Harry Potter said this: \n \"#{quote}\"", poll_id: @harry_poll.id)
3.times do |o|
chara = Faker::Movies::HarryPotter.character
@achoice = Answerchoice.create!(content: chara, question_id: @q.id)
Userchoice.create!(answerchoice_id: @achoice.id, user_id: @harry.id)
Userchoice.create!(answerchoice_id: @achoice.id, user_id: @hermione.id)
end
Answerchoice.create!(content: "None of the above.", question_id: @q.id)
end
end
|
FactoryGirl.define do
factory :supplement do
name { Faker::StarWars.planet }
description { Faker::StarWars.quote }
end
end
|
require "test_helper"
feature "As a user, I would like to see the details of memories" do
before do
@user = users :user_1
sign_in @user
end
scenario "users can view other user's memory details" do
# given one of another user's memories
@memory = memories :user2_memory
# when the user visits the detail page
visit memory_path(@memory)
# then the user can see that memory
page_must_include_memory(@memory)
end
end
|
class User < ActiveRecord::Base
has_many :authentications, :dependent => :destroy
has_many :credentials, :dependent => :destroy
has_many :trips, :dependent => :destroy
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
def apply_omniauth(omniauth)
Rails.logger.debug(omniauth['user_info'].inspect)
self.email = omniauth['user_info']['email'] if email.blank?
self.first_name = omniauth['user_info']['first_name'] if first_name.blank?
self.last_name = omniauth['user_info']['last_name'] if last_name.blank?
provider = Provider.find_by_code(omniauth['provider'])
authentications.build(:provider_id => provider.id, :uid => omniauth['uid'])
end
def password_required?
(authentications.empty? || !password.blank?) && super
end
def is_admin?
role == 'admin'
end
def credential_for(provider)
self.credentials.where(:provider_id => provider.id).first
end
def has_credential_for?(provider)
!!credential_for(provider)
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)
Product.delete_all
# . . .
Product.create!(title: 'Seven Mobile Apps in Seven Weeks',
description:
%{<p>
<em>Native Apps, Multiple Platforms</em>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam quis nulla pharetra, feugiat mi a, ullamcorper elit. Proin viverra risus enim, ac varius erat feugiat ut. Duis id nulla suscipit, consectetur turpis ac, rhoncus ante. Curabitur sodales dui sed magna posuere finibus. Vivamus efficitur odio in pharetra facilisis. Donec ac dictum dolor. Integer iaculis tincidunt ullamcorper. Proin id elit sit amet ligula convallis ultricies. Proin venenatis risus at sagittis iaculis. Etiam nec sem ac ex ultricies lacinia. Donec lacinia posuere congue. Aliquam pulvinar ligula et egestas interdum. Morbi varius est ac nunc suscipit, vel interdum diam pharetra.
</p>},
image_url: '7apps.jpg',
price: 26.00)
# . . . |
module EulerSolution
def run
raise 'Not implemented'
end
end
def execute(problem)
start_time = Time.now
result = problem.run
end_time = Time.now
puts "Result: #{result}"
puts "Time: #{((end_time - start_time) * 1000).to_i}ms"
end |
FactoryGirl.define do
factory :email_user do
email {Faker::Internet.email}
association :user
end
end
|
class AddColumnsSpot < ActiveRecord::Migration[5.1]
def change
add_column :spots, :bathrooms, :string
add_column :spots, :bedrooms, :string
add_column :spots, :beds, :string
end
end
|
FactoryBot.define do
factory :address do
trait :invalid do
valid false
after(:build) { |address| address.errors.add(:street, "can't be blank") }
end
end
end
|
require_relative "lib/characterize/version"
Gem::Specification.new do |spec|
spec.name = "characterize"
spec.version = Characterize::VERSION
spec.authors = ["Jim Gay"]
spec.email = ["jim@saturnflyer.com"]
spec.description = "Use plain modules like presenters"
spec.summary = "Use plain modules like presenters"
spec.homepage = "https://github.com/saturnflyer/characterize"
spec.license = "MIT"
spec.require_paths = ["lib"]
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/saturnflyer/characterize"
spec.metadata["changelog_uri"] = "https://github.com/saturnflyer/characterize/blob/master/CHANGELOG.md"
spec.files = Dir.chdir(File.expand_path(__dir__)) do
Dir["{app,config,db,lib}/**/*", "LICENSE.txt", "Rakefile", "README.md"]
end
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.add_dependency "casting", "~> 1.0.2"
spec.add_dependency "rails", ">= 6.1"
spec.add_dependency "direction"
end
|
require 'date'
class Logger
def self.log(text, include_timestamp=true)
if include_timestamp
puts "#{DateTime.now.to_s} - #{text}"
else
puts text
end
end
end
|
class CreateFineCancelTrackers < ActiveRecord::Migration
def self.up
create_table :fine_cancel_trackers do |t|
t.integer :user_id
t.decimal :amount, :precision => 5, :scale => 1, :default => 0
t.integer :finance_id
t.string :finance_type
t.date :date
t.integer :transaction_id
t.timestamps
end
end
def self.down
drop_table :fine_cancel_trackers
end
end
|
require 'test_helper'
class AboutUsControllerTest < ActionDispatch::IntegrationTest
setup do
@about_u = about_us(:one)
end
test "should get index" do
get about_us_url
assert_response :success
end
test "should get new" do
get new_about_u_url
assert_response :success
end
test "should create about_u" do
assert_difference('AboutU.count') do
post about_us_url, params: { about_u: { } }
end
assert_redirected_to about_u_url(AboutU.last)
end
test "should show about_u" do
get about_u_url(@about_u)
assert_response :success
end
test "should get edit" do
get edit_about_u_url(@about_u)
assert_response :success
end
test "should update about_u" do
patch about_u_url(@about_u), params: { about_u: { } }
assert_redirected_to about_u_url(@about_u)
end
test "should destroy about_u" do
assert_difference('AboutU.count', -1) do
delete about_u_url(@about_u)
end
assert_redirected_to about_us_url
end
end
|
class Admin::BlogsController < Admin::AdminController
before_filter :set_previous_path, only: [:new, :edit]
helper_method :previous_path
def index
@blogs = Blog.order('created_at desc')
end
def new
@blog = Blog.new
end
def show
@blog = Blog.find(params[:id])
end
def edit
@blog = Blog.find(params[:id])
end
def create
@blog = Blog.new(params[:blog].merge(user_id: current_user.id))
if @blog.save
flash[:success] = "Successfully created blog"
redirect_to admin_blogs_path
else
flash[:error] = @blog.errors.full_messages.join(', ')
render :new
end
end
def update
@blog = Blog.find(params[:id])
if @blog.update_attributes(params[:blog])
flash[:success] = "Successfully updated blog"
redirect_to admin_blog_path(@blog)
else
flash[:error] = @blog.errors.full_messages.join('<br/>')
render :edit
end
end
def destroy
@blog = Blog.find(params[:id])
if @blog.destroy
flash[:success] = 'Blog has been successfully deleted'
else
flash[:error] = 'There were errors deleting your blog. Please try again'
end
redirect_to admin_blogs_path
end
def previous_path
session[:return_to]
end
private
def set_previous_path
session[:return_to] = request.referer
end
end |
class UsersController < ApplicationController
skip_before_action :authenticate_user, only: [:create]
def show
user = current_user
render json: {userId: user.id, username: user.username, email: user.email, friendcode: user.friendcode}
end
def create
user = User.new(auth_params)
if user.save
jwt = Auth.issue({user_id: user.id})
render json: {jwt: jwt, userId: user.id, username: user.username, email: user.email, friendcode: user.friendcode}
else
render json: {error: "Account creation failed."}
end
end
def update
user = current_user
if user.update(edit_params)
render json: {userId: user.id, username: user.username, email: user.email, friendcode: user.friendcode}
else
render json: {message: "Account edit failed"}
end
end
def destroy
User.destroy(current_user)
render json: {message: "Account deleted"}
end
private
def auth_params
params.require(:auth).permit(:email, :username, :friendcode, :password)
end
def edit_params
params.require(:user).permit(:email, :friendcode, :password)
end
end
|
class CheckoutController < ApplicationController
def new
@book = Book.find_by(slug: params[:book])
end
def create
if current_user.street_address.nil?
flash[:notice] = "Please update your address to checkout."
redirect_to account_settings_path
else
book = Book.find_by(slug: params[:book])
loan = Loan.new(user_id: current_user.id, book_id: book.id)
if loan.save
redirect_to myaccount_path
else
redirect_to root_path
end
end
end
end
|
require 'rack/test'
require File.join(File.dirname(__FILE__), 'arabic_number_translator.rb')
set :environment, :test
def app
Sinatra::Application
end
describe 'Arabic Number Translator' do
include Rack::Test::Methods
it "should be valid" do
get '/'
last_response.body.should =~ /Western numerals using Arabic number characters/
end
it "should return the correct content-type when viewing root" do
get '/'
last_response.headers["Content-Type"].should == "text/html;charset=utf-8"
end
it "should return 404 when page cannot be found" do
get '/404'
last_response.status.should == 404
end
it "respond to json" do
post '/json', { :page => { :arabic => "2" }, :commit => "Convert 2 English" }
last_response.should be_ok
last_response.body.should == '{"page":{"arabic":"2","western":"two"}}'
end
it "respond to xml" do
post '/xml', { :page => { :arabic => "2"}, :commit => "Convert 2 English" }
last_response.should be_ok
last_response.body.should == '<?xml version="1.0" encoding="UTF-8"?>
<page>
<arabic>
<![CDATA[2]]>
</arabic>
<western>
<![CDATA[two]]>
</western>
</page>
'
end
it "respond proper json if spanish if requested" do
post '/json', { :page => { :arabic => "2" }, :commit => "Convert 2 Spanish" }
last_response.should be_ok
last_response.body.should == '{"page":{"arabic":"2","western":"dos"}}'
end
it "respond proper xml if spanish if requested" do
post '/xml', { :page => { :arabic => "2"}, :commit => "Convert 2 Spanish" }
last_response.should be_ok
last_response.body.should == '<?xml version="1.0" encoding="UTF-8"?>
<page>
<arabic>
<![CDATA[2]]>
</arabic>
<western>
<![CDATA[dos]]>
</western>
</page>
'
end
end
|
require 'command_test'
class TestGenerateLocalizationArchive < CommandTest
def new_runner(twine_file = nil, options = {})
options[:output_path] = @output_path
options[:format] = 'apple'
unless twine_file
twine_file = build_twine_file 'en', 'fr' do
add_section 'Section' do
add_definition key: 'value'
end
end
end
Twine::Runner.new(options, twine_file)
end
def test_generates_zip_file
new_runner.generate_localization_archive
assert File.exist?(@output_path), "zip file should exist"
end
def test_zip_file_structure
new_runner.generate_localization_archive
names = []
Zip::File.open(@output_path) do |zipfile|
zipfile.each do |entry|
names << entry.name
end
end
assert_equal ['Locales/', 'Locales/en.strings', 'Locales/fr.strings'], names
end
def test_uses_formatter
formatter = prepare_mock_formatter Twine::Formatters::Apple
formatter.expects(:format_file).twice
new_runner.generate_localization_archive
end
def test_prints_empty_file_warnings
empty_twine_file = build_twine_file('en') {}
new_runner(empty_twine_file).generate_localization_archive
assert_match "Skipping file", Twine::stdout.string
end
def test_does_not_print_empty_file_warnings_if_quite
empty_twine_file = build_twine_file('en') {}
new_runner(empty_twine_file, quite: true).generate_localization_archive
refute_match "Skipping file", Twine::stdout.string
end
class TestValidate < CommandTest
def new_runner(validate)
options = {}
options[:output_path] = @output_path
options[:format] = 'android'
options[:validate] = validate
twine_file = build_twine_file 'en' do
add_section 'Section' do
add_definition key: 'value'
add_definition key: 'value'
end
end
Twine::Runner.new(options, twine_file)
end
def test_does_not_validate_twine_file
prepare_mock_formatter Twine::Formatters::Android
new_runner(false).generate_localization_archive
end
def test_validates_twine_file_if_validate
assert_raises Twine::Error do
new_runner(true).generate_localization_archive
end
end
end
end
|
class StudentRollNumber
def self.validate_if_roll_number_already_taken(stud_id, suffix, student_hash, batch_id)
roll_number = suffix[:roll_number]
in_student_hash = student_hash.select{|id, val| id != stud_id.to_s && val["roll_number"] == roll_number.to_s && val["roll_number"].present?}
if in_student_hash.present?
@err_msg[stud_id] = "Roll Number Already taken"
@errors << stud_id
end
end
def self.validate_roll_number (roll_number)
student = Student.new
student.roll_number = roll_number
student.valid?
student.errors['roll_number']
end
def self.save(roll_number_prefix, batch_id, student_hash)
@errors = []
@current_values = {}
@err_msg = {}
if student_hash.present?
student_hash.each do |stud_id, suffix|
@current_values[stud_id] = suffix[:roll_number]
validate_if_roll_number_already_taken(stud_id, suffix, student_hash,batch_id)
end
if @errors.empty?
ActiveRecord::Base.transaction do
Student.update_all({:roll_number => nil},['batch_id = ?', "#{batch_id}"])
students = Student.find_all_by_batch_id(batch_id)
student_hash.each do |stud_id, suffix|
stud_record = students.detect{|x| x.id.to_s == stud_id}
stud_record.roll_number = roll_number_prefix + suffix[:roll_number]
v_errors = validate_roll_number(stud_record.roll_number)
@current_values[stud_id] = suffix[:roll_number]
unless v_errors.blank?
@errors << stud_id
@err_msg[stud_id] = v_errors
else
stud_record.send :update_without_callbacks
end
end
raise ActiveRecord::Rollback unless @errors.blank?
end
end
end
ensure
return [] if @errors.empty?
return [@errors,@current_values,@err_msg]
end
end |
require 'addressable/uri'
require "downloader/util"
require 'downloader/loggable'
module Downloader
# Helper class for extracting and/or manipulating URL segments.
# Uses Addressable::URI for parsing.
class UrlHelper
extend Loggable
# Returns +url+ with extraneous special characters removed.
#
# Currently only strips whitespace on both ends of +url+.
#
# @param url [String] the URL
# @return [String] the URL minus special characters, or the empty string if URL is nil
def self.sanitize(url)
return "" unless url
url.strip
end
# Returns the filename to be used for the file at +url+.
#
# Sets the file basename to +number+ if +numbered_filenames+ is true, otherwise returns the original filename.
# File extensions are left intact if present.
#
# Raises a UriError if the URL is nil/empty.
#
# @param url [String] the URL
# @param numbered_filenames [Boolean] determines whether the filename portion of the URL will be replaced with a number
# @param number [Numeric] the number to be used in the filename if +numbered_filenames+ is true
# @return [String] the original filename, or the filename with the base replaced by +number+
#
# Example:
#
# create_filename("https://example.com/cats/bleh.jpg", true, 1)
# # => "1.jpg"
def self.create_filename(url, numbered_filenames, number)
raise UriError, "Missing URL" if url.nil? || url.empty?
# logger.debug("Create numbered filenames? #{numbered_filenames}")
original_filename = extract_filename(url)
numbered_filenames ?
Util.rename_to_number(original_filename, number) :
original_filename
end
# Returns an Addressable::URI object with the host and scheme set.
# - the host is extracted from +url+
# - the scheme can be passed in via +user_scheme+ (eg, from the command-line options) or extracted from +url+
#
# Raises a UriError if either scheme or host are missing or can't be extracted.
#
# @param url [String] the URL
# @param user_scheme [String] the URL's scheme passed in via command-line
# @return [Addressable::URI] an Addressable::URI object with the host and scheme set
#
# Example:
#
# extract_host_with_scheme("https://example.com/cats")
# # => #<Addressable::URI:0x2b11e0125d14 URI:https://example.com>
def self.extract_host_with_scheme(url, user_scheme=nil)
uri = Addressable::URI.parse(sanitize(url))
host = uri.host
scheme = user_scheme || uri.scheme
raise UriError, "Missing scheme" unless scheme
raise UriError, "Missing host" if host.nil? || host.empty?
Addressable::URI.new(host: host, scheme: scheme)
end
# Returns the filename portion of +url+.
#
# Raises a UriError if the filename can't be extracted.
#
# @param url [String] the URL
# @return [String] the filename portion of the URL
#
# Example:
#
# extract_filename("https://example.com/cats/catting.jpg")
# # => "catting.jpg"
def self.extract_filename(url)
uri = Addressable::URI.parse(sanitize(url)).normalize
filename = uri.basename
raise UriError, "Cannot extract filename from URL: #{url}" if filename.nil? || filename.empty?
filename
end
# Returns an Addressable::URI object containing the path portion of +url+.
# Includes the query and fragment portions if present.
#
# Raises a UriError if the path can't be extracted.
#
# @param url [String] the URL
# @return [Addressable::URI] an Addressable::URI object with the path set
#
# Example:
#
# extract_relative_ref("https://example.com/cats/catting.jpg")
# # => "/cats/catting.jpg"
def self.extract_relative_ref(url)
uri = Addressable::URI.parse(sanitize(url))
raise UriError, "Cannot extract path from URL: #{url}" if uri.path.nil? || uri.path.empty?
relative_ref = Addressable::URI.parse(uri.path)
relative_ref.query ||= uri.query
relative_ref.fragment ||= uri.fragment
relative_ref
end
end
end
|
class ChangedUsersAddedUgroupsCountAndDeletedGroupsCount < ActiveRecord::Migration
def self.up
add_column :users, :ugroups_count, :integer
remove_column :users, :groups_count
end
def self.down
add_column :users, :groups_count, :integer, :limit=>nil, :default=>nil
remove_column :users, :ugroups_count
end
end
|
class Users::RegistrationsController < ::Devise::RegistrationsController
layout 'user'
respond_to :html, :json
before_action :configure_sign_up_parameters, if: :devise_controller?
after_action :transfer_guest_user_cart, if: -> { session[:guest_user_id].present? }
def create
build_resource(sign_up_params)
resource_saved = resource.save
yield resource if block_given?
if resource_saved
set_flash_message :notice, :signed_up
sign_in(resource_name, resource)
@redirect_to_path = request.referer
session[:registered] = true
respond_to do |format|
format.js { render 'users/registrations/success' }
end
else
# Errors occurred while registration
clean_up_passwords resource
@validatable = devise_mapping.validatable?
@minimum_password_length = resource_class.password_length.min if @validatable
respond_to do |format|
format.js { render 'users/registrations/error' }
end
end
end
protected
def configure_sign_up_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:first_name, :last_name, :email, :password, :password_confirmation, :phone_number) }
end
def after_update_path_for(resource)
root_path
end
def transfer_guest_user_cart
transfer_guest_user_records_to_logged_in_user(resource)
end
end
|
root = Rails.root.to_s
namespace :db do
desc 'Disconnect everyone from postgres database'
task drop_connections: :environment do
cnf = YAML.load_file(root + '/config/database.yml')[Rails.env]
if cnf['adapter'] != 'postgresql'
puts 'db:drop_connections(): Current database is not PostgreSQL! Ignoring this task...'
next
end
PostgresConnectionHelper::drop_all_connections cnf['database'], cnf['username'], cnf['password']
end
end |
class UserEventsController < ApplicationController
respond_to :json
def create
begin
user_event = UserEvent.new(params[:user_event])
user_event.record
respond_with user_event
rescue ArgumentError => error
logger.info("#{error}")
respond_with :status => :bad_request
end
end
end
|
class Notice < ApplicationRecord
belongs_to :user
belongs_to :kind, polymorphic: true,
optional: true
default_scope -> { order(updated_at: :desc) }
validates :user_id, presence: true
validates :kind_id, presence: true
validates :kind_type, presence: true
def add_unread_count!
increment!(:unread_count, by = 1).touch
end
def get_post
case self.kind_type
when "ReplyCom", "NormalCom"
return Comment.find_by(id: self.kind_id)
when "ReplyPost"
return Kickspost.find_by(id: self.kind_id)
when "Comment", "Kickspost"
return self.kind
else
return nil
end
end
end
|
namespace :tag_stat do
desc "default task"
task default: :environment do
Tag.each do |t|
TagStatWorker.perform_async(t.name)
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.