text
stringlengths
10
2.61M
# require 'pry' require_relative './game' require_relative './game_storage' require_relative './stat_tracker' module GameStats def goal_differiential(away_goals, home_goals, team_id) games = get_games_for_a_team(team_id) diff = 0 games.each do |game| if game.away_team_id == team_id diff = (away_goals.to_i - home_goals.to_i).abs elsif game.home_team_id == team_id diff = (home_goals.to_i - away_goals.to_i).abs end end diff end def get_games_for_a_team(team_id) @games.values.find_all do |game| game.home_team_id == team_id || game.away_team_id end end def biggest_blowout#win; maybe game_team & use win/lose column blowout_1 = 0 @teams.values.each do |team| blowout = @games.values.max_by do |game| goal_differiential(game.away_goals, game.home_goals, team.teamid) end blowout_1 = goal_differiential(blowout.away_goals,blowout.home_goals, team.teamid) end blowout_1 end def biggest_team_blowout(team_id) blowout_1 = 0 @teams.values.each do |team| blowout = @games.values.max_by do |game| goal_differiential(game.away_goals, game.home_goals, team_id) end blowout_1 = goal_differiential(blowout.away_goals,blowout.home_goals, team_id) end blowout_1 end def best_season(collection = @games, team_id) wins = wins_by_season(collection, team_id) best = wins.max_by do |season, num_wins| num_wins end best = best[1] wins.key(best) end def worst_season(collection = @games, team_id) wins = wins_by_season(collection, team_id) worst = wins.min_by do |season, num_wins| num_wins end worst = worst[1] wins.key(worst) end def wins(collection = @games, team_id) wins = 0 collection.values.each do |game| if (game.outcome.include?("home win") && game.home_team_id == team_id) || (game.outcome.include?("away win") && game.away_team_id == team_id) wins += 1 end end wins end def losses(collection = @games, team_id) loses = 0 collection.values.each do |game| if (game.outcome != "home win" && game.home_team_id == team_id) || (game.outcome != "away win" && game.away_team_id == team_id) loses += 1 end end loses end def wins_by_season(collection = @games, team_id) wins = 0 wins_by_season = Hash.new(0) collection.values.each do |game| if (game.outcome.include?("home win") && game.home_team_id == team_id) || (game.outcome.include?("away win") && game.away_team_id == team_id) wins_by_season[game.season] = (wins += 1) end end wins_by_season end def win_percentage(collection = @games, team_id) wins = wins(collection, team_id) total_games = collection.values.count do |game| game.game_id.to_i end (wins.to_f / total_games.to_f) * 100 end # def find_home_team_goals_from_games(collection = @games, team_id) # goals = 0 # collection.values.find_all do |game| # if game.home_team_id == team_id # goals += game.home_goals.to_i # end # end # goals # end def percentage_home_wins total_games_played = @games.keys.count total_home_games_won = @games.values.select do |game| game.outcome.include?("home") end (total_home_games_won.count.to_f / total_games_played.to_f).round(2) end def percentage_visitor_wins total_games_played = @games.keys.count total_visitor_games_won = @games.values.select do |game| game.outcome.include?("away") end (total_visitor_games_won.count.to_f / total_games_played.to_f).round(2) end def create_hash_by_season total_games_by_season = @games.values.group_by do |game| game.season end total_games_by_season end def season_with_most_games season_with_most_games = create_hash_by_season.keys.max do |season_1, season_2| create_hash_by_season[season_1].count <=> create_hash_by_season[season_2].count end season_with_most_games.to_i end def season_with_fewest_games season_with_fewest_games = create_hash_by_season.keys.min do |season_1, season_2| create_hash_by_season[season_1].count <=> create_hash_by_season[season_2].count end season_with_fewest_games.to_i end def count_of_games_by_season count_of_games_by_season = {} total_games_by_season = @games.values.group_by do |game| game.season end total_games_by_season.keys.each do |season| count_of_games_by_season.store(season.to_s, total_games_by_season[season].count) end count_of_games_by_season end def win_loss(team_id) h2h = {} w = wins(team_id) l = losses(team_id) t = get_team_name_from_id(team_id) h2h[t] = "#{w}:#{l}" h2h end def head_to_head(team_id, opponent_id) head_to_head = {} t = win_loss(team_id) o = win_loss(opponent_id) head_to_head[t.keys] = t.values.flatten head_to_head[o.keys] = o.values.flatten head_to_head end #needed to set up most/least popular venue def sort_games_by_venue venues = [] @games.each do |game| venues << game[1].venue end venues end #needed to set up most/least popular venue def order_games_by_venue most_popular_venue = Hash.new(0) sort_games_by_venue.each do |venue| most_popular_venue[venue] += 1 end most_popular_venue end def most_popular_venue popular_venue_array = [] popular_venue_array = order_games_by_venue.sort_by do |key, value| value end popular_venue_array[-1][0] end def least_popular_venue unpopular_venue_array = [] unpopular_venue_array = order_games_by_venue.min_by do |key, value| value end unpopular_venue_array[0] end #needed to setup avg goals per game def total_goals_per_game total_goals = 0.00 @games.each do |game| total_goals += (game[1].away_goals.to_f + game[1].home_goals.to_f) end total_goals end def average_goals_per_game #avg_goals_per_game average_goals = 0.00 average_goals = total_goals_per_game / @games.length.to_f average_goals.round(2) end def get_home_team_score_hash hash = Hash.new(0) @games.values.each do |game| hash[game.home_team_id] = game.home_goals.to_i end hash end def highest_scoring_home_team hash = get_home_team_score_hash team_id = hash.key(hash.values.sort.last) get_team_name_from_id(team_id) end def lowest_scoring_home_team hash = Hash.new(0) @games.values.each do |game| hash[game.home_team_id] = [0, 0] end @games.values.each do |game| counter = hash[game.home_team_id] starting_value = counter[0] game_counter = counter[1] counter[0] = (starting_value += game.home_goals.to_i) game_counter += 1 counter[1] = game_counter hash[game.home_team_id][0] = counter[0] hash[game.home_team_id][1] = counter[1] end home = Hash.new hash.each do |teamid, game_info| variable = game_info[0].to_f / game_info[1].to_f home[teamid] = variable.round(2) end home_team = home.sort_by do |teamid, average| average end get_team_name_from_id(home_team.first[0]) end def get_away_team_score_hash hash = Hash.new(0) @games.values.each do |game| hash[game.away_team_id] = [0, 0] end @games.values.each do |game| counter = hash[game.away_team_id] starting_value = counter[0] game_counter = counter[1] counter[0] = (starting_value += game.away_goals.to_i) game_counter += 1 counter[1] = game_counter hash[game.away_team_id][0] = counter[0] hash[game.away_team_id][1] = counter[1] end hash end def lowest_scoring_visitor visitors = Hash.new get_away_team_score_hash.each do |teamid, game_info| variable = game_info[0].to_f / game_info[1].to_f visitors[teamid] = variable.round(2) end visiting_team = visitors.sort_by do |teamid, average| average end get_team_name_from_id(visiting_team.first[0]) end def highest_scoring_visitor visitors = Hash.new get_away_team_score_hash.each do |teamid, game_info| variable = game_info[0].to_f / game_info[1].to_f visitors[teamid] = variable.round(2) end visiting_team = visitors.sort_by do |teamid, average| average end get_team_name_from_id(visiting_team.last[0]) end def highest_total_score sum = @games.values.max_by { |game| game.away_goals.to_i + game.home_goals.to_i } sum.away_goals.to_i + sum.home_goals.to_i end def lowest_total_score sum = @games.values.min_by { |game| game.away_goals.to_i + game.home_goals.to_i } sum.away_goals.to_i + sum.home_goals.to_i end def group_by_team_id @game_teams.values.group_by { |game| game.team_id } end def goals_scored_from_game_teams @game_teams.values.inject(Hash.new(0)) do |goals_by_team, game| goals_by_team[game.team_id.to_i] += game.goals.to_i goals_by_team end end def all_seasons @games.values.map do |game| game.season end.uniq end def goals_scored(team_id = "3", the_season = all_seasons) @games.values.inject(0) do |goals_scored, game| if game.home_team_id == team_id && game.season == the_season goals_scored += game.home_goals.to_i elsif game.away_team_id == team_id && game.season == the_season goals_scored += game.away_goals.to_i else goals_scored end end end def goals_against(team_id = "3", the_season = all_seasons) @games.values.inject(0) do |goals_against, game| if game.home_team_id == team_id && game.season == the_season goals_against += game.away_goals.to_i elsif game.away_team_id == team_id && game.season == the_season goals_against += game.home_goals.to_i else goals_against end end end def total_wins(team_id = "3", the_season = all_seasons) @games.values.inject(0) do |wins, game| if game.home_team_id == team_id && game.outcome.include?("home win") && the_season.include?(game.season) wins += 1 elsif game.away_team_id == team_id && game.outcome.include?("away win") && the_season.include?(game.season) wins += 1 else wins end end end def total_game_count(team_id = "3", the_season = all_seasons) @games.values.inject(0) do |total, game| if game.home_team_id == team_id && the_season.include?(game.season) total += 1 elsif game.away_team_id == team_id && the_season.include?(game.season) total += 1 end total end end def average_goals_scored(team_id = "3", the_season = all_seasons) goals_scored(team_id = "3", the_season = all_seasons).to_f / total_game_count(team_id = "3", the_season = all_seasons).to_f end def average_goals_against(team_id = "3", the_season = all_seasons) goals_against(team_id = "3", the_season = all_seasons).to_f / total_game_count(team_id = "3", the_season = all_seasons).to_f end def win_percentage_helper(team_id = "3", the_season = all_seasons) if total_game_count(team_id, the_season) > 0 (total_wins(team_id, the_season).to_f / total_game_count(team_id, the_season)).round(2) else 0.0 end end def season_summary(team_id = "3", the_season = all_seasons) summary = {} seasons = [] seasons << the_season s = seasons.flatten.sort s.each do |season| summary = @games.values.inject(Hash.new(0)) do |stats, game| game_type = if game.type == 'R' :regular_season elsif game.type = 'P' :preseason end stats[game_type] = {win_percentage: win_percentage_helper(team_id = "3", season), goals_scored: goals_scored(team_id, season), goals_against: goals_against(team_id, season) } stats end summary end summary end def average_goals_per_game_per_season average_goals_per_game_per_season = {} @games.values.each do |game| average_goals_per_game_per_season[game.season] = 0 end @games.values.each do |game| average_goals_per_game_per_season[game.season] += game.home_goals.to_i + game.away_goals.to_i end average_goals_per_game_per_season end def average_goals_by_season average_goals_by_season = {} count_of_games_by_season.each do |season, count| # binding.pry average_goals_by_season[season.to_s] = (average_goals_per_game_per_season[season.to_s].to_f / count.to_f).round(2) end average_goals_by_season end def preseason_game_hash(collection, season) preseason_game_hash = collection.to_h array_of_preseason_games = [] collection.to_h.values.each do |game| if game.type == "P" && game.season == season array_of_preseason_games << game end end preseason_game_hash.values.each do |game| if array_of_preseason_games.include?(game) == false preseason_game_hash.delete(preseason_game_hash.key(game)) end end preseason_game_hash end def regular_season_game_hash(collection, season) regular_season_game_hash = collection.to_h regular_season_game_hash.delete_if do |game_id, game| game.type == "P" || game.season != season end regular_season_game_hash end def create_team_id_array(collection, season) team_id_array = [] collection.to_h.each do |game_id, game| if game.season == season team_id_array << game.home_team_id team_id_array << game.away_team_id end end team_id_array.uniq end def biggest_bust(season) collection = @games.to_a regular_season_game_hash(collection, season) preseason_game_hash(collection, season) win_percentage_by_team_and_season = {} create_team_id_array(collection, season).each do |team_id| win_percentage_by_team_and_season[team_id] = win_percentage(preseason_game_hash(collection, season), team_id) - win_percentage(regular_season_game_hash(collection, season), team_id) end biggest_decrease = win_percentage_by_team_and_season.max_by do |team_id, win| win end name_of_team_with_biggest_bust = "" @teams.values.each do |team| if team.teamid == biggest_decrease[0] name_of_team_with_biggest_bust = team.teamName end end name_of_team_with_biggest_bust end def biggest_surprise(season) collection = @games.to_a regular_season_game_hash(collection, season) preseason_game_hash(collection, season) win_percentage_by_team_and_season = {} create_team_id_array(collection, season).each do |team_id| win_percentage_by_team_and_season[team_id] = win_percentage(regular_season_game_hash(collection, season), team_id) - win_percentage(preseason_game_hash(collection, season), team_id) end biggest_increase = win_percentage_by_team_and_season.max_by do |team_id, win| win end name_of_team_with_biggest_surprise = "" @teams.values.each do |team| if team.teamid == biggest_increase[0] name_of_team_with_biggest_surprise = team.teamName end end name_of_team_with_biggest_surprise end def team_id_from_team_name(name) team_id = "" @teams.values.each do |team| if team.teamName == name team_id = team.teamid end end team_id end def array_of_losses(collection = @games, team_id) losses = [] collection.values.each do |game| if (game.outcome.start_with?("away win") && game.home_team_id == team_id) || (game.outcome.start_with?("home win") && game.away_team_id == team_id) losses << game end end losses end def array_of_opponents(collection = @games, teamid, input) array_of_opponents = [] input.each do |game| if game.home_team_id == teamid array_of_opponents << game.away_team_id.to_i elsif game.away_team_id == teamid array_of_opponents << game.home_team_id.to_i end end array_of_opponents end def rival(teamname) team_id_from_team_name(teamname) input = array_of_losses(team_id_from_team_name(teamname)) rival_team_id_hash = Hash.new(0) array_of_opponents(team_id_from_team_name(teamname), input).each do |opponent| rival_team_id_hash[opponent] += 1 end rival_team_id_hash_value = rival_team_id_hash.values.max rival_team_id = rival_team_id_hash.key(rival_team_id_hash_value).to_s rival_team_name = "" @teams.values.each do |team| if team.teamid == rival_team_id rival_team_name = team.teamName end end rival_team_name end def array_of_wins(collection = @games, team_id) wins = [] collection.values.each do |game| if (game.outcome.start_with?("away win") && game.away_team_id == team_id) || (game.outcome.start_with?("home win") && game.home_team_id == team_id) wins << game end end wins end def favorite_opponent(teamname) team_id_from_team_name(teamname) input = array_of_wins(team_id_from_team_name(teamname)) favorite_opponent_team_id_hash = Hash.new(0) array_of_opponents(team_id_from_team_name(teamname), input).each do |opponent| favorite_opponent_team_id_hash[opponent] += 1 end favorite_opponent_team_id_hash_value = favorite_opponent_team_id_hash.values.max favorite_opponent_team_id = favorite_opponent_team_id_hash.key(favorite_opponent_team_id_hash_value).to_s favorite_opponent = "" @teams.values.each do |team| if team.teamid == favorite_opponent_team_id favorite_opponent = team.teamName end end favorite_opponent end end
# NOTE: Application has "admin" user only # admin's password can be changed from browser, but user name "admin" can't be changed. # many clients can login at the same time (App has multiple active sessions) # raw password shouldn't be compromised (except default password) # you may find detail at https://github.com/treasure-data/fluentd-ui/pull/34 class User include ActiveModel::Model SALT = "XG16gfdC5IFRaQ3c".freeze ENCRYPTED_PASSWORD_FILE = FluentdUI.data_dir + "/#{Rails.env}-user-pwhash.txt" attr_accessor :name, :password, :password_confirmation, :current_password validates :name, presence: true validates :password, length: { minimum: 8 } validate :valid_current_password validate :valid_password_confirmation def authenticate(unencrypted_password) return false if @name != "admin" digest(unencrypted_password) == stored_digest end def digest(unencrypted_password) unencrypted_password ||= "" hash = Digest::SHA1.hexdigest(SALT + unencrypted_password) stretching_cost.times do hash = Digest::SHA1.hexdigest(hash + SALT + unencrypted_password) end hash end def stored_digest if File.exist?(ENCRYPTED_PASSWORD_FILE) File.read(ENCRYPTED_PASSWORD_FILE).rstrip else digest(Settings.default_password) end end def update_attributes(params) params.each_pair do |key, value| send("#{key}=", value) end return false unless valid? File.open(ENCRYPTED_PASSWORD_FILE, "w") do |f| f.write digest(password) end end def valid_current_password unless authenticate(current_password) errors.add(:current_password, :wrong_password) end end def valid_password_confirmation if password != password_confirmation errors.add(:password, :confirmation, attribute: User.human_attribute_name(:password_confirmation)) end end def stretching_cost Rails.env.test? ? 1 : 20000 end end
module QuestionsHelper def form_header(question) title = question.new_record? ? 'Create new' : 'Edit' "#{title} #{question.quiz.title} question" end end
class Pokemon < ActiveRecord::Base has_and_belongs_to_many :search_areas self.primary_key = :pokeid def self.import(file) CSV.foreach(file.path, headers: true) do |row| pokemon_hash = row.to_hash # exclude the price field pokemon = Pokemon.where(id: pokemon_hash["id"]) if pokemon.count == 1 pokemon.first.update_attributes(pokemon_hash) else Pokemon.create!(pokemon_hash) end # end if !product.nil? end # end CSV.foreach end # end self.import(file) def self.open_spreadsheet(file) case File.extname(file.original_filename) when ".csv" then Roo::CSV.new(file.path, csv_options: {encoding: "iso-8859-1:utf-8"}) when ".xls" then Roo::Excel.new(file.path, nil, :ignore) when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore) else raise "Unknown file type: #{file.original_filename}" end end end
class Customer < ApplicationRecord has_many :invoices has_many :transactions, through: :invoices has_many :merchants, through: :invoices def favorite_merchant merchants.select("merchants.*, transactions.count AS succ_transactions") .joins(invoices: :transactions) .where(transactions: { result: 'success' }) .group(:id) .order("succ_transactions DESC") .first end end
class Device < ActiveRecord::Base belongs_to :customer has_and_belongs_to_many :accounting_categories validates :number, length: { minimum: 5 } def self.import_export_columns blacklist = %w{ customer_id id heartbeat hmac_key hash_key additional_data model_id deferred deployed_until device_model_mapping_id transfer_token carrier_rate_plan_id } #faster then reqexp (column_names - blacklist).reject{ |c| c.ends_with?('_at') } # Reject timestamps end def self.lookup_relation_ids_by_customer(customer) lookups = {} import_export_columns.select{|col| col.ends_with?('_id')}.each do |col| case col when 'device_make_id' then lookups[col] = Hash[DeviceMake.pluck(:name, :id)] when 'device_model_id' then lookups[col] = Hash[DeviceModel.pluck(:name, :id)] else reflections.each do |k, reflection| if reflection.foreign_key == col method = reflection.plural_name.to_sym if customer.respond_to?(method) accessor = reflection.klass.respond_to?(:export_key) ? reflection.klass.send(:export_key) : 'name' lookups[col] = Hash[customer.send(method).pluck(accessor, :id)] end end end end end lookups end def self.invalid_accounting_types_in_csv(contents, lookups) errors = {} row = CSV.parse_line(contents, headers: true, encoding: 'UTF-8') row.headers.each do |header| if header =~ /accounting_categories\[([^\]]+)\]/ and !lookups.key?(header) errors['General'] = ["'#{$1}' is not a valid accounting type"] break end end errors end def self.parse_csv(contents, lookups) data = {} errors = {} begin CSV.parse(contents, headers: true, encoding: 'UTF-8').each_with_index do |parsed_row, idx| if parsed_row['number'].to_s.strip.empty? (errors['General'] ||= []) << "An entry around line #{idx} has no number" next end row_hash = parsed_row.to_hash # Hardcode the number, just to make sure we don't run into issues dev_number = row_hash['number'] = row_hash['number'].gsub(/\D+/,'') if data[dev_number] (errors[dev_number] ||= []) << "Is a duplicate entry" next end # remove ' =" " ' from values row_hash.each{ |k,v| row_hash[k] = v =~ /^="(.*?)"/ ? $1 : v } # converts string t or f into boolean # This is postgres-specific row_hash.each{ |k,v| row_hash[k] = ['t','f'].include?(v) ? (v == 't') : v } # move accounting_category to accounting_categories and deletes col # replace value(name) w/ id(from lookups) accounting_categories = [] row_hash.dup.select{|k,_| lookups.key?(k)}.each do |k,v| if k =~ /accounting_categories\[(.*?)\]/ accounting_category_name = $1 accounting_category_code_id = lookups[k][v.to_s.strip] if accounting_category_code_id accounting_categories << accounting_category_code_id else (errors[dev_number] ||= []) << "New \"#{accounting_category_name}\" code: \"#{v}\"" end row_hash.delete(k) else row_hash[k] = lookups[k][v] end end # sets ids for accounting_category relation row_hash['accounting_category_ids'] = accounting_categories if accounting_categories.any? #(looks like key maybe empty?(column w/o header?)) data[dev_number] = row_hash.select{ |k,_| k } end rescue => e errors['General'] = [e.message] end [data, errors] end def self.import(contents, customer, current_user, clear_existing_data) errors = {} flash = {} lookups = customer.lookup_accounting_category errors = invalid_accounting_types_in_csv(contents, lookups) return [flash, errors] if errors.any? lookups.merge!(lookup_relation_ids_by_customer(customer)) data, errors = parse_csv(contents, lookups) transaction do # validate the devices w/ same numbers do not belong other customer duplicate_numbers = unscoped.where(number: data.select{|_,v|v['status'] != 'cancelled'}.keys).where.not(status: 'cancelled').where.not(customer_id: customer.id) duplicate_numbers.each do |device| (errors[device.number] ||= []) << "Duplicate number. The number can only be processed once, please ensure it's on the active account number." end return [flash, errors] if errors.any? updated_devices = customer.devices.where(number: data.keys).to_a deleted_devices_ids = clear_existing_data ? customer.devices.map(&:id) - updated_devices.map(&:id) : [] updated_devices.each do |device| device.assign_attributes(data[device.number].merge(customer_id: customer.id)) end created_devices = [] updated_devices_numbers = updated_devices.map(&:number) data.select{|k,_| !updated_devices_numbers.include?(k) }.each do |dev_number, attributes| created_devices << new(attributes.merge(customer_id: customer.id)) end updated_or_created_devices = (updated_devices + created_devices) updated_or_created_devices.each do |device| unless device.valid? errors[device.number] = device.errors.full_messages end end raise ActiveRecord::Rollback if errors.any? updated_or_created_devices.each do |device| device.track!(created_by: current_user, source: "Bulk Import") { device.save(validate: false) } end Device.where(id: deleted_devices_ids).delete_all if deleted_devices_ids.any? flash[:notice] = "Import successfully completed. #{updated_or_created_devices.length} lines updated/added. #{deleted_devices_ids.length} lines removed." end [flash, errors] end def cancelled? status == 'cancelled' end def track!(params, &block) yield end end
require 'rails_helper' RSpec.describe Service, type: :model do it 'is invalid without jurisdiction' do service = Fabricate(:service) service.jurisdiction_id = nil service.save expect(service).to_not be_valid end it 'is invalid without service_type' do service = Fabricate(:service) service.service_type = nil service.save expect(service).to_not be_valid end it 'has a service definition with a matching service code' do service = Fabricate(:service) expect(service.service_definition).to_not be_nil expect(service.service_definition.service_code).to eq(service.service_code) end end
# frozen_string_literal: true require 'grpc/health/checker' require 'griffin/interceptors/server/clear_connection_interceptor' require 'griffin/interceptors/server/filtered_payload_interceptor' require 'griffin/interceptors/server/logging_interceptor' require 'griffin/interceptors/server/x_request_id_interceptor' require 'griffin/interceptors/server/timeout_interceptor' app_id = ENV['APPLICATION_ID'] || 'main-grpc' port = ENV['PORT'] || 8081 health_check_service = Grpc::Health::Checker.new health_check_service.add_status(app_id, Grpc::Health::V1::HealthCheckResponse::ServingStatus::SERVING) if Rails.env.development? && ARGV[0]&.include?('Griffin::Server') Rails.application.runner do # Send logs to stdout like `rails s` # https://guides.rubyonrails.org/initialization.html#rails-server-start console = ActiveSupport::Logger.new($stdout) console.formatter = Rails.logger.formatter console.level = Rails.logger.level Rails.logger.extend(ActiveSupport::Logger.broadcast(console)) end end pool_min, pool_max = *(ENV['GRIFFIN_THREAD_SIZE'] || '10,10').split(',', 2).map(&:to_i) connection_min, connection_max = *(ENV['GRIFFIN_CONNECTION_SIZE'] || '1,3').split(',', 2).map(&:to_i) worker_size = (ENV['GRIFFIN_WORKER_SIZE'] || 2).to_i if worker_size < 2 Rails.logger.warn("Unexpected worker size (via GRIFFIN_WORKER_SIZE): #{worker_size}. If you want to enable graceful reloading, set GRIFFIN_WORKER_SIZE greater than 1.") end interceptors = [ Rails.env.development? ? nil : Griffin::Interceptors::Server::TimeoutInterceptor.new(30), Griffin::Interceptors::Server::FilteredPayloadInterceptor.new(filter_parameters: Rails.configuration.filter_parameters), Griffin::Interceptors::Server::LoggingInterceptor.new, Griffin::Interceptors::Server::ClearConnectionInterceptor.new, Griffin::Interceptors::Server::XRequestIdInterceptor.new, ].compact if Rails.env.production? && worker_size >= 2 && ENV['MEMORY_LIMIT_MIN'] && ENV['MEMORY_LIMIT_MAX'] memory_limit_min = ENV.fetch('MEMORY_LIMIT_MIN').to_i memory_limit_max = ENV.fetch('MEMORY_LIMIT_MAX').to_i interceptors << Griffin::Interceptors::Server::WorkerKillerInterceptor.new(memory_limit_min: memory_limit_min, memory_limit_max: memory_limit_max) end Griffin::Server.configure do |c| c.bind('0.0.0.0') c.port(port) c.services([ health_check_service, RecipeService, UserService, ]) c.interceptors(interceptors) c.workers(worker_size) c.pool_size(pool_min, pool_max) c.connection_size(connection_min, connection_max) c.log('-') # STDOUT c.log_level(Rails.logger.level) end
DB = Sequel.connect('mysql2://root@localhost/amazing_cache') module DBHelper module_function def count sdata.count end def sdata DB[:sdata] end def insert(params) sdata.insert(params) end def update(id, params) sdata.where(id: id).update(params) end def create_table! sql = <<-SQL CREATE TABLE `sdata` ( `id` bigint(20) unsigned NOT NULL DEFAULT 0, `name` varchar(64) DEFAULT NULL, `kind` bigint(20) unsigned DEFAULT NULL, `value` decimal(10,2) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; SQL DB.run('DROP TABLE IF EXISTS sdata') DB.run(sql) end end
require 'spec_helper' describe Roe::Client do use_vcr_cassette "client", :record => :new_episodes describe '.new' do it 'initializes with a url' do client = Roe::Client.new('http://www.youtube.com/oembed') client.endpoint.should eq('http://www.youtube.com/oembed') end it 'defaults the format to json' do client = Roe::Client.new('http://www.youtube.com/oembed') client.format.should eq(:json) end it 'accepts an optional format argument' do client = Roe::Client.new('http://www.youtube.com/oembed', :xml) client.format.should eq(:xml) end end describe '#resolve' do it 'returns a Hashie::Rash' do client = Roe::Client.new('http://vimeo.com/api/oembed.json') client.resolve('http://vimeo.com/7100569').should be_kind_of(Hashie::Rash) end it 'returns oembed data using json format' do client = Roe::Client.new('http://www.hulu.com/api/oembed.json') data = client.resolve('http://www.hulu.com/watch/20807/late-night-with-conan-obrien-wed-may-21-2008') data.embed_url.should be end it 'returns oembed data using xml format' do client = Roe::Client.new('http://www.hulu.com/api/oembed.xml', :xml) data = client.resolve('http://www.hulu.com/watch/20807/late-night-with-conan-obrien-wed-may-21-2008') data.embed_url.should be end it 'raises a Faraday error when passing invalid arguments' do client = Roe::Client.new('http://vimeo.com/api/oembed.json') lambda { client.resolve('123') }.should raise_error end end end
# -*- coding: utf-8 -*- module Plugin::Intent class Intent < Diva::Model field.string :slug, required: true # Intentのslug field.string :label, required: true field.string :model_slug, required: true end end
require 'minitest/autorun' require "minitest/reporters" Minitest::Reporters.use! =begin Write a minitest assertion that will fail if the value.odd? is not true. =end =begin S - setup the necessary objects E - execute the code agaist the object being tested A - assert the results of the execution T - Tear down and clean up any lingering artifacts =end class TestOdd < Minitest::Test def setup @value = 1 end def test_integer_is_odd assert(@value.odd?, 'value is not odd') end def test_integer_is_odd_option_two assert_equal(true, @value.odd?) end end
require 'rails_helper' describe "post a location route", :type => :request do before do post '/locations', params: { :country => 'Mexico', :city => 'Mexico City' } end it 'returns the country' do expect(JSON.parse(response.body)['country']).to eq('Mexico') end it 'returns the city' do expect(JSON.parse(response.body)['city']).to eq('Mexico City') end it 'returns a created status' do expect(response).to have_http_status(:created) end end
class Game < ApplicationRecord has_many :formats, dependent: :destroy has_many :leagues, through: :formats has_many :maps, dependent: :destroy validates :name, presence: true, uniqueness: true, length: { in: 1..128 } end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Venn::Diagram do let(:diagram) { Venn::Diagram.new } it "should exist" do Venn::Diagram.nil?.must_equal false end [:a, :b].to_objects {[ [[1, 2], [3, 4]], [[5, 6], [7, 8]] ]}.each do |test| describe "no match" do before do diagram.a_is test.a diagram.b_is test.b end it "should return set a" do diagram.a_only.must_equal test.a end it "should return set b" do diagram.b_only.must_equal test.b end it "should return nothing for a and b" do diagram.a_and_b.must_equal [] end end end [:a, :b, :a_only, :b_only, :a_and_b].to_objects {[ [[1, 2], [2, 3], [1], [3], [2]], [['a', 'b'], ['b', 'c'], ['a'], ['c'], ['b']] ]}.each do |test| describe "one match" do before do diagram.a_is test.a diagram.b_is test.b end it "should return a" do diagram.a_only.must_equal test.a_only end it "should return b" do diagram.b_only.must_equal test.b_only end it "should return the one match for a and b" do diagram.a_and_b.must_equal test.a_and_b end end end describe "three sets of data with a few matches" do describe "first example" do before do diagram.a_is ['abc', 'ab', 'ac', 'a'] diagram.b_is ['abc', 'ab', 'bc', 'b'] diagram.c_is ['abc', 'bc', 'ac', 'c'] end it "should return a" do diagram.a_only.must_equal ['a'] end it "should return b" do diagram.b_only.must_equal ['b'] end it "should return c" do diagram.c_only.must_equal ['c'] end it "should return a and b" do diagram.a_and_b.must_equal ['ab'] end it "should return b and c" do diagram.b_and_c.must_equal ['bc'] end it "should return a and c" do diagram.a_and_c.must_equal ['ac'] end it "should return a and b and c" do diagram.a_and_b_and_c.must_equal ['abc'] end end describe "second example" do before do diagram.a_is ['xyz', 'xy', 'xz', 'x'] diagram.b_is ['xyz', 'xy', 'yz', 'y'] diagram.c_is ['xyz', 'yz', 'xz', 'z'] end it "should return a" do diagram.a_only.must_equal ['x'] end it "should return b" do diagram.b_only.must_equal ['y'] end it "should return c" do diagram.c_only.must_equal ['z'] end it "should return a and b" do diagram.a_and_b.must_equal ['xy'] end it "should return b and c" do diagram.b_and_c.must_equal ['yz'] end it "should return a and c" do diagram.a_and_c.must_equal ['xz'] end it "should return a and b and c" do diagram.a_and_b_and_c.must_equal ['xyz'] end end end describe "setting values with are" do before do diagram.a_are ['a'] end it "should have set the value" do diagram.a_only.must_equal ['a'] end end describe "setting values with more than one letter" do before do diagram.good_items_are ['a', 'b'] diagram.bad_items_are ['b', 'c'] end it "should have set the value" do diagram.good_items_only.must_equal ['a'] diagram.bad_items_only.must_equal ['c'] diagram.good_items_and_bad_items.must_equal ['b'] end end describe "a more complex example" do before do diagram.fizz_items_are [3, 6, 9, 12, 15, 18, 21] diagram.buzz_items_are [5, 10, 15, 20, 25, 30, 35] end it "should return the expected results" do diagram.fizz_items_only [3, 6, 9, 12, 18, 21] diagram.buzz_items_only [5, 10, 20, 25, 30, 35] diagram.fizz_items_and_buzz_items [15] end end end
require 'rails_helper' feature 'Tasks CRUD' do before :each do User.destroy_all user = User.new(first_name: 'Bob', last_name: 'Dole', email: 'bob@dole.com', password: 'bob', admin: true) user.save! visit root_path click_link 'Sign In' fill_in :email, with: 'bob@dole.com' fill_in :password, with: 'bob' click_button 'Sign In' project = Project.create!(name: 'Sunshine') Membership.create!(user_id: user.id, project_id: project.id, role: 'Owner') task = project.tasks.create(description: "Finish this project", due_date: '2015-04-02') end scenario 'Users can create new task' do visit projects_path expect(page).to have_content 'Tasks' expect(page).to have_content 'Sunshine' within('.table') { click_link 'Sunshine' } expect(page).to have_content '1 task' click_link '1 task' click_link 'New Task' expect(page).to have_content "New Task" fill_in :task_description, with: "Anything you want" fill_in :task_due_date, with: "02/03/2015" click_button 'Create Task' expect(page).to have_content "Anything you want" end scenario 'User can edit tasks' do visit projects_path expect(page).to have_content 'Sunshine' within('.table') { click_link 'Sunshine' } expect(page).to have_content '1 task' click_link '1 task' click_link 'New Task' expect(page).to have_content "New Task" fill_in :task_description, with: "Anything you want" fill_in :task_due_date, with: "02/03/2015" click_button 'Create Task' within('.table') { click_on 'Anything you want' } click_on 'Edit' fill_in :task_description, with: "run errrands" fill_in :task_due_date, with: "02/04/2015" click_button 'Update Task' expect(page).to have_content "Task was successfully updated" end scenario 'display error messages and validate task fields' do visit projects_path expect(page).to have_content 'Tasks' expect(page).to have_content 'Sunshine' within('.table') { click_link 'Sunshine' } expect(page).to have_content '1 task' click_link '1 task' click_link 'New Task' click_button 'Create Task' expect(page).to have_content "1 error prohibited this form from being saved:" end end
require 'byebug' class MaxIntSet def initialize(max) @max = max @store = Array.new(max + 1, false) end def insert(num) validate!(num) @store[num] = true end def remove(num) validate!(num) @store[num] = false end def include?(num) validate!(num) @store[num] end private def is_valid?(num) num <= @max && num >= 0 end def validate!(num) raise "number is out of bounds of array" if !is_valid?(num) end end class IntSet def initialize(num_buckets = 20) @store = Array.new(num_buckets) { Array.new } end def insert(num) self[num] << num if self[num].empty? self[num].each.with_index do |integer,index| if num != integer self[num] << num end end end def remove(num) self[num].each.with_index do |integer,index| if num == integer self[num].delete_at(index) end end end def include?(num) self[num].each.with_index do |integer,index| return true if num == integer end false end private def [](num) bucket_index = num % num_buckets bucket = @store[bucket_index] end def num_buckets @store.length end end class ResizingIntSet attr_reader :count_eles def initialize(num_buckets = 1) @store = Array.new(num_buckets) { Array.new } @count_eles = 0 end def insert(num) @count_eles += 1 if @count_eles > @store.length new_store = new_buckets re_mod(new_store) @store = new_store end self[num] << num end def remove(num) self[num].each_with_index do |el, idx| self[num].delete_at(idx) if el == num end end def include?(num) self[num].each_with_index do |el, idx| return true if el == num end false end def new_buckets num_buckets = @store.length * 2 new_store = Array.new(num_buckets) { [] } end def re_mod(new_store) @store.each do |bucket| bucket.each do |ele| new_bucket_index = ele % new_store.length new_store[new_bucket_index] << ele end end end private def [](num) bucket_index = num % num_buckets bucket = @store[bucket_index] end def num_buckets @store.length end # def resize! # end end
require 'spec_helper' feature "viewing bookmarks" do scenario "accesing a list of links" do Link.create(:title => 'title',:url => 'link') visit '/links' expect(page).to have_content('title') expect(page).to have_content('link') end end
require 'rails_helper' RSpec.describe UserTeam, type: :model do describe 'validations' do it 'requires a team_id and user_id' do user_team = build(:user_team, user_id: nil, team_id: nil) expect(user_team.valid?).to eq(false) expect(user_team.errors.full_messages).to eq([ "User must exist", "Team must exist", "User can't be blank", "Team can't be blank" ]) end end describe 'relationships' do it 'belongs to a user' do user_team = create(:user_team) expect(user_team.user.id).to_not eq(nil) end it 'belongs to a team' do user_team = create(:user_team) expect(user_team.team.id).to_not eq(nil) end end end
# Meld cards very-closely resemble Flip cards class MeldCard < FlipCard def parse_collector_num # Use standard numbering for "front side" of meld cards return super if self.container_index == 0 other_cnum = other_container.css("[id$=\"numberRow\"] .value").text.strip other_cnum.gsub('a', 'b') # Second container is always b-side of meld end # Similar to double-faced cards, the flavor text on meld cards is # formatted differently from every other card. def parse_flavor_text return FLAVOR_TEXT_OVERRIDES[self.multiverse_id] if FLAVOR_TEXT_OVERRIDES[self.multiverse_id] textboxes = container.css('[id$="flavorRow"] .cardtextbox') textboxes.map{|t| t.text.strip}.select(&:present?).join("\n").presence end MELD_MULTIVERSE_ID = { 414304 => 414305, # Bruna, the Fading Light => Brisela, Voice of Nightmares 414319 => 414305, # Gisela, the Broken Blade => Brisela, Voice of Nightmares 414386 => 414392, # Graf Rats => Chittering Host 414391 => 414392, # Midnight Scavengers => Chittering Host 414428 => 414429, # Hanweir Garrison => Hanweir, the Writhing Township 414511 => 414429, # Hanweir Battlements => Hanweir, the Writhing Township } def as_json(options={}) return super unless self.container_index.blank? [ self.class.new(self.multiverse_id, self.page, 0), self.class.new(MELD_MULTIVERSE_ID[self.multiverse_id], self.page, 1) ].map(&:as_json) end end
require 'spec_helper' describe FeedItemsHelper do before (:each) do @group = Factory(:group) @group.save! @user = Factory(:user) @user.save! end it "should convert an entry in the user feed (using first person text) for when a user creates a group" do @group.add_creator(@user) feed_item = @user.feed.feed_items.where( :user_id => @user.id, :feed_type => :user_built_hub, :referenced_model_id => @group.id ).first feed_item_to_text( feed_item, :first_person => true ).should == "You built the #{@group.name} Hub" end it "should convert an entry in the user feed (using first person text) for when a user leaves a group" do @group.add_user(@user) @group.remove_user(@user) feed_item = @user.feed.feed_items.where( :user_id => @user.id, :feed_type => :user_left_hub, :referenced_model_id => @group.id ).first feed_item_to_text( feed_item, :first_person => true ).should == "You left the #{@group.name} Hub" end it "should convert an entry in the user feed (using first person text) for when a user joins a group" do @group.add_user(@user) feed_item = @user.feed.feed_items.where( :user_id => @user.id, :feed_type => :user_joined_hub, :referenced_model_id => @group.id ).first feed_item_to_text( feed_item, :first_person => true ).should == "You became a member of the #{@group.name} Hub" end end
# Preview all emails at http://localhost:3000/rails/mailers/thanks class ThanksPreview < ActionMailer::Preview # Preview this email at http://localhost:3000/rails/mailers/thanks/thank_you def thank_you ThanksMailer.thank_you end end
FactoryGirl.define do factory :country do name 'United States of America' code 'US' end end
class AddAllowEmailSearchToUser < ActiveRecord::Migration def self.up add_column :users, :allow_email_search, :boolean User.update_all('allow_email_search=1') end def self.down remove_column :users, :allow_email_search end end
require 'watir-webdriver' class CustomerCheck # class constants STORE_CODE = "default/" attr_accessor :domain def initialize(domain = "https://demo.itnova.nl/") @domain = domain end def login(user, pass) puts "login. User: #{user}"; # open browser b = Watir::Browser.new b.goto @domain + STORE_CODE + 'customer/account/login/' # fill and submit form b.text_field(:id => 'email').set(user) b.text_field(:id => 'pass').set(pass) b.button(:name => 'send').click b.button(:name => 'send').wait_while_present # button does not dissapear when password is incorrect. # Wait for account text on page Watir::Wait.until { b.text.include? 'Account' } if b.div(:class => "dashboard").exists? return true else filename = 'customer_' + Time.now.strftime + '%y-%m-%d_%H%M%S.png' browser.screenshot.save filename puts 'Customer test failed screenshot saved as "' + filename + '"' end end end if __FILE__ == $0 check = CustomerCheck.new puts 'Login check: ' + check.login('edwin.koster@kega.nl','banaan1').to_s end
Rails.application.routes.draw do devise_for :administrators devise_for :users mount RailsAdmin::Engine => '/admin', as: 'rails_admin' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: 'goods#index' resources :goods end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception helper :all #setting @current_user variable to be used in UsersController based on which session was created def check_user_login if session[:patient_id] @current_user = User.find(session[:patient_id]) @dr_schedule_made = [] elsif session[:doctor_id] @current_user = User.find(session[:doctor_id]) @dr_schedule_made = DrAvailability.where(doctor_id: @current_user) end end def check_current_doctor if session[:doctor_id] @current_doctor = User.find(session[:doctor_id]) else @current_doctor = params[:doctor_id] end end def check_dr_schedule_made if @current_user if @current_user.type=="Doctor" && !@dr_schedule_made.any? redirect_to new_dr_availability_path end end end end
require 'rails_helper' # https://github.com/internetee/registry/issues/576 RSpec.describe 'EPP contact:update' do let(:registrar) { create(:registrar) } let(:user) { create(:api_user_epp, registrar: registrar) } let(:session_id) { create(:epp_session, user: user).session_id } let(:ident) { contact.identifier } let(:request) { post '/epp/command/update', { frame: request_xml }, 'HTTP_COOKIE' => "session=#{session_id}" } let(:request_xml) { <<-XML <?xml version="1.0" encoding="UTF-8" standalone="no"?> <epp xmlns="https://epp.tld.ee/schema/epp-ee-1.0.xsd"> <command> <update> <contact:update xmlns:contact="https://epp.tld.ee/schema/contact-ee-1.1.xsd"> <contact:id>TEST</contact:id> <contact:chg> <contact:postalInfo> <contact:name>test</contact:name> </contact:postalInfo> </contact:chg> </contact:update> </update> <extension> <eis:extdata xmlns:eis="https://epp.tld.ee/schema/eis-1.0.xsd"> <eis:ident cc="US" type="priv">test</eis:ident> </eis:extdata> </extension> </command> </epp> XML } before do sign_in user end context 'when contact ident is valid' do context 'when submitted ident matches current one' do let!(:contact) { create(:contact, code: 'TEST', ident: 'test', ident_type: 'priv', ident_country_code: 'US') } specify do request expect(epp_response).to have_result(:success) end end context 'when submitted ident does not match current one' do let!(:contact) { create(:contact, code: 'TEST', ident: 'another-test', ident_type: 'priv', ident_country_code: 'US') } it 'does not update code' do expect do request contact.reload end.to_not change { ident.code } end it 'does not update type' do expect do request contact.reload end.to_not change { ident.type } end it 'does not update country code' do expect do request contact.reload end.to_not change { ident.country_code } end specify do request expect(epp_response).to have_result(:data_management_policy_violation, t('epp.contacts.errors.valid_ident')) end end end context 'when contact ident is invalid' do let(:contact) { build(:contact, code: 'TEST', ident: 'test', ident_type: nil, ident_country_code: nil) } before do contact.save(validate: false) end context 'when submitted ident is the same as current one' do let(:request_xml) { <<-XML <?xml version="1.0" encoding="UTF-8" standalone="no"?> <epp xmlns="https://epp.tld.ee/schema/epp-ee-1.0.xsd"> <command> <update> <contact:update xmlns:contact="https://epp.tld.ee/schema/contact-ee-1.1.xsd"> <contact:id>TEST</contact:id> <contact:chg> <contact:postalInfo> <contact:name>test</contact:name> </contact:postalInfo> </contact:chg> </contact:update> </update> <extension> <eis:extdata xmlns:eis="https://epp.tld.ee/schema/eis-1.0.xsd"> <eis:ident cc="US" type="priv">test</eis:ident> </eis:extdata> </extension> </command> </epp> XML } it 'does not update code' do expect do request contact.reload end.to_not change { ident.code } end it 'updates type' do request contact.reload expect(ident.type).to eq('priv') end it 'updates country code' do request contact.reload expect(ident.country_code).to eq('US') end specify do request expect(epp_response).to have_result(:success) end end context 'when submitted ident is different from current one' do let(:request_xml) { <<-XML <?xml version="1.0" encoding="UTF-8" standalone="no"?> <epp xmlns="https://epp.tld.ee/schema/epp-ee-1.0.xsd"> <command> <update> <contact:update xmlns:contact="https://epp.tld.ee/schema/contact-ee-1.1.xsd"> <contact:id>TEST</contact:id> <contact:chg> <contact:postalInfo> <contact:name>test</contact:name> </contact:postalInfo> </contact:chg> </contact:update> </update> <extension> <eis:extdata xmlns:eis="https://epp.tld.ee/schema/eis-1.0.xsd"> <eis:ident cc="US" type="priv">another-test</eis:ident> </eis:extdata> </extension> </command> </epp> XML } it 'does not update code' do expect do request contact.reload end.to_not change { ident.code } end it 'does not update type' do expect do request contact.reload end.to_not change { ident.type } end it 'does not update country code' do expect do request contact.reload end.to_not change { ident.country_code } end specify do request expect(epp_response).to have_result(:data_management_policy_violation, t('epp.contacts.errors.ident_update')) end end end end
class Admin::Attributes::RemotesController < ApplicationController before_filter :authenticate_admin before_filter :current_admin layout 'admin' def index @remotes = PropertyAttrRemote.order('sort').all end def show @remote = PropertyAttrRemote.find(params[:id]) @current_admin = current_admin end def new end def create @remote = PropertyAttrRemote.new(params[:remote]) if @remote.save flash[:notice] = "Remote attribute created" redirect_to admin_attributes_remotes_path else flash[:alert] = "#{@remote.errors.full_messages.to_sentence}" render :new end end def edit @remote = PropertyAttrRemote.find(params[:id]) end def update @remote = PropertyAttrRemote.find(params[:id]) if @remote.update_attributes(params[:remote]) flash[:notice] = "Remote attribute updated" redirect_to admin_attributes_remotes_path else flash[:alert] = "#{@remote.errors.full_messages.to_sentence}" render :edit end end def destroy remote = PropertyAttrRemote.find(params[:id]) if remote.destroy flash[:notice] = "Remote attribute deleted" redirect_to admin_attributes_remotes_path else flash[:alert] = "#{remote.errors.full_messages.to_sentence}" redirect_to admin_attributes_remotes_path end end def currentadmin @current_admin = current_admin end def sort params[:remote].each_with_index {|val, index| obj = PropertyAttrRemote.find(val) obj.update_attribute(:sort, index) } render :text => "" end end
class PurchasedItemAddress include ActiveModel::Model attr_accessor :postal_code, :shipping_area_id, :city, :address_detail, :building, :phone_number, :user_id, :item_id, :token with_options presence: true do validates :city validates :address_detail validates :token validates :user_id validates :item_id validates :postal_code, format: { with: /\A\d{3}[-]\d{4}\z/, message: "Input correctly" } validates :shipping_area_id, numericality: { other_than: 0, message: "Select" } validates :phone_number, format: { with: /\A\d{11}\z/, message: "Input only number" } end def save purchased_item = PurchasedItem.create(user_id: user_id, item_id: item_id) Address.create(postal_code: postal_code, shipping_area_id: shipping_area_id, city: city, address_detail: address_detail, building: building, phone_number: phone_number, purchased_item_id: purchased_item.id) end end
# == Synopsis # # Classes to enable the differencing of Windows Registry files in ASCII format and output # the results in an XML-based format # # == Usage # # Example: # # require 'wired-diff' # include Wired::Diff # ... # meta = WinRegDiffMetadata.new(baseline.value, delta.value, app_name.value, nsrl.value, action.value) # ... # diff = WinRegDiff.new(fp_baseline, fp_delta) # ... # doc = WinRegDiffDoc.new(meta, diff) # doc.write(fp_output) # # == Author # # Alden Dima # # == Copyright # # This software was developed at the National Institute of Standards # and Technology by employees of the Federal Government in the course # of their official duties. Pursuant to title 17 Section 105 of the # United States Code this software is not subject to copyright # protection and is in the public domain. Reg-Diff is an experimental # system. NIST assumes no responsibility whatsoever for its use by # other parties, and makes no guarantees, expressed or implied, about # its quality, reliability, or any other characteristic. We would # appreciate acknowledgement if the software is used. This software # can be redistributed and/or modified freely provided that any # derivative works bear some notice that they are derived from it, # and any modified versions bear some notice that they have been # modified. module Wired # Classes related to the differencing of Windows Registry patch files module Diff # Reads a file and outputs its SHA 1 value def Diff.sha1_file(file) return SHA1::new(File.new(file).read).to_s end # Returns the contents of a file as a string def Diff.file_contents(file) return File.new(file).read end # Represents Registry difference metadata. Collects diffnode system metadata automatically class WinRegDiffMetadata attr_reader :baseline, :baseline_sha, :delta, :delta_sha, :app_name, :nsrl, :action, :time # Create a new WinRegDiffMetadata object. Parameters are: # [_baseline_] the ASCII-ized Windows Registry patch file that will serve as the base case # [_delta_] the ASCII-ized Windows Registry patch file that contains changes relative to the baseline # [_app_name_] the name of the application installed, deinstalled, or executed. If the delta is the result of a documented registry hack, then app_name is the name of that hack. # [_nsrl_] the NSRL application ID if the application is part of the NSRL # [_action_] the action performed to create the delta. One of _I_, _D_, _E_, or _O_ for Install, Deinstall, Execute, or Other def initialize(baseline, delta, app_name, nsrl, action) @baseline = baseline @baseline_sha = Diff.sha1_file(baseline) @delta = delta @delta_sha = Diff.sha1_file(delta) @time = Time.now.to_s @app_name = app_name @nsrl = nsrl @action = action end # Who's running this script? def user return Etc.getlogin end # Uses uname to determine diff node system architecture def arch return `uname -m`.chomp end # Uses uname to determine diff node system operating system def os return `uname -s`.chomp end # Uses uname to determine diff node system operating system version def osver return `uname -r`.chomp end # Uses uname to determine diff node system's name def sys return `uname -n`.chomp end end # Represents a single Windows Registry key class RegKey attr_reader :path def initialize(path) @path = path end end # Represents a single Windows Registry Value class RegValue attr_reader :path, :name, :data def initialize(path, name, data) @path = path @name = name @data = data end end # Represents the difference between two Windows Registry Patch # files. Sorts out the keys and values based on whether they were # added, deleted or modified (values only). class WinRegDiff attr_reader :key_add, :key_del, :val_add, :val_del, :val_mod, :bad_baseline_values, :bad_delta_values # Create a new WinRegDiff object # [_fp_b_] is the File object associated with the baseline Registry patch file # [_fp_d_] is the File object associated with the delta Registry patch file def initialize(fp_b, fp_d) keys_b, values_b, @bad_baseline_values = WinRegDiff.load_reg(fp_b) keys_d, values_d, @bad_delta_values = WinRegDiff.load_reg(fp_d) # sort out the keys based on whether they were added or deleted paths = (keys_b.keys + keys_d.keys).uniq @key_add = Array.new @key_del = Array.new paths.each do |path| key_b = keys_b[path] key_d = keys_d[path] if key_b.nil? @key_add.push(key_d) elsif key_d.nil? @key_del.push(key_b) end end # sort out values based on whether they were added, deleted, or modified paths = (values_b.keys + values_d.keys).uniq @val_add = Array.new @val_del = Array.new @val_mod = Array.new paths.each do |path| value_b = values_b[path] value_d = values_d[path] if value_b.nil? @val_add.push(value_d) elsif value_d.nil? @val_del.push(value_b) elsif value_b.data != value_d.data @val_mod.push(value_d) end end end # Load registry data from registry patch files private def WinRegDiff.load_reg(fp) reg_path = '' accum = nil reg_keys = Hash.new reg_values = Hash.new bad_values = Array.new if !fp.eof? fp.gets # dispose of header end fp.each do |line| line.strip! line.gsub!(/[[:cntrl:]]/, '?') # Gotta love control characters embedded in Registry entries if line =~ /^\[.*\]$/ reg_path = line.slice(1 .. -2) reg_keys[reg_path] = RegKey.new(reg_path) elsif line =~ /^$/ # ignore blank lines elsif line =~ /\\$/ if accum.nil? accum = line.chop.lstrip else accum << line.chop.lstrip end else value_name_data = (accum ? accum : "") << line.lstrip value_name = value_data = nil parts = value_name_data.split('=') case parts.size when 2 # the majority of registry values value_name, value_data = parts else # why do people do things like allow a field delimiter # to appear as a part of a field value? front = true if parts[0] == "@" front = false value_name = parts[0].clone parts.shift end parts.each do |part| if front if value_name.nil? value_name = part.clone else value_name << '=' << part.clone end else if value_data.nil? value_data = part.clone else value_data << '=' << part end end if front and part =~ /.*"$/ front = false end end end accum = nil if not accum.nil? # trying to thwart bad lines from RegEdit if value_name != "@" and value_name !~ /^".*"$/ bad_values << "[#{reg_path}] #{value_name}=#{value_data}" next else value_name.gsub!(/^"|"$/) {} end # The existence checks are based on a fully qualified value name. lookup_key = reg_path.clone lookup_key << "\\" << value_name value = RegValue.new(reg_path, value_name, value_data) reg_values[lookup_key] = value end end return [reg_keys, reg_values, bad_values] end end # Represents the output. All the work gets done during object # construction; you pretty much instantiate this object and then # write its contents to a file. class WinRegDiffDoc # Create a new WinRegDiffDoc object # [_metadata_] is a WinRegDiffMetadata object # [_regdiff_] is a WinRegDiff object def initialize(metadata, regdiff) @metadata = metadata @key_add = regdiff.key_add @key_del = regdiff.key_del @val_add = regdiff.val_add @val_del = regdiff.val_del @val_mod = regdiff.val_mod @doc = REXML::Document.new decl = REXML::XMLDecl.new(nil, REXML::Encoding::UTF_8, true) @doc << decl @winregdiff = REXML::Element.new('winregdiff') @doc << @winregdiff baseline delta diffnode items_added items_deleted items_modified end # Write XML document to _fp_ def write(fp) @doc.write(fp, 0, false, false) fp << "\n" end private def baseline baseline = REXML::Element.new('baseline') @winregdiff << baseline file = REXML::Element.new('file') baseline << file name = REXML::Element.new('name') name.add_text(@metadata.baseline) file << name sha = REXML::Element.new('sha') sha.add_text(@metadata.baseline_sha) file << sha end def delta delta = REXML::Element.new('delta') @winregdiff << delta file = REXML::Element.new('file') delta << file name = REXML::Element.new('name') name.add_text(@metadata.delta) file << name sha = REXML::Element.new('sha') sha.add_text(@metadata.delta_sha) file << sha app = REXML::Element.new('app') delta << app app_name = REXML::Element.new('name') app_name.add_text(@metadata.app_name) app << app_name nsrl = REXML::Element.new('nsrl') nsrl.add_text(@metadata.nsrl) app << nsrl action = REXML::Element.new('action') action.add_text(@metadata.action) app << action end def diffnode diffnode = REXML::Element.new('diffnode') @winregdiff << diffnode arch = REXML::Element.new('arch') arch.add_text(@metadata.arch) diffnode << arch sys = REXML::Element.new('sys') sys.add_text(@metadata.sys) diffnode << sys os = REXML::Element.new('os') os.add_text(@metadata.os) diffnode << os osver = REXML::Element.new('osver') osver.add_text(@metadata.osver) diffnode << osver user = REXML::Element.new('user') user.add_text(@metadata.user) diffnode << user time = REXML::Element.new('time') time.add_text(@metadata.time) diffnode << time end # helper method for items_added, items_deleted and items_modified def insert_keys(keys, subtree) keys.each do |clef| key = REXML::Element.new('key') subtree << key path = REXML::Element.new('path') path.add_text(clef.path) key << path end end # helper method for items_added, items_deleted and items_modified def insert_values(values, subtree) values.each do |val| value = REXML::Element.new('value') subtree << value path = REXML::Element.new('path') path.add_text(val.path) value << path name = REXML::Element.new('name') name.add_text(val.name) value << name data = REXML::Element.new('data') begin cdata = REXML::CData.new(val.data) rescue p(val) end data << cdata value << data end end private(:insert_keys, :insert_values) def items_added items_added = REXML::Element.new('add') @winregdiff << items_added insert_keys(@key_add, items_added) insert_values(@val_add, items_added) end def items_deleted items_deleted = REXML::Element.new('del') @winregdiff << items_deleted insert_keys(@key_del, items_deleted) insert_values(@val_del, items_deleted) end def items_modified items_modified = REXML::Element.new('mod') @winregdiff << items_modified insert_values(@val_mod, items_modified) end end end end
class GameView def initialize welcome end def welcome puts <<-STRING Welcome to Ruby Flash Cards! To play, enter the correct term for each definition. (Type 'quit' to quit.) STRING sleep(3) end def user_go gets.chomp end def display_definition(definition) puts <<-STRING Definition: STRING puts "#{definition.capitalize}" gets.chomp end def clear_screen! sleep(5) print "\e[2J" print "\e[H" end def move_to_home! print "\e[H" end def correct(user_answer, card_count) puts <<-STRING #{user_answer.capitalize} was correct! #{card_count} answered correctly. STRING end def incorrect(user_answer,correct_answer) puts <<-STRING #{user_answer.capitalize} is incorrect. The correct answer is: #{correct_answer.capitalize} STRING end def force_end_game(num_of_cards) puts <<-STRING You have completed #{num_of_cards}. See you next time! STRING end def end_game puts "Gratz! You won the game!" end end
require 'spec_helper' describe "customer_services/edit" do before(:each) do @customer_service = assign(:customer_service, stub_model(CustomerService, :partner => nil, :active_record => false )) end it "renders the edit customer_service form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form[action=?][method=?]", customer_service_path(@customer_service), "post" do assert_select "input#customer_service_partner[name=?]", "customer_service[partner]" assert_select "input#customer_service_active_record[name=?]", "customer_service[active_record]" end end end
class TopicView < ActiveRecord::Base belongs_to :user belongs_to :topic belongs_to :last_read_post, :class_name => 'Post', :foreign_key => :last_read_post_id def self.find_or_new(topic_id, user_id) topic_view = TopicView.find_by_topic_id_and_user_id topic_id, user_id topic_view ||= TopicView.new :topic_id => topic_id, :user_id => user_id end def update_last_read_post_id!(new_id) original_id = self.last_read_post_id if original_id.nil? || original_id < new_id self.last_read_post_id = new_id self.save! end original_id end end
Journal::Application.routes.draw do get "log_in" => "session#new", :as => "log_in" get "log_out" => "session#destroy", :as => "log_out" get "sign_up" => "users#new", :as => "sign_up" get 'account', to: 'accounts#show' root :to => "projects#index" resource :session, :only => [:new, :create, :destroy], :controller => 'session' resources :users do resources :accounts end resources :accounts do resources :projects end resources :projects do resources :entries end end
require 'csv' require 'cookbook' class Helper def self.write_csv(file, data) CSV.open(file, 'w') do |csv| data.each do |row| csv.puts(row) end end end end describe Cookbook do let (:recipes) do [ ['Crumpets', 'Crumpets description'], ['Beans & Bacon breakfast', 'Beans description'], ['Plum pudding', 'Pudding description'], ['Apple pie', 'Apple pie description'], ['Christmas crumble', 'Crumble description'] ] end let(:csv_path) { 'spec/recipes.csv' } before do Helper.write_csv(csv_path, recipes) @cookbook = Cookbook.new(csv_path) end describe '#initialize' do it 'creates a new cookbook and loads recipes for the CSV' do expect(@cookbook.all.length).to eq(recipes.length) end end describe '#all' do it 'gives acces to all recipes' do expect(@cookbook).to respond_to :all expect(@cookbook.all).to be_a Array end it 'should return array of Recipe instances' do first_recipe = @cookbook.all.first expect(first_recipe).to be_instance_of(Recipe) end end describe '#add_recipe' do it 'adds a recipe to the cookbook' do size_before = @cookbook.all.length @cookbook.add_recipe(Recipe.new('Risotto', 'Good stuff')) new_cookbook = Cookbook.new(csv_path) expect(new_cookbook.all.length).to eq(size_before + 1) end end describe '#remove_recipe' do it 'removes a recipe from the cookbook' do size_before = @cookbook.all.length @cookbook.remove_recipe(0) new_cookbook = Cookbook.new(csv_path) expect(new_cookbook.all.length).to eq(size_before - 1) end end end
require 'spec_helper' describe "Authentication" do subject { page } describe "signin page" do before { visit login_path } it { should have_content('Sign in') } it { should have_title('Sign in') } describe "with invalid information" do before { click_button "Sign in" } #if invalid info entered, it should reload page with error flashed it { should have_title('Sign in') } it { should have_selector('.error') } #make sure error message doesn't persist on future pages describe "when visting another page" do before { click_link "Home" } it { should_not have_selector('.error') } end end describe "with valid information" do #create user using factory let(:user) { FactoryGirl.create(:user) } #fill in for with valid info before do fill_in "Email", with: user.email.upcase fill_in "Password", with: user.password click_button "Sign in" end #if valid info entered, should goto home page, show sign out link, sign in link should be gone it { should have_title(full_title('')) } it { should_not have_link('Sign in', href: login_path) } it { should have_link('Users', href: users_path) } it { should have_link('Sign Out', href: logout_path) } it { should have_link('Settings', href: edit_user_path(user)) } it { should have_content(user.name) } describe "Followed by Sign Out" do before { click_link "Sign Out" } it { should have_link('Sign in') } end end end describe "authorisation" do describe "for non signed in users" do let(:user) { FactoryGirl.create(:user) } before { visit help_path } it { should have_title('Sign in') } describe "when attempting to visit a page" do before do visit help_path fill_in "Email", with: user.email fill_in "Password", with: user.password click_button "Sign in" end describe "after signing in" do it "should render the page you orignially tried to access" do expect(page).to have_title('Help') end end end describe "in the users controller" do #navigate to the user edit page without signing in before { visit edit_user_path(user) } #ensure it still has title sign in - ie get redirected it { should have_title('Sign in') } end describe "submitting to the update action" do #this describes somebody trying to send PATCH request malixiously before { patch user_path(user) } #specify { expect(response).to redirect_to(login_path) } end describe "visiting the user index" do #ensuring that not everyone can see the user index page before { visit users_path } it { should have_title('Sign in') } end end describe "as wrong user" do #this describes trying to edit other users info let(:user) { FactoryGirl.create(:user) } let(:wrong_user) { FactoryGirl.create(:user,name:"wrong", email: "wrong@example.com") } before { sign_in user, no_capybara: true } describe "submitting a GET request to the Users#edit action" do before { get edit_user_path(wrong_user) } specify { expect(response.body).not_to match(full_title('Edit user')) } #specify { expect(response).to redirect_to(root_url) } end describe "submitting a PATCH request to the Users#update action" do before { patch user_path(wrong_user) } #specify { expect(response).to redirect_to(root_url) } end end describe "as non-admin user" do let(:user) { FactoryGirl.create(:user) } let(:non_admin) { FactoryGirl.create(:user, name:"nonadmin", email: "nonadmin@example.com") } before { sign_in non_admin, no_capybara: true } describe "submitting a DELETE request to the Users#destroy action" do before { delete user_path(user) } #ßspecify { expect(response).to redirect_to(root_url) } end end end end
#A. A module is a way of polymorphing code that allows you to create # features that aren't necessarily restricted to one class, while # providing a way to limit class conflicts. An object cannot be made # from a module. #B. They are generally used by either including them in a class using # the include keyword, or by creating classes within the module to prevent # conflicts between existing classes. module Vehicle end class Automobile include Vehicle end end pinto = Automobile.new
require "pry" class School attr_accessor :roster def initialize(school_name) @school = school_name @roster = Hash.new {|h, k| h[k] = []} end def add_student(student_name, grade) @roster[grade] << student_name end def grade(grade) @roster[grade] end def sort @roster.each_value { |students| students.sort! } end end
# # Copyright 2016-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'rbconfig' require 'serverspec' if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/ set :backend, :cmd set :os, :family => 'windows' else set :backend, :exec end RSpec.shared_examples 'a poise_archive test' do |ext| base = "/test/#{ext}" describe file("#{base}/LICENSE") do its(:content) { is_expected.to eq "This is in the public domain.\n" } end describe file("#{base}/README") do its(:content) { is_expected.to eq "This is a project!\n\n" } end describe file("#{base}/src/main.c") do its(:content) { is_expected.to eq "int main(int argc, char **argv)\n{\n return 0;\n}\n\n" } end describe file("#{base}/bin/run.sh") do its(:content) { is_expected.to eq "#!/bin/sh\necho \"Started!\"\n" } it { is_expected.to be_mode '755' } unless os[:family] == 'windows' end describe file("#{base}_0/myapp-1.0.0/src/main.c") do its(:content) { is_expected.to eq "int main(int argc, char **argv)\n{\n return 0;\n}\n\n" } end describe file("#{base}_2/main.c") do its(:content) { is_expected.to eq "int main(int argc, char **argv)\n{\n return 0;\n}\n\n" } end describe file("#{base}_user") do it { is_expected.to be_owned_by 'poise' } it { is_expected.to be_mode '755' } unless os[:family] == 'windows' end describe file("#{base}_user/README") do it { is_expected.to be_owned_by 'poise' } it { is_expected.to be_mode '644' } unless os[:family] == 'windows' end describe file("#{base}_user/bin/run.sh") do it { is_expected.to be_owned_by 'poise' } it { is_expected.to be_mode '755' } unless os[:family] == 'windows' end describe file("#{base}_http/README") do its(:content) { is_expected.to eq "This is a project!\n\n" } end describe file("#{base}_http/src/main.c") do its(:content) { is_expected.to eq "int main(int argc, char **argv)\n{\n return 0;\n}\n\n" } end end describe 'default provider' do describe 'tar' do it_should_behave_like 'a poise_archive test', 'default/tar' end describe 'tar.gz' do it_should_behave_like 'a poise_archive test', 'default/tar.gz' end describe 'tar.bz2' do it_should_behave_like 'a poise_archive test', 'default/tar.bz2' end describe 'tar.xz' do it_should_behave_like 'a poise_archive test', 'default/tar.xz' end describe 'zip' do it_should_behave_like 'a poise_archive test', 'default/zip' end end describe 'Tar provider' do describe 'tar' do it_should_behave_like 'a poise_archive test', 'Tar/tar' end describe 'tar.gz' do it_should_behave_like 'a poise_archive test', 'Tar/tar.gz' end describe 'tar.bz2' do it_should_behave_like 'a poise_archive test', 'Tar/tar.bz2' end end describe 'GnuTar provider', if: File.exist?('/test/GnuTar') do describe 'tar' do it_should_behave_like 'a poise_archive test', 'GnuTar/tar' end describe 'tar.gz' do it_should_behave_like 'a poise_archive test', 'GnuTar/tar.gz' end describe 'tar.bz2' do it_should_behave_like 'a poise_archive test', 'GnuTar/tar.bz2' end describe 'tar.xz' do it_should_behave_like 'a poise_archive test', 'GnuTar/tar.xz' end end describe 'Zip provider' do describe 'zip' do it_should_behave_like 'a poise_archive test', 'Zip/zip' end end describe 'SevenZip provider', if: File.exist?('/test/SevenZip') do describe 'tar' do it_should_behave_like 'a poise_archive test', 'SevenZip/tar' end describe 'tar.gz' do it_should_behave_like 'a poise_archive test', 'SevenZip/tar.gz' end describe 'tar.bz2' do it_should_behave_like 'a poise_archive test', 'SevenZip/tar.bz2' end describe 'tar.xz' do it_should_behave_like 'a poise_archive test', 'SevenZip/tar.xz' end describe 'zip' do it_should_behave_like 'a poise_archive test', 'SevenZip/zip' end end describe 'core features' do describe file('/test/keep/EXISTING') do it { is_expected.to be_a_file } end describe file('/test/existing/EXISTING') do it { is_expected.to_not exist } end end
require 'spec_helper' require 'greenpeace/environment' describe Greenpeace::Environment do let(:config) { double('config') } subject { Greenpeace::Environment.new(config) } context 'when the provided config has 2 settings' do before(:each) do allow(config).to receive(:settings).and_return([ double('setting', identifier: 'foo', value: 'foovalue'), double('othersetting', identifier: 'bar', value: 'barvalue')]) end describe '#initialize' do it 'imports the first setting key' do expect(subject.values).to have_key('foo') end it 'assigns the correct value to the first key' do expect(subject.values['foo']).to eq('foovalue') end it 'imports the second setting key' do expect(subject.values).to have_key('bar') end it 'assigns the correct value to the first key' do expect(subject.values['bar']).to eq('barvalue') end end describe '#method_missing' do it 'exposes the first key as a method' do expect(subject.foo).to eq('foovalue') end it 'exposes the second key as a method' do expect(subject.bar).to eq('barvalue') end it 'fails when accessing an unknown key' do expect { subject.foobar }.to raise_error end end end end
require 'spec_helper' describe GapIntelligence::Category do include_examples 'Record' describe 'attributes' do subject(:category) { described_class.new build(:category) } it 'has name' do expect(category).to respond_to(:name) end it 'has full_name' do expect(category).to respond_to(:full_name) end it 'has frequency' do expect(category).to respond_to(:frequency) end it "has published date" do expect(category.published_date).to be_an_instance_of(Date) end it 'has publish tag only' do expect(category).to respond_to(:publish_tag_only) end it 'has publish product location only' do expect(category).to respond_to(:publish_product_location) end end end
class Player # Инициализация def initialize end # Метод выполнения шага игры def play_turn(warrior) turn = WarriorTurn.new(warrior) turn.go! end end class WarriorTurn < SimpleDelegator def go! # Пойдем к леснице, если ничего больше не остается move_to_stairs! if nothing_there? end def nothing_there? true end def move_to_stairs! self.walk!(self.direction_of_stairs) end end
module CoursesHelper def map_status Course.statuses.keys.map{|w| [w.humanize, w]} end def option_key_value subjects subjects.map do |subject| [subject.name_subject, subject.id] end end end
class AddColumnSectorIdToPartPersonDetails < ActiveRecord::Migration def change add_column :part_person_details, :sector_id, :integer end end
class Address < ActiveRecord::Base belongs_to :profile validates :postal_code, :state_id, :city_id, :street, :district, :number, presence: true belongs_to :city belongs_to :state end
module Tree class BinarySearchTree attr_accessor :root, :data def initialize(data) @data = data @root = nil process_data end def search(key, root = @root) return nil if root.nil? current_node = root while current_node != nil break if key == current_node.datum if key < current_node.datum current_node = current_node.left else current_node = current_node.right end end current_node end def search_via_recursion(key, root = @root) return nil if root.nil? return root if key == root.datum if key < root.datum search(key, root.left) else search(key, root.right) end end def insert(datum) node = Tree::Node.new(datum) previous_node = root current_node = root while current_node != nil if datum <= current_node.datum current_node = current_node.left else current_node = current_node.right end previous_node = current_node unless current_node.nil? end if datum < previous_node.datum previous_node.left = node else previous_node.right = node end end def insert_via_recursion(datum, current_node = @root) if datum <= current_node.datum if current_node.left.nil? node = Tree::Node.new(datum) current_node.left = node else insert_via_recursion(datum, current_node.left) end else if current_node.right.nil? node = Tree::Node.new(datum) current_node.right = node else insert_via_recursion(datum, current_node.right) end end end def minimum_value(root = @root) return nil if root.nil? current_node = root while current_node.left != nil current_node = current_node.left end current_node end def maximum_value(root = @root) return nil if root.nil? current_node = root while current_node.right != nil current_node = current_node.right end current_node end def predecessor(key, root = @root) node = search(key) return nil if node.nil? return maximum_value(node.left) end def successor(key, root = @root) node = search(key) return nil if node.nil? return minimum_value(node.right) end private def process_data @data.each do |datum| node = Tree::Node.new(datum) if @root.nil? @root = node next end insert(datum) end end end end
require 'spec_helper' describe Game do describe "Database Tests" do it { should have_db_column(:name).of_type(:string) } it { should have_db_column(:starting_points).of_type(:integer) } it { should have_db_column(:user_id).of_type(:integer) } end describe "Validation Tests" do let!(:game) { FactoryGirl.create(:game) } it { should have_valid(:name).when("Blah blah") } it { should_not have_valid(:name).when(nil, "") } it { should validate_uniqueness_of(:name) } it { should have_valid(:starting_points).when(9) } it { should_not have_valid(:starting_points).when(nil, "") } end describe "Association Tests" do it { should belong_to(:user) } it { should have_many(:game_traits) } it { should have_many(:characters) } end end
class AcupuncturesController < ApplicationController before_filter :signed_in_admin, only: [:destroy, :edit, :update] def index @acupunctures = Acupuncture.paginate(page: params[:page]) respond_to do |format| format.html # index.html.erb format.json { render json: @acupunctures } end end def show @acupuncture = Acupuncture.find_by_permalink(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @acupuncture } end end def new @admin = current_admin @acupuncture = Acupuncture.new respond_to do |format| format.html # new.html.erb format.json { render json: @acupuncture } end end def edit @acupuncture = Acupuncture.find_by_permalink(params[:id]) end def create @acupuncture = Acupuncture.new(params[:acupuncture]) respond_to do |format| if @acupuncture.save format.html { redirect_to @acupuncture, notice: 'Article was successfully created.' } format.json { render json: @acupuncture, status: :created, location: @acupuncture } else format.html { render action: "new" } format.json { render json: @acupuncture.errors, status: :unprocessable_entity } end end end def update @acupuncture = Acupuncture.find_by_permalink(params[:id]) respond_to do |format| if @acupuncture.update_attributes(params[:acupuncture]) format.html { redirect_to @acupuncture, notice: 'Article was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @acupuncture.errors, status: :unprocessable_entity } end end end def destroy @acupuncture = Acupuncture.find_by_permalink(params[:id]) @acupuncture.destroy respond_to do |format| format.html { redirect_to acupunctures_url } format.json { head :no_content } end end end
require "aethyr/core/actions/commands/command_action" module Aethyr module Core module Actions module Alook class AlookCommand < Aethyr::Extend::CommandAction def initialize(actor, **data) super(actor, **data) end def action event = @data room = $manager.get_object(@player.container) player = @player if event[:at].nil? object = room elsif event[:at].downcase == "here" object = $manager.find player.container else object = find_object(event[:at], event) end if object.nil? player.output "Cannot find #{event[:at]} to inspect." return end output = "Object: #{object}\n" output << "Attributes:\n" object.instance_variables.sort.each do |var| val = object.instance_variable_get(var) if var == :@observer_peers val = val.keys.map {|k| k.to_s } elsif var == :@local_registrations val = val.map { |e| e.instance_variable_get(:@listener).to_s.tr('#<>', '') } end output << "\t#{var} = #{val}\n" end output << "\r\nInventory:\r\n" if object.respond_to? :inventory object.inventory.each do |o| output << "\t#{o.name} # #{o.goid} #{object.inventory.position(o) == nil ? "" : object.inventory.position(o).map(&:to_s).join('x')}\n" end else output << "\tNo Inventory" end if object.respond_to? :equipment output << "\r\nEquipment:\r\n" object.equipment.inventory.each do |o| output << "\t#{o.name} # #{o.goid}\n" end output << "\t#{object.equipment.equipment.inspect}\n" end puts output player.output(output) end end end end end end
module Ratlas class Query def initialize(target, scope = :all, conditions = {}) @target = target @scope = scope @conditions = {:limit => "50"}.merge(conditions) @conditions.delete_if{|k,v| @target.respond_to?(:exclude) && @target.exclude.include?(k)} end def where(conditions) raise "#where expects a conditions hash" unless conditions.is_a?(Hash) add_conditions(conditions) self end def each &block execute.each &block end def to_a execute.to_a end def and(conditions) where(conditions) end def limit(limit) add_condition(:limit => limit ) end def to_params to_uri.query end def to_uri uri = Addressable::URI.new uri.host = Ratlas::ENDPOINT uri.path = Ratlas::ENDPOINT_VERSION + '/' + @target.resource_name + '.json' uri.query_values = conditions_for_query uri end def request JSON.parse(Net::HTTP.get_response(URI.parse('http:'+to_uri.to_s)).body) end def execute Ratlas::Response.new(request, @target.resource_key) end protected def conditions_for_query output = {} @conditions.each{|k,v| output[k.to_s.camelize!(false)] = v} return output end def add_condition(key, value) @conditions[key.to_sym] = value.to_s end def add_conditions(conditions) conditions.each do |key, value| add_condition(key, value) end end end end
class AddBlobToTagging < ActiveRecord::Migration[6.0] def change add_reference(:taggings, :active_storage_blob, foreign_key: true) end end
def digit_product(str_num) digits = str_num.chars.map { |n| n.to_i } product = 1 digits.each do |digit| product *= digit end product end p digit_product('12345') # OMG. product has been initialized to 0. this is fine # for addition, but not multiplication. set product to # 1 to fix this code.
require 'rails_helper' RSpec.describe 'the application show' do # [x] done # # Application Show Page # # As a visitor # When I visit an applications show page # Then I can see the following: # - Name of the Applicant # - Full Address of the Applicant including street address, city, state, and zip code # - Description of why the applicant says they'd be a good home for this pet(s) # - names of all pets that this application is for (all names of pets should be links to their show page) # - The Application's status, either "In Progress", "Pending", "Accepted", or "Rejected" it "shows the application and all it's attributes" do application_one = Application.create!(name: 'Sally Smith', address: '123 West 23rd Ave', city: 'Parker', state: 'CO', zip: '80134', description: nil, status: "In Progess" ) visit "/applications/#{application_one.id}" expect(page).to have_content(application_one.name) expect(page).to have_content(application_one.address) expect(page).to have_content(application_one.city) expect(page).to have_content(application_one.state) expect(page).to have_content(application_one.zip) expect(page).to have_content(application_one.description) expect(page).to have_content(application_one.status) end # [x] done # # Searching for Pets for an Application # # As a visitor # When I visit an application's show page # And that application has not been submitted, # Then I see a section on the page to "Add a Pet to this Application" # In that section I see an input where I can search for Pets by name # When I fill in this field with a Pet's name # And I click submit, # Then I am taken back to the application show page # And under the search bar I see any Pet whose name matches my search it "can search for a pet by name" do shelter = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) application_one = Application.create!(name: 'Sally Smith', address: '123 West 23rd Ave', city: 'Parker', state: 'CO', zip: '80134', description: nil, status: "In Progress" ) pet_1 = Pet.create(adoptable: true, age: 1, breed: 'sphynx', name: 'Jack', shelter_id: shelter.id) visit "/applications/#{application_one.id}" expect(page).to have_content("Sally Smith") expect(page).to have_field(:pet_of_interst_name) expect(page).to have_content("In Progress") fill_in( :pet_of_interst_name, with: "Jack") click_on("Find") expect(page).to have_content("Jack") end # [x] done # # Add a Pet to an Application # # As a visitor # When I visit an application's show page # And I search for a Pet by name # And I see the names Pets that match my search # Then next to each Pet's name I see a button to "Adopt this Pet" # When I click one of these buttons # Then I am taken back to the application show page # And I see the Pet I want to adopt listed on this application it "can search for a pet by name" do shelter = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) application_one = Application.create!(name: 'Sally Smith', address: '123 West 23rd Ave', city: 'Parker', state: 'CO', zip: '80134', description: nil, status: "In Progess" ) pet_1 = Pet.create(adoptable: true, age: 1, breed: 'sphynx', name: 'Jack', shelter_id: shelter.id) visit "/applications/#{application_one.id}" expect(page).to have_content("Sally Smith") expect(page).to have_field(:pet_of_interst_name) fill_in( :pet_of_interst_name, with: "Jack") click_on("Find") expect(page).to have_content("Jack") expect(page).to have_link("Adopt Jack") click_on("Adopt Jack") expect(page).to have_content("Jack") within '#pet_requests' do expect(page).to have_content("Jack") end end # [x] done # # Submit an Application # # As a visitor # When I visit an application's show page # And I have added one or more pets to the application # Then I see a section to submit my application # And in that section I see an input to enter why I would make a good owner for these pet(s) # When I fill in that input # And I click a button to submit this application # Then I am taken back to the application's show page # And I see an indicator that the application is "Pending" # And I see all the pets that I want to adopt # And I do not see a section to add more pets to this application it "can post pet for adoption" do shelter = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) application_one = Application.create!(name: 'Sally Smith', address: '123 West 23rd Ave', city: 'Parker', state: 'CO', zip: '80134', description: nil, status: "In Progress" ) pet_1 = Pet.create(adoptable: true, age: 1, breed: 'sphynx', name: 'Jack', shelter_id: shelter.id) visit "/applications/#{application_one.id}" expect(page).to have_content("In Progress") expect(page).to have_content("Sally Smith") expect(page).to have_field(:pet_of_interst_name) fill_in( "pet_of_interst_name", with: "Jack") click_on("Find") expect(page).to have_content("Jack") expect(page).to have_link("Adopt Jack") click_on("Adopt Jack") expect(page).to have_content("Jack") within '#pet_requests' do expect(page).to have_content("Jack") end expect(page).to have_field(:description) fill_in( "description", with: "I would love a new friend.") click_on("Submit Adoption Form") expect(current_path).to eq("/applications/#{application_one.id}") expect(page).to have_content("I would love a new friend.") expect(page).to have_content("Pending") expect(page).to_not have_field(:pet_of_interst_name) end # [x] done # # No Pets on an Application # # As a visitor # When I visit an application's show page # And I have not added any pets to the application # Then I do not see a section to submit my application it "will not allow you to submit a form without pets requested" do shelter = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) application_one = Application.create!(name: 'Sally Smith', address: '123 West 23rd Ave', city: 'Parker', state: 'CO', zip: '80134', description: nil, status: "In Progress" ) pet_1 = Pet.create(adoptable: true, age: 1, breed: 'sphynx', name: 'Jack', shelter_id: shelter.id) visit "/applications/#{application_one.id}" expect(page).to have_content("In Progress") expect(page).to have_content("Sally Smith") expect(page).to have_field(:pet_of_interst_name) expect(page).to_not have_field(:description) fill_in( "pet_of_interst_name", with: "Jack") click_on("Find") click_on("Adopt Jack") expect(page).to have_field(:description) end # [x] done # Partial Matches for Pet Names # # As a visitor # When I visit an application show page # And I search for Pets by name # Then I see any pet whose name PARTIALLY matches my search # For example, if I search for "fluff", my search would match pets with names "fluffy", "fluff", and "mr. fluff" it 'can find partial matches to pet name' do shelter = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) application_one = Application.create!(name: 'Sally Smith', address: '123 West 23rd Ave', city: 'Parker', state: 'CO', zip: '80134', description: nil, status: "In Progess" ) pet_1 = Pet.create(adoptable: true, age: 1, breed: 'sphynx', name: 'Jack', shelter_id: shelter.id) pet_2 = Pet.create(adoptable: true, age: 1, breed: 'sphynx', name: 'Fluffy', shelter_id: shelter.id) pet_3 = Pet.create(adoptable: true, age: 1, breed: 'sphynx', name: 'Rascal', shelter_id: shelter.id) pet_4 = Pet.create(adoptable: true, age: 1, breed: 'sphynx', name: 'Applejack', shelter_id: shelter.id) visit "/applications/#{application_one.id}" fill_in( "pet_of_interst_name", with: "Jack") click_on("Find") expect(page).to_not have_content("Fluffy") expect(page).to_not have_content("Rascal") expect(page).to have_content("Applejack") expect(page).to have_content("Jack") end # [x] done # Case Insensitive Matches for Pet Names # # As a visitor # When I visit an application show page # And I search for Pets by name # Then my search is case insensitive # For example, if I search for "fluff", my search would match pets with names "Fluffy", "FLUFF", and "Mr. FlUfF" it 'can find case insensitive matches' do shelter = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) application_one = Application.create!(name: 'Sally Smith', address: '123 West 23rd Ave', city: 'Parker', state: 'CO', zip: '80134', description: nil, status: "In Progress" ) pet_1 = Pet.create(adoptable: true, age: 1, breed: 'sphynx', name: 'Jack', shelter_id: shelter.id) pet_2 = Pet.create(adoptable: true, age: 1, breed: 'sphynx', name: 'Fluffy', shelter_id: shelter.id) pet_3 = Pet.create(adoptable: true, age: 1, breed: 'sphynx', name: 'Rascal', shelter_id: shelter.id) pet_4 = Pet.create(adoptable: true, age: 1, breed: 'sphynx', name: 'Applejack', shelter_id: shelter.id) visit "/applications/#{application_one.id}" fill_in( "pet_of_interst_name", with: "JACK") click_on("Find") expect(page).to_not have_content("Fluffy") expect(page).to_not have_content("Rascal") expect(page).to have_content("Applejack") expect(page).to have_content("Jack") end end
class Admin::OpenDaysController < Admin::AdminController before_action :set_open_day, only: [:show, :edit, :update, :destroy] respond_to :html def index @open_days = OpenDay.upcoming respond_with(@open_days) end def show respond_with(@open_day) end def new @open_day = OpenDay.new @open_day.starts_at = Date.today.end_of_day - 239.minutes # 8pm @open_day.address = 'Singel 542, 1017 AZ Amsterdam' @open_day.description_en = " <ul> <li>20:00 — Doors Open</li> <li>20:30 — Welcome and Keynote</li> <li>21:15 — Q&amp;A and drinks</li> </ul>" @open_day.description_nl = " <ul> <li>20:00 — Deuren Open</li> <li>20:30 — Welkomst en Keynote</li> <li>21:15 — Q&amp;A en borrel</li> </ul>" respond_with(@open_day) end def edit end def create @open_day = OpenDay.new(open_day_params) @open_day.save redirect_to admin_open_days_path end def update @open_day.update(open_day_params) redirect_to admin_open_days_path end def destroy @open_day.destroy respond_with(@open_day) end private def set_open_day @open_day = OpenDay.find(params[:id]) end def open_day_params params.require(:open_day).permit(:starts_at, :address, :description_en, :description_nl, :facebook_event_url) end end
class UsersController < ApplicationController before_action :authenticate_auth_user! , except: [:info] MTik::verbose=false def new @user = User.new end def create tik = MTik::Connection.new(:host => M_HOST, :user => M_USER, :pass => M_PASS, :unecrypted_plaintext => true) @user = User.new(users_params) @user.access_state = true if @user.save tik.get_reply( '/ip/firewall/address-list/add', "=address=#{@user.address}", "=list=#{@user.is_router ? "User_Router" : "users_new" }", "=comment=#{@user.name}") do |request, sentence| @trap = request.reply.find_sentence('!trap') if @trap.nil? tik.get_reply( '/queue/simple/add', "=max-limit=#{@user.is_router ? "40M/40M" : "20M/20M"}", "=name=#{@user.name}", "=target=#{@user.address}", "=queue=default/default", "=total-queue=default") do |request, sentence| @trap = request.reply.find_sentence('!trap') if @trap.nil? tik.close redirect_to action: "index" else @user.destroy render 'new' end end end end else render 'new' end end def edit @user = User.find(params[:id]) end def update user = User.find(params[:id]) old_address = user.address tik = MTik::Connection.new(:host => M_HOST, :user => M_USER, :pass => M_PASS, :unecrypted_plaintext => true) if user.update(users_params) tik.get_reply('/ip/firewall/address-list/set', "=address=#{user.address}", "=list=#{user.is_router ? "User_Router" : "users_new" }", "=comment=#{user.name}", "=.id=#{tik.get_reply('/ip/firewall/address-list/print', ".proplist=.id", "?address=#{old_address}")[0]['.id']}") do |request, sentence| @trap = request.reply.find_sentence('!trap') if @trap.nil? tik.get_reply('/queue/simple/set', "=target=#{user.address}", "=name=#{user.name}", "=max-limit=#{user.is_router ? "40M/40M" : "20M/20M"}", "=.id=#{tik.get_reply('/queue/simple/print', ".proplist=.id", "?target=#{old_address}/32")[0]['.id']}") do |request, sentence| @trap = request.reply.find_sentence('!trap') if @trap.nil? tik.close redirect_to action: "index" else render 'edit' end end else render 'edit' end end else render 'edit' end end def index if Rails.env.production? @users = User.find_by_sql("select * from users ORDER BY inet_aton(address)") else @users = User.all end end def show @user = User.find(params[:id]) end def extend tik = MTik::Connection.new(:host => M_HOST, :user => M_USER, :pass => M_PASS, :unecrypted_plaintext => true) user = User.find(params[:id]) user.date_of_disconnect = user.date_of_disconnect + 1.month if Date.today < user.date_of_disconnect user.access_state = true end user.update(update_params) tik.get_reply('/ip/firewall/address-list/set', "=disabled=#{user.access_state ? "no" : "yes" }", "=.id=#{tik.get_reply('/ip/firewall/address-list/print', ".proplist=.id", "?address=#{user.address}")[0]['.id']}") tik.close redirect_to action: "index" end def deactivate tik = MTik::Connection.new(:host => M_HOST, :user => M_USER, :pass => M_PASS, :unecrypted_plaintext => true) user = User.find(params[:id]) user.access_state = false user.update(update_params) tik.get_reply('/ip/firewall/address-list/set', "=disabled=yes", "=.id=#{tik.get_reply('/ip/firewall/address-list/print', ".proplist=.id", "?address=#{user.address}")[0]['.id']}") tik.close redirect_to action: "index" end def activate tik = MTik::Connection.new(:host => M_HOST, :user => M_USER, :pass => M_PASS, :unecrypted_plaintext => true) user = User.find(params[:id]) user.access_state = true user.update(update_params) tik.get_reply('/ip/firewall/address-list/set', "=disabled=no", "=.id=#{tik.get_reply('/ip/firewall/address-list/print', ".proplist=.id", "?address=#{user.address}")[0]['.id']}") tik.close redirect_to action: "index" end def destroy tik = MTik::Connection.new(:host => M_HOST, :user => M_USER, :pass => M_PASS, :unecrypted_plaintext => true) user = User.find(params[:id]) tik.get_reply('/ip/firewall/address-list/remove', "=.id=#{tik.get_reply('/ip/firewall/address-list/print', ".proplist=.id", "?address=#{user.address}")[0]['.id']}") tik.get_reply('/queue/simple/remove', "=.id=#{tik.get_reply('/queue/simple/print', ".proplist=.id", "?target=#{user.address}/32")[0]['.id']}") user.destroy tik.close redirect_to action: "index" end def info @ipaddress = request.env['HTTP_X_FORWARDED_FOR'] @user=User.find_by(address: @ipaddress) end private def users_params params.require(:user).permit(:name, :address, :is_router, :date_of_disconnect, :access_state) end def update_params params.permit(:name, :address, :is_router, :date_of_disconnect, :access_state, :updated_at) end end
require 'rails_helper' RSpec.describe "PollOpinions", type: :request do let!(:valid_attributes) { { type:'PollOpinion', question: "A la belle Etoile ?", expiration_date: Date.today } } let!(:invalid_attributes) { { type:'PollOpinion', question: nil, expiration_date: nil } } let!(:invalid_attributes_question_only) { { type:'PollOpinion', question: nil, expiration_date: Date.today } } let!(:admin) { create(:user, :admin, :registered) } context "/ As logged as admin," do before do request_log_in(admin) end describe "DELETE #destroy" do let!(:poll) { create(:poll_opinion) } let(:url) { "/poll_opinions/#{ poll.to_param }" } it "deletes Poll" do expect { delete url, params:{ id: poll.id, poll: poll.attributes } }.to change(Poll, :count).by(-1) end it "redirects to the polls page" do delete url, params:{ id: poll.id, poll: poll.attributes } expect(response).to redirect_to(polls_path) end end describe "POST #create" do context "with valid params" do it "creates a new Poll" do expect { post '/poll_opinions', params: { poll_opinion: valid_attributes } }.to change(Poll, :count).by(1) end it "assigns a newly created poll as @pol" do post '/poll_opinions', params: { poll_opinion: valid_attributes } expect(PollOpinion.last.question).to eq(valid_attributes[:question]) end it "redirects to the created poll" do post '/poll_opinions', params: { poll_opinion: valid_attributes } t = PollOpinion.find_by(question: valid_attributes[:question]) expect(response).to redirect_to polls_path end end context "with invalid params" do it "re-renders the 'new' template" do post '/poll_opinions', params: { poll_opinion: invalid_attributes_question_only } expect(response).to render_template :new end it "doesn't persist poll" do expect { post '/poll_opinions', params: { poll_opinion: invalid_attributes_question_only } }.to change(Poll, :count).by(0) end end end end describe "PUT #update" do context "with valid params" do before :each do request_log_in(admin) end let(:new_attributes_poll_question) { { question: "Sous les ponts ?", expiration_date:Date.today.weeks_since(2)} } let(:new_attributes) { { question: "Sous les toits ?", expiration_date:Date.today.weeks_since(2)} } let!(:poll) { create(:poll_opinion) } it "updates the requested poll_question with a new poll_question" do url = "/poll_opinions/#{ poll.to_param }" put url, params:{ id: poll.id, poll_opinion:new_attributes_poll_question } poll.reload expect(poll).to have_attributes( question: new_attributes_poll_question[:question] ) end it "updates the requested poll" do url = "/poll_opinions/#{ poll.to_param }" put url, params:{ id: poll.id, poll_opinion: new_attributes } poll.reload expect(poll).to have_attributes( question: new_attributes[:question] ) expect(poll).to have_attributes( expiration_date: new_attributes[:expiration_date]) end it "redirects to the users page" do url = "/poll_opinions/#{ poll.to_param }" put url, params:{ id: poll.id, poll_opinion: new_attributes } expect(response).to redirect_to polls_path end end context "with invalid params" do before :each do admin = create(:user, :admin, :registered) request_log_in(admin) end let(:poll) { create(:poll_opinion) } it "assigns the poll as @poll" do url = "/poll_opinions/#{ poll.to_param }" put url, params:{ id: poll.id, poll_opinion: invalid_attributes } poll.reload expect(poll.question).not_to eq(invalid_attributes[:question]) end it "re-renders the 'edit' template" do url = "/poll_opinions/#{ poll.to_param }" put url, params:{ id: poll.id, poll_opinion: invalid_attributes } expect(response).to render_template :edit end end end end
class EventsController < ApplicationController def show @event = current_user.events.find(params[:id]) @photos = @event.photos end end
require 'rails_helper' describe "The main page." do before do @user = FactoryGirl.create(:user) visit login_path fill_in('email', with: 'MyString') fill_in('password', with: 'MyString') click_button('Log In') visit home_path end it "User can see main page" do expect(page).to have_content "Первый в мире удобный менеджер флеш-карточек. Именно так." end it "User will see 'correct' if answer is ok." do card = FactoryGirl.create(:card, user_id: @user.id) visit home_path fill_in "answer", with: card.original_text click_button "Check!" expect(page).to have_content "Correct" end it "User will see 'incorrect' if answer isn't' ok." do card = FactoryGirl.create(:card, user_id: @user.id) visit home_path fill_in "answer", with: 'Sieg Heil!' click_button "Check!" expect(page).to have_content "Incorrect" end end
require('pg') require_relative('../db/sql_runner.rb') require_relative('./stock.rb') require_relative('./customer.rb') require('pry') class Rental attr_accessor :id, :rental_reference, :rental_items, :rental_price, :rental_date, :customer_id, :stock_id def initialize(options) @id = options['id'].to_i if options['id'] @rental_reference = options['rental_reference'] @rental_items = options['rental_items'] @rental_price = options['rental_price'] @rental_date = options['rental_date'] @customer_id = options['customer_id'] @stock_id = options['stock_id'] end def save_rental() sql = "INSERT into rentals (rental_reference, rental_items, rental_price, rental_date, customer_id, stock_id) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id" values = [@rental_reference, @rental_items, @rental_price, @rental_date, @customer_id, @stock_id] rental = SqlRunner.run(sql, values).first @id = rental['id'].to_i end def delete_rental() sql = "DELETE FROM rentals WHERE id = $1" values = [@id] SqlRunner.run(sql, values) end def self.all_rentals() sql = "SELECT * FROM rentals" rentals = SqlRunner.run(sql) result = rentals.map { |rental| Rental.new(rental) } end def self.delete_all() sql = "DELETE FROM rentals" SqlRunner.run(sql) end def self.find( id ) sql = "SELECT * FROM rentals WHERE id = $1" values = [id] rental = SqlRunner.run( sql, values ) result = Rental.new( rental.first ) return result end def update_rental() sql = "UPDATE rentals SET (rental_reference, rental_items, rental_price, rental_date, customer_id, stock_id) = ($1, $2, $3, $4, $5, $6) WHERE id =$6" values = [@rental_reference, @rental_items, @rental_price, @rental_date, @customer_id, @stock_id, @id] SqlRunner.run(sql, values) end ## Here I want this function to return the details of the customer from this rental. def customer sql = "SELECT * FROM customers WHERE id = $1" values = [@customer_id] results = SqlRunner.run(sql, values) return results.map { |customer| Customer.new(customer) } end ## This method should return the details of what stock is being rented. def stock sql = "SELECT * FROM stocklist WHERE id = $1" values = [@stock_id] results = SqlRunner.run(sql, values) return results.map { |stock| Stock.new(stock)} end ## This function should randomly generate a number between 1-500000 and ## interpolate it with the string REN so it can be used as a serial number generator. def reference_gen() num = rand 500000 return "REN#{num}" end # binding.pry # nil end
#!/usr/bin/env ruby ## # author: Jakub Zak # e-mail: jakub.zak@me.com # module: KRAKER::Core::DataCollector # detail: Collects data from the object returned by Kraken::API.upload. ## module KRAKER module Core class DataCollector private attr_accessor :log, :cfg public attr_accessor :result, :files_data def initialize log, cfg self.log = log self.cfg = cfg self.result = Hash.new self.files_data = Array.new end def run prepare_storage log.info 'collecting data' summarise_data end def add_to_data data self.files_data << data end private def summarise_data self.files_data.each do | data | result[:all] += data.saved_bytes.to_i result[:files][:"#{data.file_name}"] = data.saved_bytes.to_i end end def prepare_storage result[:all] = 0 result[:files] = {} end end end end
class Admin::NewsletterSignupsController < Admin::ControllerBase def index @newsletter_signups = NewsletterSignup.order(created_at: :desc).decorate @count = @newsletter_signups.count end end
module Topaz # The main tempo clock class Clock include API attr_reader :event, :midi_output, :source, :trigger # @param [Fixnum, UniMIDI::Input] tempo_or_input # @param [Hash] options # @option options [Boolean] :midi_transport Whether to respect start/stop MIDI commands from a MIDI input # @param [Proc] tick_event def initialize(tempo_or_input, options = {}, &tick_event) # The MIDI clock output is initialized regardless of whether there are devices # so that it is ready if any are added during the running process. @midi_output = MIDIClockOutput.new(:devices => options[:midi]) @event = Event.new @trigger = EventTrigger.new @source = TempoSource.new(tempo_or_input, options.merge({ :event => @event })) initialize_events(&tick_event) end # Set the tempo # # If external MIDI tempo is being used, this will switch to internal tempo at the desired rate. # # @param [Fixnum] value # @return [ExternalMIDITempo, InternalTempo] def tempo=(value) if @source.respond_to?(:tempo=) @source.tempo = value else @source = TempoSource.new(event, tempo_or_input) end end # This will start the clock source # # In the case that external midi tempo is being used, this will instead start the process # of waiting for a start or clock message # # @param [Hash] options # @option options [Boolean] :background Whether to run the timer in a background thread (default: false) # @return [Boolean] def start(options = {}) @start_time = Time.now begin @source.start(options) rescue SystemExit, Interrupt => exception stop raise exception end true end # This will stop the clock source # @param [Hash] options # @return [Boolean] def stop(options = {}) @source.stop(options) @start_time = nil true end # Seconds since start was called # @return [Float] def time (Time.now - @start_time).to_f unless @start_time.nil? end private # Initialize the tick and MIDI clock events so that they can be passed to the source # and fired when needed # @param [Proc] block # @return [Clock::Event] def initialize_events(&block) @event.tick << block if block_given? clock = proc do if @trigger.stop? stop else @midi_output.do_clock end end @event.clock = clock @event.start << proc { @midi_output.do_start } @event.stop << proc { @midi_output.do_stop } @event end # Trigger clock events class EventTrigger def initialize @stop = [] end # Pass in a callback which will stop the clock if it evaluates to true # @param [Proc] callback # @return [Array<Proc>] def stop(&callback) if block_given? @stop.clear @stop << callback end @stop end # Should the stop event be triggered? # @return [Boolean] def stop? !@stop.nil? && @stop.any?(&:call) end end # Clock events class Event attr_accessor :clock def initialize @start = [] @stop = [] @tick = [] end # @return [Array] def do_clock !@clock.nil? && @clock.call end # Pass in a callback that is called when start is called # @param [Proc] callback # @return [Array<Proc>] def start(&callback) if block_given? @start.clear @start << callback end @start end # @return [Array] def do_start @start.map(&:call) end # pass in a callback that is called when stop is called # @param [Proc] callback # @return [Array<Proc>] def stop(&callback) if block_given? @stop.clear @stop << callback end @stop end # @return [Array] def do_stop @stop.map(&:call) end # Pass in a callback which will be fired on each tick # @param [Proc] callback # @return [Array<Proc>] def tick(&callback) if block_given? @tick.clear @tick << callback end @tick end # @return [Array] def do_tick @tick.map(&:call) end end end Tempo = Clock # For backwards compat end
# frozen_string_literal: true class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable validates :email, :type, :password, presence: true enum status: {'student': 'Student','teacher': 'Teacher'} #different types of users end
class QuestionsController < ApplicationController before_filter :require_session include Session def show @course = Course.find_by(course_cd: params[:course_cd]) @question = @course.questions.find(params[:id]) end def answer question = Question.find(params[:id]) checked_answer = question.check_answer(params[:answer_field], params[:option_field]) if checked_answer[:result] set_completed_to_session(question) render_json('ok', '正解です', accurate_rate, progress_rate(question.course), question.answer, checked_answer[:each_sentences]) else render_json('ng', '不正解です', accurate_rate, progress_rate(question.course), question.answer, checked_answer[:each_sentences]) end rescue => e logger.debug(e.message) render_json('ng', '不正解です', accurate_rate, progress_rate(question.course), question.answer, nil, 500) end def see_answer question = Question.find(params[:id]) set_mistaked_to_session(question) render_json('ok', '解答例', accurate_rate, progress_rate(question.course), question.answer) end private def render_json(result, messages, accurate_rate, progress, answer, each_sentences=nil, status=200) render json: { result: result, messages: messages, accurate_rate: accurate_rate, progress: progress, answer: answer, each_sentences: each_sentences }, status: status end def require_session unless session_exists? reset_session redirect_to root_path end end end
# Welcome back! Let’s write a program that asks us to type in as many words as we want # (one word per line, continuing until we just press Enter on an empty line) and then # repeats the words back to us in # alphabetical order. OK? array = [] loop do puts "start typing, will stop when you press enter and type nothing" input = gets.chomp array << input break if input.empty? end puts array.sort # book solution # puts 'Give me some words, and I will sort them:' # words = [] # while true # word = gets.chomp # if word == '' # break # end # words.push word # end # puts 'Sweet! Here they are, sorted:' # puts words.sort
class AddCitroenvieToUser < ActiveRecord::Migration def change add_column :users, :citroenvie, :boolean add_index :users, :citroenvie end end
# encoding: utf-8 require "carrierwave" require 'carrierwave/processing/mini_magick' class BaseUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick # 性能压缩提升30% MiniMagick.processor = :gm # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir # "/home/mzoneapp/api_v1/public/#{model.class.to_s.underscore}" "uploads/#{model.class.to_s.underscore}" end # Provide a default URL as a default if there hasn't been a file uploaded: def default_url # "photo/#{version_name}.jpg" end # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: def extension_white_list %w(jpg jpeg gif png) end # http://kb.cnblogs.com/page/82967/ # 使用gm 的用法 -thumbnail '100x100^' # gm convert input.jpg -thumbnail '100x100^' -gravity center -extent 100x100 output_3.jpg def my_resize_to_fill(width, height, gravity = 'Center') manipulate! do |img| cols, rows = img[:dimensions] img.combine_options do |cmd| if width != cols || height != rows scale_x = width/cols.to_f scale_y = height/rows.to_f if scale_x >= scale_y cols = (scale_x * (cols + 0.5)).round rows = (scale_x * (rows + 0.5)).round cmd.resize "#{cols}" else cols = (scale_y * (cols + 0.5)).round rows = (scale_y * (rows + 0.5)).round cmd.resize "x#{rows}" end end cmd.gravity gravity # 多余的部分用白色代替 cmd.background "rgba(255,255,255,0.0)" # 关键就是 thumbnail 后面 ^ 就能达到我们的需求 !!!!! cmd.thumbnail "#{width}x#{height}^" if cols != width || rows != height cmd.extent "#{width}x#{height}" if cols != width || rows != height end img = yield(img) if block_given? img end end #品质设置 plane def plane_pic manipulate! do |img| #img.quality(percentage.to_s) #img = yield(img) if block_given? img.strip img.combine_options do |c| # Use Progressive DCT Instead of Baseline DCT. c.interlace 'plane' end img end end end
require 'features_helper' feature 'Show calculation results for Showerheads', :js, :real_measure do include Features::CommonSupport let!(:user) { create(:user) } let!(:dhw) do create(:structure_type, name: 'Domestic Hot Water System', api_name: 'domestic_hot_water_system', genus_api_name: 'domestic_hot_water_system') end let!(:showerhead) do create(:structure_type, name: 'Showerhead', api_name: 'showerhead', genus_api_name: 'water') end let!(:measure1) do Measure.find_by!(api_name: 'showerheads') end before do set_up_audit_report_for_measures( [measure1], user: user, substructures: [ { name: 'Showerhead', structure_type: showerhead }, { name: 'DHW', structure_type: dhw } ] ) end scenario 'Verify measure' do add_new_structures( 'DHW - White House' => dhw.api_name, 'Showerhead - White House' => showerhead.api_name ) fill_out_structure_cards( '1 - Domestic Hot Water System', existing: { afue: 0.7, dhw_cold_water_temperature: 80, dhw_hot_water_temperature: 130 }, proposed: { dhw_cold_water_temperature: 80, dhw_hot_water_temperature: 130 } ) fill_out_structure_cards( '2 - Showerhead', existing: { gpm: 2.5 }, proposed: { gpm: 1.5, per_unit_cost: 360 } ) fill_out_measure_level_fields( retrofit_lifetime: '20' ) click_link 'Edit report data' fill_out_audit_level_fields( gas_cost_per_therm: 1, water_cost_per_gallon: 0.00844, num_apartments: 10, num_bedrooms: 10 ) click_link 'Edit measures' expect_measure_summary_values( annual_water_savings: '43,840', annual_gas_savings: '128.0', annual_cost_savings: '$498.40', cost_of_measure: '$360.00', years_to_payback: '0.722', savings_investment_ratio: '27.7' ) end end
class AddSenderToAnnouncement < ActiveRecord::Migration[5.1] def change add_column :announcements, :sender, :string end end
#!/usr/bin/env ruby # execute in background: pipe-command-server & require 'open3' def execute_cmd cmd Open3.popen2e(cmd) do |stdin, stdout_err, wait_thr| while line = stdout_err.gets puts line STDOUT.flush end # exit_status = wait_thr.value end end pipe = File.expand_path('~/pipes/command-server') unless File.exists? pipe require 'mkfifo' require 'fileutils' FileUtils.mkdir_p(File.dirname(pipe)) File.mkfifo(pipe) end input = open(pipe, 'r+') # the r+ means we don't block while line = input.gets.rstrip # will block if there's nothing in the pipe execute_cmd(line) end
class AddContactIdToTestScores < ActiveRecord::Migration def change add_column :test_scores, :contact_id, :integer end end
class Module def defensive_copy *method_names method_names.each { |name| define_method(name) { var = instance_variable_get("@#{name}") Array.new(var.class == Array ? var : var.values) } } end end
step ':name should receive :count private message(s)' do |name, count| FakeYammer.messages_endpoint_hits.should == count.to_i end step ':name should receive a private reminder message' do |name| FakeYammer.message.should include("Reminder") end step 'the private reminder message sent should be from :name' do |name| sender = User.find_by_name!(name) FakeYammer.access_token.should == sender.access_token end
class GroupUser < ApplicationRecord belongs_to :group belongs_to :user scope :belongs_to_group_id, -> (group_id) { where(group_id: group_id)} scope :your_id, -> (user_id) { where.not(user_id: user_id) } end
class AboutusController < ApplicationController def index render 'layouts/aboutus.html.erb' end end
class CreateOperations < ActiveRecord::Migration def change create_table :operations do |t| t.string :acronimo t.string :nombre t.integer :montomax t.integer :montomin t.string :tipo t.boolean :natural t.boolean :juridico t.timestamps null: false end end end
module HashSyntax module Transformer MATCH_18 = ObjectRegex.new('symbeg (ident | kw) sp? hashrocket') MATCH_19 = ObjectRegex.new('label') extend self def transform(input_text, options) tokens = extract_tokens(input_text) if options[:"to-18"] transform_to_18(input_text, tokens, options) elsif options[:"to-19"] transform_to_19(input_text, tokens, options) else raise ArgumentError.new('Either :to_18 or :to_19 must be specified.') end end private def extract_tokens(text) swizzle_parser_flags do Ripper.lex(text).map { |token| Token.new(token) } end end def swizzle_parser_flags old_w = $-w old_v = $-v old_d = $-d $-w = $-v = $-d = false yield ensure $-w = old_w $-v = old_v $-d = old_d end def transform_to_18(input_text, tokens, options) lines = input_text.lines.to_a # eagerly expand lines matches = MATCH_19.all_matches(tokens) line_adjustments = Hash.new(0) matches.each do |label_list| label = label_list.first lines[label.line - 1][label.col + line_adjustments[label.line],label.width] = ":#{label.body[0..-2]} =>" line_adjustments[label.line] += 3 # " =>" is inserted and is 3 chars end lines.join end def transform_to_19(input_text, tokens, options) lines = input_text.lines.to_a # eagerly expand lines matches = MATCH_18.all_matches(tokens) line_adjustments = Hash.new(0) matches.each do |match_tokens| symbeg, ident, *spacing_and_comments, rocket = match_tokens lines[symbeg.line - 1][symbeg.col + line_adjustments[symbeg.line],1] = '' lines[ident.line - 1].insert(ident.col + line_adjustments[ident.line] + ident.width - 1, ':') lines[rocket.line - 1][rocket.col + line_adjustments[rocket.line],2] = '' if spacing_and_comments.last != nil && spacing_and_comments.last.type == :on_sp lines[rocket.line - 1][rocket.col + line_adjustments[rocket.line] - 1,1] = '' line_adjustments[rocket.line] -= 3 # chomped " =>" else line_adjustments[rocket.line] -= 2 # only chomped the "=>" end end lines.join end end end
# encoding: utf-8 class ApplicationExcel require 'spreadsheet' attr_reader :book, :sheet def initialize Spreadsheet.client_encoding = 'cp932' @book = Spreadsheet::Workbook.new end def create_worksheet(title) @sheet = @book.create_worksheet @sheet.name = Kconv.tosjis(title) end def write(alls, opt={}) alls.each_with_index do |row, i| row.attributes.each_with_index do |col, j| col[1] = col[1].strftime("%Y/%m/%d %H:%M:%S") if col[1].class.to_s == "Time" cell( 1, j, (col[0] rescue nil), :top => :medium, :right => :thin, :bottom => :medium, :left => :thin) if i == 0 cell(i + 2, j, (col[1] rescue nil), :top => :thin, :right => :thin, :bottom => :thin, :left => :thin) end end end def cell(row, col, val, opt={}) @sheet[row, col] = Kconv.tosjis(Kconv.tosjis(val)) rescue @sheet[row, col] = val.to_i unless val.blank? rule(row, col, opt) end def rule(row, col, opt={}) @sheet[row, col] = @sheet[row, col] before = @sheet.row(row).format(col) format = Spreadsheet::Format.new # format.font = Spreadsheet::Font.new(Kconv.tosjis("MS Pゴシック"), :size => 11, :encoding => :shift_jis) format.font = Spreadsheet::Font.new(Kconv.tosjis("MS ゴシック"), :size => 10, :encoding => :shift_jis) format.font.size = opt[:size] unless opt[:size].blank? format.font.bold = opt[:bold] unless opt[:bold].blank? format.font.italic = opt[:italic].blank? ? before.font.italic : opt[:italic] format.number_format = opt[:number_format]? '#,###,###,###,###' : before.number_format format.top = opt[:top ].blank? ? before.top : opt[:top] format.bottom = opt[:bottom].blank? ? before.bottom : opt[:bottom] format.left = opt[:left ].blank? ? before.left : opt[:left] format.right = opt[:right ].blank? ? before.right : opt[:right] format.horizontal_align = opt[:align].blank? ? before.horizontal_align : opt[:align] @sheet.row(row).set_format(col, format) @sheet.row(row).height = opt[:height] unless opt[:height].blank? @sheet.column(col).width = opt[:width ] unless opt[:width].blank? end def data require 'stringio' data = StringIO.new '' @book.write data return data.string.bytes.to_a.pack("C*") end end
class AddPlanIdToAgents < ActiveRecord::Migration[6.0] def change add_column :agents, :plan_id, :string end end
Rails.application.routes.draw do devise_for :admins, path: 'admins' devise_for :users, path: 'users' root to: 'pages#home' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :draws, only: [:new, :create, :edit, :update, :destroy] end
# require 'dotenv-rails' require 'rest_client' require 'json' require 'byebug' require 'unirest' require 'mechanize' # This function takes user input and puts it in an array to be passed into our get_aud_string_of_lyrics_from_multiple_artists function. To search with multiple artists the input needs to be seperated by a "," def user_input(user_input_as_string) output_array = user_input_as_string.split(",") output_array.each do |artist| artist.strip! end end #This function takes an array of strings as an argument def lyrics_by_artist(artist_array) lyrics = "" if artist_array.any? && artist_array.length <= 1 artist_array.each do |artist| response = RestClient::Request.execute( method: :get, url: "https://itunes.apple.com/search?term=#{artist}", ) parsed_response = JSON.parse(response) # if parsed_response["status"] == "success" parsed_response["results"].each do |result| # name of song track = result["trackName"] # scrape the first result of a google search mechanize = Mechanize.new page = mechanize.get('http://google.com/') puts page.title lyrics += parsed_track_response["results"]["lyrics"] end end if lyrics.length != 0 lyrics else lyrics = "No lyrics found for artists: #{artist_array.join(", ")} " end else p 'Please enter 1 to 3 artists seperated by a ","' end end p lyrics_by_artist(user_input("cage the elephant")) # response = RestClient::Request.execute( # method: :get, # url: "https://api.audd.io/findLyrics/?api_token=#{ENV["AUD_TOKEN"]}&q=#{artist}", # ) # response = Unirest.get "https://audd.p.rapidapi.com/findLyrics/?q=#{artist}", # headers:{ # "X-RapidAPI-Key" => "cc18bab80cmshf7200a4db77b274p177d1cjsncd3ac6352036", # "Content-Type" => "application/x-www-form-urlencoded" # }, # parameters:{ # "parameter" => "#{artist}" # } do |response| # response.code # Status code # response.headers # Response headers # response.body # Parsed body # response.raw_body # Unparsed body # byebug # end
class Account < ActiveRecord::Base belongs_to :charity, foreign_key: :charity_id end
class DatesManipulator def date_list_from_multiple_ranges_string(date_string) ranges = date_string.split(/&/) dates = ranges.map { |range| date_list_from_string_range(range)} ranges.flatten end private def date_list_from_string_range(date_range) regex = /20[01][0-9]-[0-9]{2}-[0-9]{2}/ result = date_range.scan(regex) start_date = Date.parse(result[0]) return start_date if result.size == 1 end_date = Date.parse(result[1]) date = start_date date_tab = [] while date <= end_date do date_tab.insert(-1, date) date = date + 1.day end date_tab end end
# frozen_string_literal: true require 'rails/generators/active_record' module BeyondCanvas module Generators class ViewsGenerator < Rails::Generators::Base # :nodoc: desc 'Creates all Beyond Canvas views to overwrite them' source_root File.expand_path('../../../../app/views/beyond_canvas', __dir__) def copy_views directory 'authentications', 'app/views/beyond_canvas/authentications' end end end end
class EncountersCreateMoves < ActiveRecord::Migration def change create_table :moves do |t| t.string :code t.string :name t.string :description t.string :using t.string :on t.text :effects t.text :variations t.text :library_requirements t.string :success_message t.string :failure_message t.text :effects end end end
class CreateEleSimulations < ActiveRecord::Migration[5.2] def change create_table :ele_simulations do |t| t.float :actual_price_paid t.float :ele_cost_saved t.integer :ele_use t.belongs_to :full_simulation, index: true t.timestamps end end end
require 'spec_helper' describe 'Battle' do let(:hero) { Hero.new strength: 5, health: 10, actions: { attack: AttackAction.new, flee: FleeAction.new } } let(:monster) { Monster.new toughness: 2, notice: 1, damage: 4, exp: 10, gold: 20 } let(:dicepool) { Dicepool.new } describe 'Hero attacks monster' do context 'when the attack is succesful' do before :each do Dicepool.any_instance.stub(:roll_die).and_return(5) hero.activate_action :attack, monster end it 'kills monster' do expect(monster).to be_dead end it 'gets monster\'s gold' do expect(hero.gold).to eq 20 end it 'gets experience' do expect(hero.exp).to eq 10 end end context 'when the attack fails' do before :each do Dicepool.any_instance.stub(:roll_die).and_return(2) hero.activate_action :attack, monster end it 'takes damage' do expect(hero.health).to eq 6 end end end describe 'Hero fless from monster' do context 'when the flee attempt is succesful' do before do Dicepool.any_instance.stub(:roll_die).and_return(5) hero.activate_action :flee, monster end it 'fled' do expect(hero.fled?).to be_true end end context 'when the flee attempt fails' do before do Dicepool.any_instance.stub(:roll_die).and_return(2) hero.activate_action :flee, monster end it 'taked damage' do expect(hero.health).to eq 6 end end end end
# # Be sure to run `pod spec lint IotaKit.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| s.swift_version = '4.0' s.name = "IotaKit" s.version = "0.5.5" s.summary = "The IOTA Swift API Library" # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC The IOTA Swift API Library. IotaKit is compatible with all architectures, tested on iOS/MacOS/Ubuntu. DESC s.homepage = "https://github.com/pascalbros/IotaKit" s.license = "MIT (Copyright (c) 2018 Pasquale Ambrosini)" s.source = { :git => "https://github.com/pascalbros/IotaKit.git", :tag => "v#{s.version}" } s.author = { "Pasquale Ambrosini" => "pasquale.ambrosini@gmail.com" } s.ios.deployment_target = "11.0" s.osx.deployment_target = "10.10" s.requires_arc = true s.source_files = 'Sources/IotaKit/**/*.{swift,c,h}' s.pod_target_xcconfig = {'SWIFT_INCLUDE_PATHS' => '$(SRCROOT)/IotaKit/Sources/IotaKit/include/sha3','LIBRARY_SEARCH_PATHS' => '$(SRCROOT)/IotaKit/Sources/IotaKit', 'SWIFT_VERSION' => '4.0'} s.exclude_files = 'Sources/IotaKit/Utils/Crypto.swift' s.preserve_paths = 'Sources/IotaKit/include/sha3/module.modulemap' end
class RecipientsController < ApplicationController def index end def new user = User.find(session[:user_id]) @recipient = user.recipients.new # @user.recipients << @recipient end def create @user = User.find(session[:user_id]) @recipient = Recipient.create(recipient_params) @user.recipients << @recipient redirect_to @user end def recipient_params params.require(:recipient).permit(:name, :email) end end
# frozen_string_literal: true module Eq module Companies # Eq::Companies::CompanyEntity class CompanyEntity < EntityBase attribute :id, Types::Integer.optional attribute :name, Types::Strict::String attribute :logo, Types::Strict::String attribute :created_at, Types::Time.optional attribute :updated_at, Types::Time.optional end end end
#!/usr/bin/env ruby # encoding: utf-8 import os import nysol.mcmd as nm import nysol.util.mtemp as mtemp #=分類階層(taxonomy)クラス # 一階層の分類階層(アイテム-分類)を扱うクラス。 # #===利用例 # 以下taxo.csvの内容 # --- # item,taxo # a,X1 # b,X1 # c,X2 # d,X2 # # 以下rubyスクリプト # --- # require 'rubygems' # require 'mining' # taxo=Taxonomy("taxo.csv","item","taxo") # puts taxo.itemFN # => "item" # puts taxo.taxoFN # => "taxo" # puts taxo.itemSize # => 4 (アイテムは"a,b,c,d"の4種類) # puts taxo.taxoSize # => 2 (分類は"X1,X2"の2種類) # puts taxo.file # => ./1252379737_1756/dat/1 # #=====./1252379737_1756/dat/1 の内容 # item,taxo # a,X1 # b,X1 # c,X2 # d,X2 class Taxonomy(object): #=== taxonomyクラスの初期化 # 一階層の分類階層を扱う。 # アイテム項目とその分類名項目を持つファイルから分類階層オブジェクトを生成する。 #====引数 # iFile: taxonomyファイル名 # itemFN: アイテム項目名 # taxoFN: 分類項目名 #====機能 #* アイテム(itemFN)と分類(taxoFN)の2項目からなるファイルが規定のパス(Taxonomy.file)に書き出される。 #* 同じアイテムが重複して登録されていれば単一化して書き出される。 #* アイテム順にソートされる。 #* アイテム数と分類数を計算する。 def __init__(self,iFile,itemFN,taxoFN): # アイテムの項目名(=>String) self.itemFN = None # 分類の項目名(=>String) self.taxoFN = None # アイテムの種類数(=>Fixnum) self.itemSize = None # 分類の種類数(=>Fixnum) self.taxoSize = None # taxonomyデータファイル名(=>String) self.file = None self.temp = mtemp.Mtemp() self.iFile = iFile self.iPath = os.path.abspath(self.iFile) self.itemFN = itemFN self.taxoFN = taxoFN # item順に並べ替えてpathに書き出す self.file = self.temp.file() para_it = self.itemFN +"," + self.taxoFN nm.mcut(f=para_it,i=self.iFile).muniq(k=para_it,o=self.file).run(msg="on") f = nm.mcut(f=self.itemFN,i=self.iFile) f <<= nm.mtrafld(f=self.itemFN,a="__fld",valOnly=True) f <<= nm.mtra(f="__fld",r=True) f <<= nm.muniq(k="__fld") f <<= nm.mcount(a="size") f <<= nm.mcut(f="size") xx1 = f.run() self.itemSize = int(xx1[0][0]) xx2 = nm.mcut(f=self.taxoFN+":item",i=self.file).muniq(k="item").mcount(a="size").mcut(f="size").run() self.taxoSize = int(xx2[0][0])
#This game takes a random number between 0-100 and asks the user to try and guess it. #The user has 5 guesses to get it right. The program will tell the user if thier guess #is too high or too low. class Game def initialize @turns = [] # => [] @rand_number = rand(100) # Generate the reandom number end #Take the input, check it against the guess array and prevent duplicate inputs #It also passes the input on to an array to track the number of guesses def input puts "Guess a number between 0-100 please. >" @guess = gets.chomp.to_i while @turns.include?(@guess) puts "Didn't we try that one already? Hmmmm Pick again. >" @guess = gets.chomp.to_i end @turns << @guess end #Checks the guess to see if it is too high or too low compaired to the random number #also checks if it is the correct number. def check if @rand_number > @guess puts "your guess is too low" elsif @rand_number < @guess puts "your guess is too high" elsif @rand_number == @guess puts "Congratulations you guessed it. That was really fucking hard!" end end #this actually runs the program through. def begin while @turns.length < 5 do input check end puts "You wern't even close. Nice try it was #{@rand_number}" end end game = Game.new # => #<Game:0x007fd04c0b8438 @turns=[], @rand_number=21> game.begin
class AddTotalOpponentCounts < ActiveRecord::Migration[5.2] def change add_column :league_matches, :total_home_team_round_wins, :integer, null: false, default: 0 add_column :league_matches, :total_away_team_round_wins, :integer, null: false, default: 0 add_column :league_matches, :total_round_draws, :integer, null: false, default: 0 add_column :league_rosters, :bye_matches_count, :integer, null: false, default: 0 add_column :league_rosters, :normalized_round_score, :decimal, null: false, default: 0 add_column :league_rosters, :buchholz_score, :decimal, null: false, default: 0 add_column :league_rosters, :median_buchholz_score, :decimal, null: false, default: 0 reversible do |dir| dir.up do League::Match.includes(:rounds).find_each { |match| match.reset_cache! } League.find_each { |league| league.trigger_scores_update! } end end end end
# Unix 中有一个叫 grep 的命令。grep 命令利用正则表达式搜索文本数据,输出按照指定模式匹配到的行。我们试试用 Ruby 实现 grep 命令 pattern = Regexp.new(ARGV[0]) # 1 filename = ARGV[1] # 2 # 3 file = File.open(filename) # 4 file.each_line do |line| # 5 if pattern =~ line # 6 print line # 7 end # 8 end # 9 file.close # 10 # 在命令行输入以下命令,以执行代码: # ruby simple_grep.rb 模式 文件名 # 分析一下: # Ruby 执行该脚本时,需要有两个命令行参数——ARGV[0] 和 ARGV[1] # 第 1 行,程序根据第 1 个参数创建了正则表达式对象,并赋值给变量 pattern。Regexp.new(str) 表示把字符串 str 转换为正则表达式对象。 # 第 2 行,把第 2 个参数赋值给作为文件名的变量 filename。 # 第 4 行,打开文件,创建文件对象,并将其赋值给变量 file。 # 第 5 行,读取一行数据,并将其赋值给变量 line。 # 第 6 行,使用 if 语句,判断变量 line 的字符串是否匹配变量 pattern 的正则表达式。 # 如果匹配,则在程序第 7 行输出该字符串 # 这个 if 语句没有 else 部分,因此,若不匹配,程序什么都不会做。只会执行下一次的循环(下一行) # 第10 行,当全部文本读取完毕后,关闭文件,结束程序。
# frozen_string_literal: true require 'tty-progressbar' # ** PROGRESS BAR ANIMATION bar = TTY::ProgressBar.new('calculating [:bar]', total: 30) 30.times do sleep(0.1) bar.advance(1) end
# frozen_string_literal: true require_relative '../entities/handoff_to_legacy_request' require_relative '../entities/handoff_to_legacy_request_room' require_relative '../helpers/id_generator' require_relative '../log' require 'pg' module MyServiceName module Repository class HandoffToLegacyRequestRepository include Log TABLE_NAME = 'handoff_to_legacy_requests' ROOMS_TABLE_NAME = 'handoff_to_legacy_request_rooms' private_constant :TABLE_NAME, :ROOMS_TABLE_NAME attr_reader :connection private :connection def initialize db_url = ENV['POSTGRES_DB_URL'] raise ConfigurationError if db_url.nil? @connection = PG::Connection.open(db_url) end # Default insert def insert(interaction_id:, rooms:) generated_id = Helper::IdGenerator.call logger.info "HandoffToLegacyRequest Repository: insert id='#{generated_id}' " \ "interaction_id='#{interaction_id}' rooms='#{rooms}'" connection.transaction do |transaction| insert_query( id: generated_id, interaction_id: interaction_id, transaction: transaction, ) insert_rooms(rooms: rooms, handoff_to_legacy_request_id: generated_id, transaction: transaction) end generated_id end # insert "that tries to recconect and run" def insert_with_retries(interaction_id:, rooms:, retries: 5, sleep_seconds: 1) generated_id = Helper::IdGenerator.call logger.info "HandoffToLegacyRequest Repository: insert id='#{generated_id}' " \ "interaction_id='#{interaction_id}' rooms='#{rooms}'" last_error = nil (1..retries).each do |_| begin connection.transaction do |transaction| insert_query( id: generated_id, interaction_id: interaction_id, transaction: transaction, ) insert_rooms(rooms: rooms, handoff_to_legacy_request_id: generated_id, transaction: transaction) end return generated_id rescue PG::UnableToSend, PG::ConnectionBad, PG::AdminShutdown => e last_error = e logger.info 'Failed to persist. --> Retrying' sleep sleep_seconds if !connected? reconnect end end end raise last_error end # insert and spawn reconnect thread if error def insert_and_spawn_reconnect_thread(interaction_id:, rooms:, sleep_seconds: 1) generated_id = Helper::IdGenerator.call logger.info "HandoffToLegacyRequest Repository: insert id='#{generated_id}' " \ "interaction_id='#{interaction_id}' rooms='#{rooms}'" begin connection.transaction do |transaction| insert_query( id: generated_id, interaction_id: interaction_id, transaction: transaction, ) insert_rooms(rooms: rooms, handoff_to_legacy_request_id: generated_id, transaction: transaction) end rescue PG::UnableToSend, PG::ConnectionBad, PG::AdminShutdown => e async_reconnect sleep_seconds raise end end # Connection Management def connected? @connection.status == PG::CONNECTION_OK end def reconnect @connection.reset end private def async_reconnect(sleep_seconds) thread = Thread.new do loop do logger.info 'Trying to reconnect!' reconnect break if connected? sleep sleep_seconds end logger.info 'Reconnected!! \o/' end logger.info "Reconnecting to DB. Launched Thread." end def insert_rooms(rooms:, handoff_to_legacy_request_id:, transaction:) rooms.each do |pas_room_id| generated_id = Helper::IdGenerator.call logger.info "HandoffToLegacyRequest Repository: insert room id='#{generated_id}' " \ "handoff_to_legacy_request_id='#{handoff_to_legacy_request_id}' pas_room_id='#{pas_room_id}' " insert_room_query( id: generated_id, handoff_to_legacy_request_id: handoff_to_legacy_request_id, pas_room_id: pas_room_id, transaction: transaction, ) end end def insert_query(id:, interaction_id:, transaction:) transaction.exec_params( "INSERT INTO #{TABLE_NAME} VALUES ($1, $2)", [id, interaction_id], ) end def insert_room_query(id:, handoff_to_legacy_request_id:, pas_room_id:, transaction:) transaction.exec_params( "INSERT INTO #{ROOMS_TABLE_NAME} VALUES ($1, $2, $3)", [id, handoff_to_legacy_request_id, pas_room_id], ) end end end end
class AddDownloadedAtToSurveys < ActiveRecord::Migration def change add_column :surveys, :downloaded_at, :datetime end end
class CreateDepartmentInformations < ActiveRecord::Migration def change create_table :department_informations do |t| t.text :name t.references :parent_department, index: true t.text :description t.integer :layer t.references :manager, index: true t.references :vice_manager, index: true t.text :duty t.timestamps null: false end add_foreign_key :department_informations, :parent_departments add_foreign_key :department_informations, :managers add_foreign_key :department_informations, :vice_managers end end
# Clase para describir a una persona con datos básicos. # # @author Jorge González Cabrera # # @!attribute [rw] nombre # @return [String] el nombre del individuo # @!attribute [rw] apellidos # @return [String] los apellidos del individuo # @!attribute [rw] sexo # @return [true,false] el sexo del individuo(true = hombre, false = mujer) # @!attribute [rw] edad # @return [Fixnum] edad del individuo class Individuo attr_accessor :nombre, :apellidos, :sexo, :edad # Crea un objeto individuo recibiendo los datos para todos los atributos de la clase. # # @return [Individuo] def initialize(nombre, apellidos, edad, sexo) @nombre = nombre @apellidos = apellidos @edad = edad @sexo = sexo end # Formatea los datos del individuo en una línea. # # @return [String] los datos del individuo. def to_s if @sexo "\n #{@nombre} #{@apellidos}, hombre, #{@edad} años" else "\n #{@nombre} #{@apellidos}, mujer, #{@edad} años" end end end