text
stringlengths
10
2.61M
class FontTradeWinds < Formula head "https://github.com/google/fonts/raw/main/ofl/tradewinds/TradeWinds-Regular.ttf", verified: "github.com/google/fonts/" desc "Trade Winds" homepage "https://fonts.google.com/specimen/Trade+Winds" def install (share/"fonts").install "TradeWinds-Regular.ttf" end test do end end
class Customer < User belongs_to :manager has_one :profile, class_name: CustomerProfile accepts_nested_attributes_for :profile, update_only: true attr_accessible :profile, :profile_attributes extend Enumerize delegate :company_name, :dba, :first_name, :company_address, to: :profile, allow_nil: true has_many :offices accepts_nested_attributes_for :offices, allow_destroy: true, reject_if: :all_blank attr_accessible :offices_attributes has_many :contact_persons accepts_nested_attributes_for :contact_persons attr_accessible :contact_persons_attributes has_many :mailing_addresses accepts_nested_attributes_for :mailing_addresses attr_accessible :mailing_addresses_attributes has_many :policies def json_fields [:id, :email, :confirmed_at, :confirmed, :profile, :offices] end def self.collection_json(relation) fields = [:id, :email, :confirmed_at, :profile, :offices, :policies] relation.map do |record| JsonHelper.resource_to_json(record, false, fields) end end end
# Account Balance, Debugging, Ruby Basics, Exercises # Financially, you started the year with a clean slate. balance = 0 # Here's what you earned and spent during the first three months. january = { income: [ 1200, 75 ], expenses: [ 650, 140, 33.2, 100, 26.9, 78 ] } february = { income: [ 1200 ], expenses: [ 650, 140, 320, 46.7, 122.5 ] } march = { income: [ 1200, 10, 75 ], expenses: [ 650, 140, 350, 12, 59.9, 2.5 ] } # Let's see how much you've got now... def calculate_balance(month) plus = month[:income].sum minus = month[:expenses].sum plus - minus end [january, february, march].each do |month| balance += calculate_balance(month) # This is the problem line end puts balance # The issue is that we're currently just returning the balance from March, # since the variable is reassigned three times with the each, instead of # it incrementing. instead of `balance =`, we change to `balance +=`
apt_package 'fontconfig' directory '/usr/share/fonts' do owner 'root' group 'root' mode '0755' action :create end execute "download font" do command 'wget https://s3.amazonaws.com/oliver-dev/fonts/zawgyi.ttf' user "root" cwd '/usr/share/fonts/' not_if { ::File.exists?('/usr/share/fonts/zawgyi.ttf') } end execute "refresh font cache" do command 'fc-cache -f -v' user "root" end
class AddColumnsToProjectStatusMaster < ActiveRecord::Migration def change add_column :project_status_masters, :active, :integer add_column :project_status_masters, :user_id, :integer end end
class Speaker < ActiveRecord::Base SPEAKER_GENDERS = [:male, :female] LEARNING_METHODS = [:acad, :nat] enum gender: SPEAKER_GENDERS enum learning_method: LEARNING_METHODS belongs_to :city belongs_to :state belongs_to :country belongs_to :native_language belongs_to :english_country_residence validates :gender, inclusion: {in: SPEAKER_GENDERS.map { |sg| sg.to_s }} validates :learning_method, inclusion: {in: LEARNING_METHODS.map { |l| l.to_s }} validates :other_languages, :numericality => { :greater_than_or_equal_to => 0 } validates :age, :numericality => { :greater_than_or_equal_to => 0 } validates :english_onset, :numericality => { :greater_than_or_equal_to => 0 } validates :length_english_residence, :numericality => { :greater_than_or_equal_to => 0 } belongs_to :user validates_presence_of :name, :city, :country, :native_language, :other_languages, :age, :gender, :english_onset, :learning_method, :length_english_residence has_many :phonemes, dependent: :destroy # City getter def city_name city.try(:name) end # City setter def city_name=(name) self.city = City.find_or_create_by(name: name) if name.present? end # State getter def state_name state.try(:name) end # State setter def state_name=(name) self.state = State.find_or_create_by(name: name) if name.present? end # Country getter def country_name country.try(:name) end # Country setter def country_name=(name) self.country = Country.find_or_create_by(name: name) if name.present? end # Native Language getter def native_language_name native_language.try(:name) end # Native Language setter def native_language_name=(name) self.native_language = NativeLanguage.find_or_create_by(name: name) if name.present? end # English Country Residence getter def english_country_residence_name english_country_residence.try(:name) end # English Country Residence setter def english_country_residence_name=(name) self.english_country_residence = EnglishCountryResidence.find_or_create_by(name: name) if name.present? end end
class CreateReports < ActiveRecord::Migration[5.0] def change create_table :reports do |t| t.integer :generate_by t.datetime :begin_dt t.datetime :end_dt t.boolean :unit t.boolean :state t.boolean :kind t.boolean :onu t.boolean :blend t.boolean :code t.boolean :total t.belongs_to :collection, index: true, foreign_key: true t.timestamps end end end
class Subforum < ActiveRecord::Base belongs_to :forum has_many :posts, :dependent => :destroy delegate :forumname, :to => :forum, :prefix => false def most_recent_post Post.where('subforum_id = ?', self.id).last end def self.find_by_name(forumname) Subforum.where('forumname = ?', forumname) end validates :subforumname, presence: true validates :forum_id, presence: true end
require 'omf_base/lobject' require 'rack' require 'omf-web/session_store' require 'omf-web/widget' require 'omf-web/theme' OMF::Web::Theme.require 'widget_page' module OMF::Web::Rack class WidgetMapper < OMF::Base::LObject def initialize(opts = {}) @opts = opts @tabs = {} end def call(env) req = ::Rack::Request.new(env) sessionID = req.params['sid'] if sessionID.nil? || sessionID.empty? sessionID = "s#{(rand * 10000000).to_i}" end Thread.current["sessionID"] = sessionID body, headers = render_page(req) if headers.kind_of? String headers = {"Content-Type" => headers, "Access-Control-Allow-Origin" => "*"} end [200, headers, [body]] end def render_page(req) opts = @opts.dup opts[:prefix] = req.script_name opts[:request] = req opts[:path] = req.path_info p = req.path_info p = '/' if p.empty? widget_name = p.split('/')[1] unless widget_name return render_widget_list(opts) end widget_name = opts[:widget_name] = widget_name.to_sym begin widget = OMF::Web::Widget.create_widget(widget_name) page = OMF::Web::Theme::WidgetPage.new(widget, opts) return [page.to_html, 'text/html'] rescue Exception => ex warn "Request for unknown widget '#{widget_name}':(#{ex})" opts[:flash] = {:alert => %{Unknonw widget '#{widget_name}'.}} [OMF::Web::Theme::WidgetPage.new(nil, opts).to_html, 'text/html'] end end def render_widget_list(popts) wlist = OMF::Web::Widget.registered_widgets [wlist.to_json, 'application/json'] end end # WidgetMapper end # OMF::Web::Rack
# frozen_string_literal: true require 'rails_helper' RSpec.describe Message, type: :model do let(:user) { create(:user) } let(:room) { create(:room) } let(:message) { create(:message, user: user, room: room) } it 'message ใ‚’ไฝœๆˆใงใใ‚‹' do expect(message).to be_valid end it 'room ใŒใชใ„ใจไฝœๆˆใงใใชใ„' do message.room = nil message.valid? expect(message.errors.full_messages[0]).to eq 'Room must exist' end it 'user ใŒใชใ„ใจไฝœๆˆใงใใชใ„' do message.user = nil message.valid? expect(message.errors.full_messages[0]).to eq 'User must exist' end end
# # @author Kristian Mandrup # # Single role base storage (common, reusable functionality) # module Trole::Storage class BaseOne < Troles::Common::Storage # constructor # @param [Symbol] the role subject def initialize role_subject super end # get Role instance by name # @param [Symbol] list of role names to find Roles for # @return [Role] reference to Role instances def find_role role raise ArgumentError, "Must be a role label" if !role.kind_of_label? role_model.where(:name => role.to_s) end # get embedded Role instances # @param [Array<Symbol>] list of role names # @return [Array<Role>] Role instances generated def role_to_embed raise "Must be implemented by embed storage to generate a set of roles to embed" end def role_model role_subject.class.troles_config.role_model end # saves the role for the user in the data store def set_roles *roles raise ArgumentError, "A single role strategy can only allow setting a single role, was: #{roles}" if (roles.size > 1) set_role roles.flat_uniq.first end # sets the role to its default state def set_default_role! clear! end end end
require 'rails_helper' class Mutations::CreateUserTest < ActiveSupport::TestCase describe 'GraphQL User mutations' do def perform_superuser(venue: nil, **args) Mutations::CreateVenue.new(object: nil, context: {current_user:{role: 3}}).resolve(args) end def perform_other_user(venue: nil, **args) Mutations::CreateVenue.new(object: nil, context: {current_user:{role: 2}}).resolve(args) end it 'create a new venue' do venue = perform_superuser( name: 'Venue One', street1: '123 main', city: 'Denver', state: 'CO', zip: '80128' ) assert venue.persisted? assert_equal venue.name, 'Venue One' assert_equal venue.addresses[0].city, 'denver' end it 'throws error when current user is not superuser' do venue = perform_other_user( name: 'Venue One', street1: '123 main', city: 'Denver', state: 'CO', zip: '80128' ) assert_equal venue.class, GraphQL::ExecutionError end end end
class QuasiStatsController < ApplicationController before_action :set_quasi_stat, only: [:show, :edit, :update, :destroy] # GET /quasi_stats # GET /quasi_stats.json def index @quasi_stats = QuasiStat.all end # GET /quasi_stats/1 # GET /quasi_stats/1.json def show end # GET /quasi_stats/new def new @quasi_stat = QuasiStat.new end # GET /quasi_stats/1/edit def edit end # POST /quasi_stats # POST /quasi_stats.json def create @quasi_stat = QuasiStat.new(quasi_stat_params) respond_to do |format| if @quasi_stat.save format.html { redirect_to @quasi_stat, notice: 'Quasi stat was successfully created.' } format.json { render :show, status: :created, location: @quasi_stat } else format.html { render :new } format.json { render json: @quasi_stat.errors, status: :unprocessable_entity } end end end # PATCH/PUT /quasi_stats/1 # PATCH/PUT /quasi_stats/1.json def update respond_to do |format| if @quasi_stat.update(quasi_stat_params) format.html { redirect_to @quasi_stat, notice: 'Quasi stat was successfully updated.' } format.json { render :show, status: :ok, location: @quasi_stat } else format.html { render :edit } format.json { render json: @quasi_stat.errors, status: :unprocessable_entity } end end end # DELETE /quasi_stats/1 # DELETE /quasi_stats/1.json def destroy @quasi_stat.destroy respond_to do |format| format.html { redirect_to quasi_stats_url, notice: 'Quasi stat was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_quasi_stat @quasi_stat = QuasiStat.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def quasi_stat_params params.require(:quasi_stat).permit(:atk_range, :cast_time, :weight_limit, :energy) end end
# frozen_string_literal: true module Complicode module Generators class Base64Data BASE64 = %w[ 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z + / ].freeze # @param ascii_sums [Struct] # @param partial_keys [Array<String>] # @return [String] def self.call(ascii_sums, partial_keys) ascii_sums.partials.each_with_index.inject(0) do |sum, (partial_sum, index)| sum + ascii_sums.total * partial_sum / partial_keys[index].size end.b(10).to_s(BASE64) end end end end
Truestack::Application.routes.draw do resources :subscriptions match "/director" => "director#index" constraints(:subdomain => 'director') do match "/" => "director#index" end devise_for :users, path_names: { sign_in: 'login', sign_out: 'logout' } get "about" => "static#about" get "mongo" => "static#mongo" get "home" => "static#home" authenticated :user do root to: 'user_applications#index' end get 'bootstrap/base-css' => 'static#base_css' get 'bootstrap/scaffolding' => 'static#scaffolding' get 'bootstrap/components' => 'static#components' get "signups/thanks" => "signups#thanks" post "signups" => "signups#create" get "signups" => "signups#new" get "profile" => "user_profile#show", :as => :profile post "profile" => "user_profile#update" post "profile/reset_token" => "user_profile#reset_token", :as => "profile_reset_api_token" resources :user_applications, :path => "apps" , :as => "apps" do post :reset_token post :purge_data end resource "admin", :only => [:show] do resources :collector_workers end get "admin/access_report" => "admins#access_report", :as => :admin_access_report get "admin/client_types" => "admins#client_types", :as => :admin_client_types mount RailsAdmin::Engine => '/rails_admin', :as => 'rails_admin' # Mount the services from the services directory. Dir[Rails.root.join("app","services","*_service.rb")].each do |file| name = File.basename(file).split('.',2).first.downcase if (name != "application_service") constant= "::Services::#{name.camelize}".constantize Rails.logger.info "Mounting #{constant} to #{constant.rack_base("apl")}" mount constant => constant.rack_base("api") end end root to: 'signups#new' end
class Ember::VisualisationsController < ApplicationController before_action :authenticate skip_before_filter :verify_authenticity_token include CrudActionsMixin self.responder = ApplicationResponder respond_to :json def namespace 'Ember::' end def show @item = Visualisation.find(params[:id]) respond_with(@item, serializer: serializer, root: "visualisation") end def create visualisation = Visualisation.new(params.permit(:data, :room, :begin, :end, :image_url, :guest_count, :arrangement_type)) @current_user.visualisations << visualisation visualisation.save render json:{id: visualisation.id} end def get_notes visualisation = Visualisation.find params[:id] @items = visualisation.notes respond_with(@items, root: 'notes', each_serializer: "Ember::NoteSerializer".constantize) end def index # if @current_user.is_super_user? # @items = Visualisation.all # elsif @current_user.is_franshise_admin? # @items = Visualisation.where(franchise_id: @current_user.franchise_id) # else # @items = Visualisation.where(user_id: @current_user.id) # end @items = Visualisation.all respond_with(paginate(@items), root: 'visualisation', each_serializer: serializer) end def get_last_visualisation @item = @current_user.visualisations.max_by{|e|e.updated_at} respond_with(@item, serializer: 'Ember::VisualisationSerializer'.constantize, root: 'visualisation') end def destroy Visualisation.where(id: params[:id]).destroy end def update visualisation = Visualisation.find(params[:id]) visualisation.update(params[:visualisation].permit(:begin, :data, :end, :room, :image_url)) visualisation.save end def add_note note = Note.new(params.permit(:body, :creation_date)) visualisation = Visualisation.find params[:id] note.save @current_user.notes << note visualisation.notes << note render json:{id: note.id, author_name: @current_user.name} end protected def authenticate authenticate_or_request_with_http_token do |token, options| begin @current_user = User.find_by(authentication_token: token) rescue Mongoid::Errors::DocumentNotFound render status: 401 end end end end
class Goal < ApplicationRecord enum kind: [:general, :penalty, :autogoal] belongs_to :player belongs_to :match belongs_to :team end
class AddColumnNumRhymesToTweet < ActiveRecord::Migration def change add_column :tweets, :num_rhymes, :integer add_index :tweets, :num_rhymes add_index :tweets, :num_syllables end end
class CreateTasksTable < ActiveRecord::Migration def change create_table :tasks do |t| t.string :name t.string :exc_path t.datetime :start_datetime t.datetime :end_datetime t.text :exc_days # serialized by rails to array t.string :server_key # add timestamps t.timestamps end end end
require 'yajl' require 'sinatra/base' require 'sinatra/respond_with' require 'sinatra/redis' require 'readers/filesystem' require 'readers/redis' require 'helpers/input_parser' require 'helpers/graph' module StatsdServer class Dash < Sinatra::Base configure do set :haml, :format => :html5 helpers StatsdServer::InputParser helpers StatsdServer::GraphHelpers register Sinatra::RespondWith register Sinatra::Redis end helpers do def render_error(msg) status 400 respond_with error: msg end def create_stats_reader(index) if index.zero? StatsdServer::Readers::Redis.new(redis) else StatsdServer::Readers::FileSystem.new(settings.data_path) end end def retention_levels @retention_levels ||= settings.retention.split(",").map! { |s| s.split(":").map!(&:to_i) } end def determine_retention_level_and_index(range) diff = (range[1] - range[0]) / 60 levels = retention_levels levels.each_with_index do |pair, index| return [pair.first, index] if diff <= pair.last || index == levels.size - 1 end end end get "/" do haml :root end %w[ counters timers gauges ].each do |datatype| # this route renders the template (with codes for the graph) get "/#{datatype}", :provides => :html do haml :view end # actual data API route get "/#{datatype}", :provides => :json do metrics = parse_metrics range = parse_time_range return render_error('invalid metrics') if metrics.empty? return render_error('invalid time range') if range.nil? level, index = determine_retention_level_and_index(range) reader = create_stats_reader(index) read_opts = { level: level, range: range.dup } results = { range: range, level: level * 1000, metrics: [] } range.map! { |n| n * 1000 } # convert to milisec metrics.each do |metric| data = reader.fetch(metric, datatype, read_opts) data = zero_fill!(data, range, level) unless data.empty? || params[:no_zero_fill] results[:metrics] << { label: metric, data: data } end respond_with results end end end end
class Article < ApplicationRecord belongs_to :period, inverse_of: :articles has_many :comments, dependent: :destroy validates :title, presence: true, length: { minimum: 5 } validates :text, presence: true, length: {minimum: 10 } end
require 'logger' require 'optparse' module Bowler class CLI def self.start(args) options = { without: [] } OptionParser.new {|opts| opts.banner = "Usage: bowl [options] <process>..." opts.on('-w', '--without <process>', 'Exclude a process from being launched') do |process| options[:without] << process.to_sym end opts.on_tail('-o', '--output-only', 'Output the apps to be started') do options[:output_only] = true end opts.on_tail("-h", "--help", "Show this message") do puts opts exit end opts.on_tail('-v', '--version', 'Show the gem version') do puts "Bowler #{Bowler::VERSION}" exit end }.parse!(args) processes = args.map(&:to_sym) tree = Bowler::DependencyTree.load to_launch = tree.dependencies_for(processes) - options[:without] if options[:output_only] puts to_launch.join("\n") else logger.info "Starting #{to_launch.join(', ')}..." start_foreman_with( launch_string(to_launch) ) end rescue PinfileNotFound logger.error "Bowler could not find a Pinfile in the current directory." rescue PinfileError => e logger.error "Bowler could not load the Pinfile due to an error: #{e}" end def self.logger @@logger ||= Logger.new(STDOUT) end def self.logger=(logger) @@logger = logger end def self.build_command(launch_string) "#{self.foreman_exec} start -c #{launch_string}" end private def self.launch_string(processes) processes.map {|process| "#{process}=1" }.sort.join(',') end def self.start_foreman_with(launch_string) exec ( self.build_command launch_string ) end def self.foreman_exec ENV["BOWLER_FOREMAN_EXEC"] || "foreman" end end end
class Medication < ActiveRecord::Base self.table_name = 'medication_orders' validates_presence_of :admission, :order_frequency, :name, :dosage, :necessity belongs_to :order_frequency belongs_to :admission enum route: {'PO' => 0, 'IM' => 1, 'SC' => 2} enum unit: {mg: 0} end
class TallyLedger < ActiveRecord::Base has_many :finance_transaction_categories belongs_to :tally_company belongs_to :tally_voucher_type belongs_to :tally_account delegate :company_name, :to => :tally_company delegate :voucher_name, :to => :tally_voucher_type delegate :account_name, :to => :tally_account validates_presence_of :ledger_name, :tally_company_id, :tally_voucher_type_id, :tally_account_id end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "translation_center/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "translation_center" s.version = TranslationCenter::VERSION s.authors = ["BadrIT", "Mahmoud Khaled", "Khaled Abdelhady"] s.email = ["mahmoud.khaled@badrit.com"] s.homepage = "http://github.com/BadrIT/translation_center" s.summary = "Multi lingual web Translation Center community for Rails 3 apps" s.description = "Translation Center is a multi lingual web engine for Rails 3 apps. It builds a translation center community with translators and admins from your system users." s.license = 'MIT' s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", ">= 3.1.0", "<= 3.2.12" s.add_dependency "jquery-rails" s.add_dependency 'haml' s.add_dependency 'haml-rails' s.add_dependency 'acts_as_votable' s.add_dependency 'ya2yaml' s.add_dependency 'font-awesome-rails' s.add_dependency 'audited-activerecord' s.add_dependency 'jquery-ui-rails' end
class Assign < ActiveRecord::Base default_scope { where(is_delete: 0) } end
require 'belafonte/errors' module Belafonte class Argument module ARGVProcessor class Processor attr_reader :occurrences, :arguments def initialize(occurrences, arguments) @occurrences, @arguments = occurrences, arguments end def processed validate_arguments arguments.first(occurrences) end private def validate_arguments raise Errors::TooFewArguments.new("Not enough arguments were given") unless valid_arguments_length? end def valid_arguments_length? arguments.length >= occurrences end end end end end
# Copyright (c) 2015 Lamont Granquist # Copyright (c) 2015 Chef Software, Inc. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. module FFI_Yajl class ParseError < StandardError; end class Parser attr_writer :stack, :key_stack attr_accessor :key, :finished attr_accessor :opts # # stack used to build up our complex object # def stack @stack ||= [] end # # stack to keep track of keys as we create nested hashes # def key_stack @key_stack ||= [] end def self.parse(obj, *args) new(*args).parse(obj) end def initialize(opts = {}) @opts = opts ? opts.dup : {} # JSON gem uses 'symbolize_names' and ruby-yajl supports this as well @opts[:symbolize_keys] = true if @opts[:symbolize_names] end def parse(str) raise FFI_Yajl::ParseError, "input must be a string or IO" unless str.is_a?(String) || str.respond_to?(:read) # initialization that we can do in pure ruby yajl_opts = {} if @opts[:check_utf8] == false && @opts[:dont_validate_strings] == false raise ArgumentError, "options check_utf8 and dont_validate_strings are both false which conflict" end if @opts[:check_utf8] == true && @opts[:dont_validate_strings] == true raise ArgumentError, "options check_utf8 and dont_validate_strings are both true which conflict" end yajl_opts[:yajl_allow_comments] = true if @opts.key?(:allow_comments) yajl_opts[:yajl_allow_comments] = @opts[:allow_comments] end yajl_opts[:yajl_dont_validate_strings] = (@opts[:check_utf8] == false || @opts[:dont_validate_strings]) yajl_opts[:yajl_allow_trailing_garbage] = @opts[:allow_trailing_garbage] yajl_opts[:yajl_allow_multiple_values] = @opts[:allow_multiple_values] yajl_opts[:yajl_allow_partial_values] = @opts[:allow_partial_values] yajl_opts[:unique_key_checking] = @opts[:unique_key_checking] # XXX: bug-compat with ruby-yajl return nil if str == "" str = str.read if str.respond_to?(:read) # call either the ext or ffi hook do_yajl_parse(str, yajl_opts) end end end
#!/usr/bin/env ruby # OpsWorks provisioner for Vagrant # -------------------------------- # Copyright (c) 2016 PixelCog Inc. # Licensed under MIT (see LICENSE) require 'date' require 'json' require 'tmpdir' require 'fileutils' module OpsWorks class OpsWorksError < StandardError; end DNA_BASE = { "ssh_users" => { "1000" => { "name" => "vagrant", "public_key" => nil, "sudoer" => true } }, "dependencies" => { "gem_binary" => "/usr/local/bin/gem", "gems" => {}, "debs" => {} }, "ec2" => { "instance_type" => "vm.vagrant" }, "opsworks_initial_setup" => { "swapfile_instancetypes" => ["vm.vagrant"] }, "ebs" => { "devices" => {}, "raids" => {} }, "opsworks" => { "activity" => "setup", "valid_client_activities" => ["setup"], "agent_version" => 0, "ruby_version" => "2.0.0", "ruby_stack" => "ruby", "rails_stack" => { "name" => nil }, "stack" => { "name" => "Vagrant Stack", "elb-load-balancers" => [], "rds_instances" => [] }, "layers" => {}, "instance" => { "infrastructure_class" => "ec2", "ip" => "127.0.0.1", "private_ip" => "127.0.0.1", "layers" => [] } }, "deploy" => {}, "opsworks_rubygems" => { "version" => "2.2.2" }, "opsworks_bundler" => { "version" => "1.5.3", "manage_package" => nil }, "opsworks_custom_cookbooks" => { "enabled" => false, "scm" => { "type" => "git", "repository" => nil, "user" => nil, "password" => nil, "revision" => nil, "ssh_key" => nil }, "manage_berkshelf" => nil, "recipes" => [] }, "chef_environment" => "_default", "recipes" => [ "opsworks_custom_cookbooks::load", "opsworks_custom_cookbooks::execute" ] } DNA_DEPLOY_BASE = { "deploy_to" => nil, "application" => nil, "deploying_user" => nil, "domains" => [], "application_type" => nil, "mounted_at" => nil, "rails_env" => nil, "ssl_support" => false, "ssl_certificate" => nil, "ssl_certificate_key" => nil, "ssl_certificate_ca" => nil, "document_root" => nil, "restart_command" => "echo 'restarting app'", "sleep_before_restart" => 0, "symlink_before_migrate" => {}, "symlinks" => {}, "database" => {}, "migrate" => false, "auto_bundle_on_deploy" => true, "scm" => { "scm_type" => "git", "repository" => nil, "revision" => nil, "ssh_key" => nil, "user" => nil, "password" => nil } } def self.provision(*args) if agent_revision < Date.today.prev_month(4) warn "Warning: OpsWorks agent version #{agent_version} is over four months old, consider updating..." end log "Checking dependencies..." check_dependencies log "Reading input..." dna = compile_json expand_paths(args) log "Parsing deployments..." dna['deploy'].each do |name, app| # if repo points to a local path, trick opsworks into receiving it as a git repo if app['scm']['repository'] && app['scm']['repository'] !~ /^(?:[A-Za-z0-9]+@|http(|s)\:\/\/)/i if !Dir.exist?(app['scm']['repository']) raise OpsWorksError, "Local app '#{name}' could not be found at '#{app['scm']['repository']}'" end app['scm']['repository'] = prepare_deployment(app['scm']['repository']) end end log "Parsing custom cookbooks..." if dna['opsworks_custom_cookbooks']['enabled'] cookbooks = dna['opsworks_custom_cookbooks'] # if repo points to a local path, trick opsworks into receiving it as a git repo if cookbooks['scm']['repository'] && cookbooks['scm']['repository'] !~ /^(?:[A-Za-z0-9]+@|http(|s)\:\/\/)/i if !Dir.exist?(cookbooks['scm']['repository']) raise OpsWorksError, "Local custom cookbooks could not be found at '#{cookbooks['scm']['repository']}'" end cookbooks['scm']['repository'] = prepare_deployment(cookbooks['scm']['repository']) # autodetect berkshelf support if cookbooks['manage_berkshelf'].nil? berksfile = cookbooks['scm']['repository'].sub(/[\/\\]+$/,'') + '/Berksfile' cookbooks['manage_berkshelf'] = File.exist?(berksfile) end end # remove the local cache to force opsworks to update custom cookbooks log "Purging local cookbooks cache from '/opt/aws/opsworks/current/site-cookbooks'..." FileUtils.rm_rf('/opt/aws/opsworks/current/site-cookbooks/') end if dna['opsworks']['instance']['hostname'] log "Setting instance hostname..." set_hostname dna['opsworks']['instance']['hostname'] end # run some base recipes if none explicitly provided if dna['opsworks_custom_cookbooks']['recipes'].empty? dna['opsworks_custom_cookbooks']['recipes']= %w( recipe[opsworks_initial_setup] recipe[ssh_host_keys] recipe[ssh_users] recipe[dependencies] recipe[ebs] recipe[agent_version] recipe[opsworks_stack_state_sync] recipe[opsworks_cleanup] ) end log "Generating dna.json..." dna_file = save_json_tempfile dna, 'dna.json' log "Running opsworks agent..." # AWS currently does not set UTF-8 as default encoding system({"LANG" => "POSIX"}, "opsworks-agent-cli run_command -f #{dna_file}") rescue OpsWorksError => e warn "Error: #{e}" exit false end def self.save_json_tempfile(data, name) tmp_dir = Dir.mktmpdir('vagrant-opsworks') File.chmod(0755, tmp_dir) tmp_file = "#{tmp_dir}/#{name}" File.open(tmp_file, 'w') { |f| f.write JSON.pretty_generate(data) } File.chmod(0755, tmp_file) tmp_file end def self.log(msg) puts msg end def self.check_dependencies `apt-get -yq install git 2>&1` if `which git`.empty? end def self.set_hostname(hostname) if !File.readlines('/etc/hosts').grep(/(?=[^\.\w-]|$)#{hostname}(?=[^\.\w-]|$)/).any? File.open('/etc/hosts', 'a') do |f| f.puts "\n127.0.0.1\t#{hostname}.localdomain #{hostname}\n" end end File.write('/etc/hostname', hostname) system('hostname', hostname) end def self.expand_paths(args) files = [] args.each do |file| if File.exist?(file) files << file elsif file.include? '*' files += Dir.glob(file) else raise OpsWorksError, "The file '#{file}' does not appear to exist." end end files end def self.compile_json(files) # combine all json files into one hash, starting with our base hash to # provide some sensible defaults dna = files.reduce(DNA_BASE) do |dna, file| log "Processing '#{file}'..." begin json = File.read(file).strip || '{}' json = JSON.parse(json) rescue JSON::ParserError => e raise OpsWorksError, "The file '#{file}' does not appear to be valid JSON. (error: #{e})" end deep_merge(dna, json) end # ensure each layer has some required fields including instances with both # private and public ip addresses dna['opsworks']['layers'].each do |name, layer| next unless Hash === layer layer['name'] ||= name layer['elb-load-balancers'] ||= [] layer['instances'] ||= {} next unless Hash === layer['instances'] layer['instances'].each do |name, instance| next unless Hash === instance instance['private_ip'] ||= instance['ip'] instance['ip'] ||= instance['private_ip'] end end # merge some default values into each app definition dna['deploy'].each do |name, app| app.replace deep_merge(DNA_DEPLOY_BASE, app) app['application'] ||= name app['domains'] << name if app['domains'].empty? end dna end def self.prepare_deployment(path) tmp_dir = Dir.mktmpdir('vagrant-opsworks') File.chmod(0755, tmp_dir) FileUtils.cp_r("#{path}/.", tmp_dir) Dir.chdir(tmp_dir) do `find . -name '.git*' -exec rm -rf {} \\; 2>&1; git init; git add .; git -c user.name='Vagrant' -c user.email=none commit -m 'Create temporary repository for deployment.'` end tmp_dir end def self.deep_merge(a, b) a.merge(b) { |_, a, b| Hash === a && Hash === b ? deep_merge(a, b) : b } end def self.agent_version File.read('/opt/aws/opsworks/current/REVISION')[/\d\d\d\d\-\d\d-\d\d-\d\d:\d\d:\d\d (\d+)/, 1].to_i end def self.agent_revision date_string = File.read('/opt/aws/opsworks/current/REVISION')[/(\d\d\d\d\-\d\d-\d\d-\d\d:\d\d:\d\d)/, 1] raise OpsWorksError, 'Unable to parse agent revision' unless date_string DateTime.strptime date_string, '%Y-%m-%d-%H:%M:%S' end end # automatically run provisioner if __FILE__ == $0 STDOUT.sync = true OpsWorks.provision *ARGV end
# Write a method that returns true if its integer argument is palindromic, false otherwise. A palindromic number reads the same forwards and backwards. def palindromic_number?(number) number.to_s == number.to_s.reverse end palindromic_number?(34543) == true palindromic_number?(123210) == false palindromic_number?(22) == true palindromic_number?(5) == true
class PhotosController < ApplicationController before_action :authenticate_usermodel! def create @stay = Stay.find(params[:stay_id]) @stay.photos.create(photo_params) redirect_to stay_path(@stay) end private def photo_params params.require(:photo).permit(:caption, :picture, :usermodel_id) end end
require "rails_helper" require "helpers/tournament_helper" describe "tournament test" do include TournamentHelper it "์ตœ์†Œ์ธ์›๋ณด๋‹ค ๋ฏธ๋‹ฌ์ผ ๋•Œ ํ† ๋„ˆ๋จผํŠธ ์‹œ์ž‘ ์‹คํŒจ" do users_count = 7 create_tournament({ register: users_count }) expect_all_memberships_count users_count start_tournament expect_status "canceled" expect_all_matches_count 0 expect_memberships_count(users_count, {status: "canceled"}) end it "์ตœ์†Œ์ธ์›์ผ ๋•Œ ํ† ๋„ˆ๋จผํŠธ ์‹œ์ž‘ ์„ฑ๊ณต" do users_count = 8 create_tournament({ register: users_count }) expect_all_memberships_count users_count start_tournament expect_status "progress" expect_memberships_count(users_count, {status: "progress"}) end it "์ตœ์†Œ์ธ์›์€ ๋„˜์ง€๋งŒ ์ตœ๋Œ€์ธ์›๋ณด๋‹ค ์ž‘์„ ๋•Œ ํ† ๋„ˆ๋จผํŠธ ์‹œ์ž‘ ์„ฑ๊ณต" do users_count = 9 create_tournament({ register: users_count}) expect_all_memberships_count users_count start_tournament expect_status "progress" expect_memberships_count(users_count, {status: "progress"}) end it "์ตœ์†Œ์ธ์›์ผ ๋•Œ ํ† ๋„ˆ๋จผํŠธ ์ฒซ ๋‚  ๋งค์นญ ์„ฑ๊ณต" do create_tournament({ register: 8 }) start_tournament expect_all_matches_count 4 expect_all_scorecards_count 8 end it "ํ™€์ˆ˜์ผ ๋•Œ ํ† ๋„ˆ๋จผํŠธ ์ฒซ ๋‚  ๋งค์นญ ์„ฑ๊ณต" do users_count = 13 create_tournament({ register: users_count }) start_tournament expect_all_matches_count 6 expect_all_scorecards_count 12 end # 8์ธ๋ถ€ํ„ฐ 32์ธ ์ผ€์ด์Šค ๋ชจ๋‘ ์ฒดํฌ์‹œ ์‹œ๊ฐ„์ด 45์ดˆ ์ •๋„ ์†Œ์š”๋˜๋ฏ€๋กœ ์ ์ ˆํžˆ ๋ณ€๊ฒฝํ•˜์—ฌ ์‚ฌ์šฉ it "๊ฒฝ๊ธฐ์— ๋น ์ง์—†์ด ์ฐธ์—ฌํ•  ๋•Œ์˜ ํ† ๋„ˆ๋จผํŠธ ์šด์˜" do (8..32).each do |users_count| create_tournament({ register: users_count }) simulate_tournament({ complete_ratio: [1.0] }) match_count = matches_count_if_all_completed_when(users_count) expect_all_matches_count matches_count expect_all_scorecards_count matches_count*2 expect_winner_get_title true expect_status "completed" expect_matches_count(matches_count, {status: "completed"}) expect_scorecards_count(matches_count, {result: "win"}) expect_scorecards_count(matches_count, {result: "lose"}) expect_memberships_count(users_count, {status: "completed"}) expect_memberships_count(1, {result: "gold"}) expect_memberships_count(1, {result: "silver"}) bronze_count = bronze_count_if_all_match_completed_when(users_count) expect_memberships_count(bronze_count, {result: "bronze"}) end end # 8์ธ๋ถ€ํ„ฐ 32์ธ ์ผ€์ด์Šค ๋ชจ๋‘ ์ฒดํฌ์‹œ ์‹œ๊ฐ„์ด 27์ดˆ ์ •๋„ ์†Œ์š”๋˜๋ฏ€๋กœ ์ ์ ˆํžˆ ๋ณ€๊ฒฝํ•˜์—ฌ ์‚ฌ์šฉ it "๋ชจ๋‘ ๋ถˆ์ฐธํ•  ๋•Œ์˜ ํ† ๋„ˆ๋จผํŠธ ์šด์˜" do (8..32).each do |users_count| create_tournament({ register: users_count }) simulate_tournament({ complete_ratio: [0] }) matches_count = users_count / 2 expect_all_matches_count matches_count expect_all_scorecards_count matches_count*2 expect_winner_get_title false expect_status "completed" expect_matches_count(matches_count, {status: "canceled"}) expect_scorecards_count(matches_count*2, {result: "canceled"}) expect_memberships_count(users_count, {status: "completed"}) expect_memberships_count(0, {result: "gold"}) expect_memberships_count(0, {result: "silver"}) expect_memberships_count(0, {result: "bronze"}) end end # 8์ธ๋ถ€ํ„ฐ 32์ธ ์ผ€์ด์Šค ๋ชจ๋‘ ์ฒดํฌ์‹œ ์‹œ๊ฐ„์ด 35์ดˆ ์ •๋„ ์†Œ์š”๋˜๋ฏ€๋กœ ์ ์ ˆํžˆ ๋ณ€๊ฒฝํ•˜์—ฌ ์‚ฌ์šฉ it "์—ฃ์ง€ ์ผ€์ด์Šค with ratio" do print_to "edge-tournament-log" (32..32).each do |users_count| create_tournament({ register: users_count }) simulate_tournament({ complete_ratio: [0.8, 0.7, 1.0] }) expect_matches_count(all_matches_count, {status: ["canceled", "completed"]}) expect_scorecards_count(all_scorecards_count, {result: ["canceled", "win", "lose"]}) expect_memberships_count(users_count, {status: "completed"}) expect_status "completed" expect_all_scorecards_count all_matches_count*2 expect_normal_memberships_result_count end print_close end end
class OrderedKeyVal attr_accessor :keys, :values def initialize @keys = [] @values = [] end def max @keys[-1] end def min @keys[0] end def delete_min @keys.shift @values.shift end def ceiling(key) i = insertion_index(key) if i == @keys.length return nil else return @keys[i] end end def insert_array(arr,val) arr.each do |x| self[x] = val end end # O(n) insertion with O(logn) time to lookup position to add item # Move the nil value from the end into the place of insertion and then add the insertion key there. def []=(key,val) if @keys.empty? @keys << key @values << val return end if h = index(key) @values[h] = val return end i = insertion_index(key) if i == 0 @keys.unshift(key) @values.unshift(val) elsif i == @keys.length @keys << key @values << val else r = @keys.length while r > i @keys[r],@keys[r-1] = @keys[r-1],@keys[r] @values[r],@values[r-1] = @values[r-1],@values[r] r -= 1 end @keys[i] = key @values[i] = val end end def [](key) i = index(key) return nil if !i return @values[i] end # O(lgn) def index(key) lo = 0 hi = @keys.length - 1 while lo <= hi mid = (lo+hi)/2 case key <=> @keys[mid] when -1 hi = mid - 1 when 1 lo = mid + 1 else return mid end end return nil end def iterate @keys @values @keys.zip(@values) end # O(n) def delete(key) i = index(key) return if !i @keys[i]=nil @values[i]=nil while i < @keys.length - 1 @keys[i],@keys[i+1] = @keys[i+1],@keys[i] @values[i],@values[i+1] = @values[i+1],@values[i] i += 1 end @keys.pop @values.pop end # O(logN) def rank(key) index(key) end # Assuming the array is already sorted there is O(logN) insertion def insertion_index(key) lo = 0 hi = @keys.length - 1 while lo < hi mid = (lo+hi)/2 case key <=> @keys[mid] when -1 hi = mid - 1 when 1 lo = mid + 1 when 0 return mid end end # At this point lo == hi if key < @keys[lo] return lo else return hi + 1 end end end # kv = OrderedKeyVal.new # kv["A"] = 6 # kv["G"] = 8 # kv["E"] = 9 # kv["O"] = 76 # kv["D"] = 46 # kv["Q"] = 638 # kv["V"] = 621 # kv["G"] = 6739 # kv["L"] = 893 # kv["T"] = 993 # kv.delete("X") # p kv["G"] # p kv["E"] # kv.iterate # p kv.rank("V") # p kv.ceiling("A")
module OrientdbBinary module BaseProtocol class RecordCreate < BinData::Record include OrientdbBinary::BaseProtocol::Base endian :big int8 :operation, value: OrientdbBinary::OperationTypes::REQUEST_RECORD_CREATE int32 :session int32 :datasegment_id int16 :cluster_id protocol_string :record_content int8 :record_type int8 :mode end class RecordCreateAnswer < BinData::Record endian :big int32 :session int64 :cluster_position int32 :record_version def process(options) return { :@rid => "##{options[:cluster_id]}:#{cluster_position}", :@version => record_version, :@type => options[:record_type] } end end end end
# Write a method that takes a positive integer as an argument and returns that number with its digits reversed. # Don't worry about arguments with leading zeros - Ruby sees those as octal numbers, which will cause confusing results. For similar reasons, the return value for our fourth example doesn't have any leading zeros. def reversed_number(num) num.to_s.reverse.to_i end reversed_number(12345) == 54321 reversed_number(12213) == 31221 reversed_number(456) == 654 reversed_number(12000) == 21 # No leading zeros in return value! reversed_number(12003) == 30021 reversed_number(1) == 1
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) topMenu1 = TopMenu.create(title: "็งŸๆˆท่ฎพ็ฝฎ", description: "็งŸๆˆท็‰นๆœ‰็š„่ฎพ็ฝฎ้กน็›ฎ") topMenu2 = TopMenu.create(title: "ๅนณๅฐ่ฎพ็ฝฎ", description: "ๅนณๅฐ้€š็”จๅŠŸ่ƒฝ๏ผŒๅŒ…ๆ‹ฌๆ ‡ๅ‡†ๅฏน่ฑกๅ’Œ่‡ชๅฎšไน‰ๆŒ‰้’ฎ็š„็ฎก็†ๅŠŸ่ƒฝ็ญ‰") topMenu3 = TopMenu.create(title: "ไธชไบบ่ฎพ็ฝฎ", description: "ไธชไบบไฝฟ็”จๅ–œๅฅฝ่ฎพ็ฝฎ") subMenu11 = SubMenu.create(title: "ๅŒบๅŸŸๅ’Œ่ฏญ่จ€", description: "ๆ—ถๅŒบใ€้ป˜่ฎค่ฏญ่จ€ใ€ๅธ็งใ€ๆ—ถ้—ดๆ ผๅผ็ญ‰่ฎพ็ฝฎ", top_menu: topMenu1) subMenu12 = SubMenu.create(title: "ๅฎšๆ—ถ้€š็Ÿฅ", description: "ๅฎšๆ—ถ้€š็Ÿฅ", top_menu: topMenu1) subMenu13 = SubMenu.create(title: "ๆŽจ้€็ฎก็†", description: "ๆŽจ้€็ฎก็†", top_menu: topMenu1) subMenu14 = SubMenu.create(title: "้ฃŽ้™ฉ้ข„่ญฆ", description: "้ฃŽ้™ฉ้ข„่ญฆ", top_menu: topMenu1) subMenu15 = SubMenu.create(title: "ๆŠฅ่กจ็ฎก็†", description: "ๆŠฅ่กจ็ฎก็†", top_menu: topMenu1) subMenu21 = SubMenu.create(title: "ๆ ‡ๅ‡†ๅฏน่ฑก็ฎก็†", description: "ๆ ‡ๅ‡†ๅฏน่ฑกๅŠๅญ—ๆฎต็š„ๆ–ฐๅปบๅ’Œ็ฎก็†", top_menu: topMenu2) subMenu22 = SubMenu.create(title: "ๆƒ้™่ฎพ็ฝฎ", description: "ๅ…จๅŽฟ่ฎพ็ฝฎ", top_menu: topMenu2) subMenu23 = SubMenu.create(title: "ๅธƒๅฑ€่ฎพ็ฝฎ", description: "้กต้ขๅธƒๅฑ€่ฎพ็ฝฎ", top_menu: topMenu2) subMenu31 = SubMenu.create(title: "่ฏญ่จ€่ฎพ็ฝฎ", description: "่‡ชๅฎšไน‰็ณป็ปŸ่ฏญ่จ€", top_menu: topMenu3) subMenu32 = SubMenu.create(title: "ไธป่œๅ•้กน็›ฎ็ฎก็†", description: "่‡ชๅฎšไน‰ไธป่œๅ•ไธญ็š„้กน็›ฎ", top_menu: topMenu3) ############ # ่ฎพ็ฝฎ้ขๆฟ ############ section111 = Section.create(title: "ๆ—ถๅŒบ่ฎพ็ฝฎ", description: "time zone", mode: "Record", sub_menu: subMenu11) section112 = Section.create(title: "้ป˜่ฎค่ฏญ่จ€่ฎพ็ฝฎ", description: "default lang", mode: "Record", sub_menu: subMenu11) section112 = Section.create(title: "ๅธ็ง่ฎพ็ฝฎ", description: "currency format", mode: "Record", sub_menu: subMenu11) section121 = Section.create(title: "ๅฎšๆ—ถ้€š็Ÿฅ่ฎพ็ฝฎ", description: "ๅฎšๆ—ถ้€š็Ÿฅ", mode: "List", sub_menu: subMenu12) section131 = Section.create(title: "ๆŽจ้€็ฎก็†", description: "ๆŽจ้€็ฎก็†", mode: "List", sub_menu: subMenu13) section141 = Section.create(title: "้ฃŽ้™ฉ้ข„่ญฆ", description: "้ฃŽ้™ฉ้ข„่ญฆ", mode: "List", sub_menu: subMenu14) section151 = Section.create(title: "ๆŠฅ่กจ็ฎก็†", description: "ๆŠฅ่กจ็ฎก็†", mode: "List", sub_menu: subMenu15) section211 = Section.create(title: "ๆ ‡ๅ‡†ๅฏน่ฑก็ฎก็†", description: "ๆ ‡ๅ‡†ๅฏน่ฑกๅŠๅญ—ๆฎต็š„ๆ–ฐๅปบๅ’Œ็ฎก็†", mode: "List", sub_menu: subMenu21) section221 = Section.create(title: "ๆƒ้™่ฎพ็ฝฎ", description: "ๆƒ้™่ฎพ็ฝฎ", mode: "List", sub_menu: subMenu22) section231 = Section.create(title: "ๅธƒๅฑ€่ฎพ็ฝฎ", description: "้กต้ขๅธƒๅฑ€่ฎพ็ฝฎ", mode: "List", sub_menu: subMenu23)
require 'sumac' # make sure it exists describe Sumac::Messages::CallRequest do # should be a subclass of Message example do expect(Sumac::Messages::CallRequest < Sumac::Messages::Message).to be(true) end # ::build, #properties, #to_json example do object = instance_double('Sumac::Objects::Reference') object_component = instance_double('Sumac::Messages::Component::Exposed', :properties => { 'object_type' => 'exposed', 'origin' => 'remote', 'id' => 1 }) expect(Sumac::Messages::Component).to receive(:from_object).with(object).and_return(object_component) argument1_component = instance_double('Sumac::Messages::Component::Integer', :properties => { 'object_type' => 'integer', 'value' => 2 }) expect(Sumac::Messages::Component).to receive(:from_object).with(2).and_return(argument1_component) argument2_component = instance_double('Sumac::Messages::Component::String', :properties => { 'object_type' => 'string', 'value' => 'abc' }) expect(Sumac::Messages::Component).to receive(:from_object).with('abc').and_return(argument2_component) message = Sumac::Messages::CallRequest.build(id: 0, object: object, method: 'm', arguments: [2, 'abc']) expect(message).to be_a(Sumac::Messages::CallRequest) expect(JSON.parse(message.to_json)).to eq({ 'message_type' => 'call_request', 'id' => 0, 'object' => { 'object_type' => 'exposed', 'origin' => 'remote', 'id' => 1 }, 'method' => 'm', 'arguments' => [{ 'object_type' => 'integer', 'value' => 2 }, { 'object_type' => 'string', 'value' => 'abc' }] }) end # ::from_properties, #arguments, #object, #id, #method # missing or unexpected property example do properties = { 'message_type' => 'call_request' } expect{ Sumac::Messages::CallRequest.from_properties(properties) }.to raise_error(Sumac::ProtocolError) end # invalid 'id' property example do properties = { 'message_type' => 'call_request', 'id' => '1', 'object' => { 'object_type' => 'exposed', 'origin' => 'local', 'id' => 1 }, 'method' => 'm', 'arguments' => [] } expect{ Sumac::Messages::CallRequest.from_properties(properties) }.to raise_error(Sumac::ProtocolError) end # invalid 'object' property type example do properties = { 'message_type' => 'call_request', 'id' => 1, 'object' => { 'object_type' => 'null' }, 'method' => 'm', 'arguments' => [] } expect{ Sumac::Messages::CallRequest.from_properties(properties) }.to raise_error(Sumac::ProtocolError) end # invalid 'object' property origin example do properties = { 'message_type' => 'call_request', 'id' => 1, 'object' => { 'object_type' => 'exposed', 'origin' => 'remote', 'id' => 1 }, 'method' => 'm', 'arguments' => [] } expect{ Sumac::Messages::CallRequest.from_properties(properties) }.to raise_error(Sumac::ProtocolError) end # invalid 'method' property type example do properties = { 'message_type' => 'call_request', 'id' => 1, 'object' => { 'object_type' => 'exposed', 'origin' => 'local', 'id' => 1 }, 'method' => 1, 'arguments' => [] } expect{ Sumac::Messages::CallRequest.from_properties(properties) }.to raise_error(Sumac::ProtocolError) end # 'method' property empty example do properties = { 'message_type' => 'call_request', 'id' => 1, 'object' => { 'object_type' => 'exposed', 'origin' => 'local', 'id' => 1 }, 'method' => '', 'arguments' => [] } expect{ Sumac::Messages::CallRequest.from_properties(properties) }.to raise_error(Sumac::ProtocolError) end # invalid 'arguments' property example do properties = { 'message_type' => 'call_request', 'id' => 1, 'object' => { 'object_type' => 'exposed', 'origin' => 'local', 'id' => 1 }, 'method' => '', 'arguments' => {} } expect{ Sumac::Messages::CallRequest.from_properties(properties) }.to raise_error(Sumac::ProtocolError) end # all properties present and valid example do properties = { 'message_type' => 'call_request', 'id' => 0, 'object' => { 'object_type' => 'exposed', 'origin' => 'local', 'id' => 1 }, 'method' => 'm', 'arguments' => [{ 'object_type' => 'integer', 'value' => 2 }, { 'object_type' => 'string', 'value' => 'abc' }] } message = Sumac::Messages::CallRequest.from_properties(properties) expect(message).to be_a(Sumac::Messages::CallRequest) object = instance_double('Sumac::Messages::Component::Exposed') allow_any_instance_of(Sumac::Messages::Component::Exposed).to receive(:object).and_return(object) expect(message.arguments).to eq([2,'abc']) expect(message.object).to be(object) expect(message.id).to eq(0) expect(message.method).to eq('m') end end
module GameOfLife class Board attr_reader :grid def initialize(rows, columns, state = nil) @rows = rows @columns = columns @grid = Array.new(rows) { Array.new(columns, StateMachine::DEAD) } if state initialize_state(state) end end def initialize_state(state) state.each do |i, j| @grid[i][j] = StateMachine::LIVE end end def randomize() rng = Random.new() state = [] cells = (@rows * @columns) / ((@rows + @columns) / 4) rng.rand(cells..cells+16).times do |i| if rng.rand(2) > 0 or i == 0 # place completely random point state << [rng.rand(@rows), rng.rand(@columns)] else # attempt to cluster in some way row = state[i-1][0] + rng.rand(-1..1) column = state[i-1][1] + rng.rand(-1..1) # catch edge cases row = rng.rand(@rows) if (row >= @rows or row < 0) column = rng.rand(@columns) if (column >= @columns or column < 0) state << [row, column] end end initialize_state(state) end def next_state new_grid = [] @grid.each_with_index do |row, i| new_row = [] row.each_with_index do |column, j| new_row << StateMachine.next_state(@grid[i][j], live_neighbors(i, j)) end new_grid << new_row end @grid = new_grid end def live_neighbors(row, column) count = 0 (-1..1).each do |i| (-1..1).each do |j| next if (i.zero?() and j.zero?()) row_index = row + i column_index = column + j if row_index >= 0 and row_index < @rows and column_index >= 0 and column_index < @columns count += 1 if @grid[row_index][column_index] == StateMachine::LIVE end end end return count end def to_s s = "" s << "#" * (@columns + 2) << "\n" @grid.each do |row| s << "#" row.each do |column| if column == StateMachine::LIVE s << "*" else s << " " end end s << "#\n" end return s << "#" * (@columns + 2) << "\n" end end class StateMachine # Any live cell with fewer than two live neighbors dies, as if caused by under-population # Any live cell with two or three live neighbors lives on to the next generation # Any live cell with more than three live neighbors dies, as if by overcrowding # Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction DEATH = [0, 1, 4, 5, 6, 7, 8] BIRTH = [3] LIVE = 1 DEAD = 0 def self.next_state(cell, live_neighbors) if cell == DEAD if BIRTH.include?(live_neighbors) return LIVE else return DEAD end elsif cell == LIVE if DEATH.include?(live_neighbors) return DEAD else return LIVE end else return DEAD end end end end if __FILE__ == $0 require "socket" require "timeout" # bind and listen acceptor = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) address = Socket.pack_sockaddr_in(45678, "0.0.0.0") acceptor.bind(address) acceptor.listen(10) # set up traps trap("EXIT") { acceptor.close() } trap("INT") { exit() } # accept and fork loop do socket, addr = acceptor.accept() fork do begin # create new random number generator rng = Random.new() # start our game loop 100.times do |i| # create a randomly-generated board columns = rng.rand(8..32) rows = rng.rand(8..32) game = GameOfLife::Board.new(rows, columns) game.randomize() # send the board to the client generations = rng.rand(16..64) socket.write("\n##### Round #{i + 1}: #{generations} Generations #####\n") socket.write(game) socket.flush() # advance the state machine generations.times do game.next_state() end #puts(game) # UNCOMMENT FOR DEBUGGING (can then copy/paste answers into netcat) # read and check the client's answer begin timeout(2) do game.to_s.each_line do |line| response = socket.gets() if response != line socket.close() exit() end end end rescue Timeout::Error socket.puts("\nToo slow!") socket.close() exit() end end # if the client made it through, send them the key as the 100th round File.open("key", "r") do |key| puts("\nCongratulations!") puts("You made it!") puts("Here's your prize: #{key.read()}") end rescue socket.close() exit() end end socket.close() end end
# An EXAMPLE Basic Model for Assets that conform to Hydra commonMetadata cModel and have basic MODS metadata (currently "Article" is the MODS exemplar) class ModsAsset < ActiveFedora::Base extend Deprecation def initialize(*) Deprecation.warn(ModsAsset, "ModsAsset is deprecated and will be removed in hydra-head 10") super end ## Convenience methods for manipulating the rights metadata datastream include Hydra::AccessControls::Permissions # adds helpful methods for basic hydra objects include Hydra::ModelMethods end
# frozen_string_literal: true class User module Register def register @event = Event.find_by(id: clean_params[:id]) return if no_member_registrations? || no_registrations? register_for_event! if @registration.valid? successfully_registered else unable_to_register end end def cancel_registration @registration = Registration.find_by(id: clean_params[:id]) return unless can_cancel_registration? @event = @registration.event @cancel_link = (@registration&.user == current_user) return cannot_cancel_paid if @registration&.paid? @registration&.destroy ? successfully_cancelled : unable_to_cancel end def override_cost return if @registration.is_a?(Registration) redirect_to receipts_path, alert: 'Can only override registration costs.' end def set_override_cost if @registration.update(reg_params) reg_params[:override_cost].to_i.zero? ? removed_flash : set_flash else flash[:alert] = 'Unable to override registration cost.' end redirect_to send("#{@registration.event.category}_registrations_path") end private def find_registration @registration = Registration.find_by(id: clean_params[:id]) @registration ||= Payment.find_by(token: clean_params[:token]).parent end def block_override return unless not_overrideable? if @registration.paid? flash[:notice] = 'That registration has already been paid.' elsif @registration.payment_amount&.zero? flash[:notice] = 'That registration has no cost.' end redirect_to override_path end def override_path cat = @registration.event.category.to_s == 'meeting' ? 'event' : @registration.event.category send("#{cat}_registrations_path") end def not_overrideable? @registration.paid? || @registration.payment_amount&.zero? end def reg_params params.require(:registration).permit(:override_cost, :override_comment) end def set_flash flash[:success] = 'Successfully overrode registration cost.' end def removed_flash flash[:success] = 'Successfully removed override registration cost.' end def no_member_registrations? return false if @event.allow_member_registrations flash.now[:alert] = 'This course is not accepting member registrations.' render status: :unprocessable_entity true end def no_registrations? return false if @event.registerable? flash.now[:alert] = 'This course is no longer accepting registrations.' render status: :unprocessable_entity true end def register_for_event! @registration = current_user.register_for(@event) end def successfully_registered flash[:success] = 'Successfully registered!' RegistrationMailer.registered(@registration).deliver # If the event does not require advance payment, this will notify on create. # # Otherwise, a different notification will be sent, and the regular one will # be triggered by BraintreeController once the registration is paid for. if @registration.event.advance_payment && !@registration.reload.paid? RegistrationMailer.advance_payment(@registration).deliver else RegistrationMailer.confirm(@registration).deliver end registered_slack_notification end def unable_to_register flash.now[:alert] = 'We are unable to register you at this time.' render status: :unprocessable_entity end def can_cancel_registration? return true if allowed_to_cancel? flash[:alert] = 'You are not allowed to cancel that registration.' redirect_to root_path, status: :unprocessable_entity false end def allowed_to_cancel? (@registration&.user == current_user) || current_user&.permitted?(:course, :seminar, :event) end def successfully_cancelled flash[:success] = 'Successfully cancelled registration!' return unless @cancel_link RegistrationMailer.cancelled(@registration).deliver cancelled_slack_notification end def unable_to_cancel flash.now[:alert] = 'We are unable to cancel your registration.' render status: :unprocessable_entity end def cannot_cancel_paid flash[:alert] = 'That registration has been paid, and cannot be cancelled.' render status: :unprocessable_entity end def registered_slack_notification SlackNotification.new( channel: :notifications, type: :warning, title: 'New Registration', fallback: 'Someone has registered for an event.', fields: slack_fields ).notify! end def cancelled_slack_notification SlackNotification.new( channel: :notifications, type: :warning, title: 'Registration Cancelled', fallback: 'Someone has cancelled their registration for an event.', fields: slack_fields ).notify! end def slack_fields { 'Event' => "<#{show_event_url(@registration.event)}|#{@registration.event.display_title}>", 'Event date' => @registration.event.start_at.strftime(TimeHelper::SHORT_TIME_FORMAT), 'Registrant name' => @registration.user.full_name, 'Registrant email' => @registration.user.email }.compact end end end
class Spot < ApplicationRecord validates :name, presence:true, length:{ in: 1..32 }, uniqueness: { scope: :address } validates :address, presence: true, uniqueness: true, length:{ maximum: 140 }, uniqueness: { scope: :name } validates :spot_time, length:{ maximum: 10 } validates :price, length:{ maximum: 99999 } validates :plan_id, presence:true # has_many :plan_spots, :dependent => :destroy # has_many :plans, through :plan_spots end
require 'rails_helper' feature "Sign in" do scenario "Article displays on show" do Article.create!( headline: "Test article", body: "Test", image: nil, date_field: "2015-12-31", category: "testcategory", source: "testsource" ) visit root_path fill_in "search articles", with: "Test article" expect(page).to have_content("Test article") expect(page).to have_content("testsource") expect(page).to have_content("Testcategory") end end
module Nitron module Data class Relation < NSFetchRequest module CoreData def inspect to_a end def to_a error_ptr = Pointer.new(:object) context.executeFetchRequest(self, error:error_ptr) end private def context UIApplication.sharedApplication.delegate.managedObjectContext end end end end end
class ChangeTemplatesToPolymorphic < ActiveRecord::Migration def up change_table :templates do |t| t.references :templable, :polymorphic => true end remove_column :templates, :subject_id end def down change_table :templates do |t| t.remove_references :templable, :polymorphic => true end add_column :templates, :subject_id, :integer end end
class UsersController < ApplicationController before_action :authenticate_user!, only: [:index, :following, :followers] before_action :currect_user, only: [:edit, :update] before_action :admin_user, only: :destroy def index @users = User.paginate(page: params[:page], :per_page => 10) end def show @user = User.find(params[:id]) @microposts = @user.microposts.paginate(page: params[:page], :per_page =>10 ) end def destroy User.find(params[:id]).destroy flash[:success] = "User deleted" redirect_to users_url end def following @title = "Following" @user = User.find(params[:id]) @users = @user.following.paginate(page: params[:page], :per_page => 10) render 'show_follow' end def followers @title = "Followers" @user = User.find(params[:id]) @users = @user.followers.paginate(page: params[:page], :per_page => 10) render 'show_follow' end private def admin_user redirect_to(root_url) unless current_user.admin? end def currect_user @user = User.find(params[:id]) redirect_to(root_url) unless current_user?(@user) end end
# frozen_string_literal: true require 'date' module Jiji::Utils class TimeSource KEY = :jiji_time_source__now def now Thread.current[KEY] || Time.now end def set(time) Thread.current[KEY] = time || Time.now end def reset Thread.current[KEY] = nil end end end
Spree::Admin::TaxonsController.class_eval do def update Spree::Taxon::LANG.each do |locale| I18n.locale = locale @taxonomy = Spree::Taxonomy.find(params[:taxonomy_id]) @taxon = @taxonomy.taxons.find(params[:id]) parent_id = params[:taxon][:parent_id] new_position = params[:taxon][:position] if parent_id || new_position #taxon is being moved new_parent = parent_id.nil? ? @taxon.parent : Taxon.find(parent_id.to_i) new_position = new_position.nil? ? -1 : new_position.to_i new_siblings = new_parent.children if new_position <= 0 && new_siblings.empty? @taxon.move_to_child_of(new_parent) elsif new_parent.id != @taxon.parent_id if new_position == 0 @taxon.move_to_left_of(new_siblings.first) else @taxon.move_to_right_of(new_siblings[new_position-1]) end elsif new_position < new_siblings.index(@taxon) @taxon.move_to_left_of(new_siblings[new_position]) # we move up else @taxon.move_to_right_of(new_siblings[new_position]) # we move down end # Reset legacy position, if any extensions still rely on it new_parent.children.reload.each{|t| t.update_attribute(:position, t.position)} if parent_id @taxon.reload @taxon.set_permalink @taxon.save! @update_children = true end end if params.key? "permalink_part_#{locale}" parent_permalink = @taxon.permalink.split("/")[0...-1].join("/") parent_permalink += "/" unless parent_permalink.blank? params[:taxon]["permalink_#{locale}".to_sym] = parent_permalink + params["permalink_part_#{locale}".to_sym] end #check if we need to rename child taxons if parent name or permalink changes @update_children = true if params[:taxon][:name] != @taxon.name || params[:taxon]["permalink_#{locale}".to_sym] != @taxon.permalink if @taxon.update_attributes(params[:taxon]) flash.notice = flash_message_for(@taxon, :successfully_updated) end #rename child taxons if @update_children @taxon.descendants.each do |taxon| taxon.reload taxon.set_permalink taxon.save! end end end I18n.locale = I18n.default_locale respond_with(@taxon) do |format| format.html {redirect_to edit_admin_taxonomy_url(@taxonomy) } format.json {render :json => @taxon.to_json } end end end
require 'spec_helper' describe Susanoo::PageView do let!(:top_genre) { create(:top_genre) } describe "#initialize" do context "pathใŒ'/'ใฎๅ ดๅˆ" do let(:path) { '/' } context "ๅ…ฌ้–‹ใƒšใƒผใ‚ธใŒ็„กใ„ๅ ดๅˆ" do before do @page_view = Susanoo::PageView.new(path) end it "@dirใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.dir).to eq('/') end it "@fileใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.file).to eq('index') end it "@genreใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.genre).to eq(top_genre) end it "@pageใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.page.attributes).to eq(Page.index_page(top_genre).attributes) end it "@publish_contentใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.publish_content).to eq(nil) end it "@layoutใซnormal_layoutใŒ่จญๅฎšใ•ใ‚Œใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.layout).to eq(Susanoo::PageView::TOP_LAYOUT) end end context "ๅ…ฌ้–‹ใƒšใƒผใ‚ธใŒใ‚ใ‚‹ๅ ดๅˆ" do let!(:page) { create(:page, :publish, name: 'index', genre_id: top_genre.id) } before do @page_view = Susanoo::PageView.new(path) end it "@pageใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.page).to eq(page) end it "@publish_contentใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.publish_content).to eq(page.publish_content) end it "@layoutใซtop_layoutใŒ่จญๅฎšใ•ใ‚Œใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.layout).to eq(Susanoo::PageView::TOP_LAYOUT) end end end context "pathใŒ'/genre11/test.html'ใฎๅ ดๅˆ" do let(:path) { '/genre11/test.html' } let!(:genre) { create(:genre, name: 'genre11', parent_id: top_genre.id) } context "ๅ…ฌ้–‹ใƒšใƒผใ‚ธใŒใ‚ใ‚‹ๅ ดๅˆ" do let!(:page) { create(:page, :publish, name: 'test', genre_id: genre.id) } before do @page_view = Susanoo::PageView.new(path) end it "@dirใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.dir).to eq('/genre11') end it "@fileใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.file).to eq(page.name) end it "@genreใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.genre).to eq(genre) end it "@pageใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.page).to eq(page) end it "@publish_contentใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.publish_content).to eq(page.publish_content) end it "@layoutใซnormal_layoutใŒ่จญๅฎšใ•ใ‚Œใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.layout).to eq(Susanoo::PageView::NORMAL_LAYOUT) end end end context "pathใŒ'/genre11/test.html.i'ใฎๅ ดๅˆ" do let(:path) { '/genre11/test.html.i' } let!(:genre) { create(:genre, name: 'genre11', parent_id: top_genre.id) } context "ๅ…ฌ้–‹ใƒšใƒผใ‚ธใŒใ‚ใ‚‹ๅ ดๅˆ" do let!(:page) { create(:page, :publish, name: 'test', genre_id: genre.id) } before do @page_view = Susanoo::PageView.new(path) end it "@dirใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.dir).to eq('/genre11') end it "@fileใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.file).to eq(page.name) end it "@genreใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.genre).to eq(genre) end it "@pageใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.page).to eq(page) end it "@publish_contentใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.publish_content).to eq(page.publish_content) end it "@layoutใซnormal_layoutใŒ่จญๅฎšใ•ใ‚Œใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.layout).to eq(Susanoo::PageView::NORMAL_LAYOUT) end it "@extensionใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.instance_eval{ @extension }).to eq('.html.i') end end end context "pathใŒ'/genre11'ใงGenreใฎใƒˆใƒƒใƒ—็”ป้ขใธใ‚ขใ‚ฏใ‚ปใ‚นใŒใใŸๅ ดๅˆ" do let(:path) { '/genre11' } let!(:genre) { create(:genre, name: 'genre11', parent_id: top_genre.id) } context "ๅ…ฌ้–‹ใƒšใƒผใ‚ธใŒ็„กใ„ๅ ดๅˆ" do before do @page_view = Susanoo::PageView.new(path) end it "@dirใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.dir).to eq('/genre11') end it "@fileใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.file).to eq('index') end it "@genreใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.genre).to eq(genre) end it "@pageใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.page.attributes).to eq(Page.index_page(genre).attributes) end it "@publish_contentใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.publish_content).to eq(nil) end it "@layoutใซgenre_top_layoutใŒ่จญๅฎšใ•ใ‚Œใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.layout).to eq(Susanoo::PageView::GENRE_TOP_LAYOUT) end end context "ๅ…ฌ้–‹ใƒšใƒผใ‚ธใŒใ‚ใ‚‹ๅ ดๅˆ" do let!(:page) { create(:page, :publish, name: 'index', genre_id: genre.id) } before do @page_view = Susanoo::PageView.new(path) end it "@pageใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.page).to eq(page) end it "@publish_contentใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.publish_content).to eq(page.publish_content) end it "@layoutใซnormal_layoutใŒ่จญๅฎšใ•ใ‚Œใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.layout).to eq(Susanoo::PageView::NORMAL_LAYOUT) end end end context "pathใŒ'/genre11'ใงSectionใฎใƒˆใƒƒใƒ—็”ป้ขใธใ‚ขใ‚ฏใ‚ปใ‚นใŒใใŸๅ ดๅˆ" do let(:path) { '/genre11' } let!(:genre) { create(:section_top_genre, name: 'genre11', parent: top_genre) } context "ๅ…ฌ้–‹ใƒšใƒผใ‚ธใŒใชใ„ๅ ดๅˆ" do before do @page_view = Susanoo::PageView.new(path) end it "@dirใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.dir).to eq('/genre11') end it "@fileใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.file).to eq('index') end it "@genreใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.genre).to eq(genre) end it "@pageใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.page.attributes).to eq(Page.index_page(genre).attributes) end it "@publish_contentใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.publish_content).to eq(nil) end it "@layoutใซgenre_top_layoutใŒ่จญๅฎšใ•ใ‚Œใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.layout).to eq(Susanoo::PageView::SECTION_TOP_LAYOUT) end end context "ๅ…ฌ้–‹ใƒšใƒผใ‚ธใŒใ‚ใ‚‹ๅ ดๅˆ" do let!(:page) { create(:page, :publish, name: 'index', genre_id: genre.id) } before do @page_view = Susanoo::PageView.new(path) end it "@pageใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.page).to eq(page) end it "@publish_contentใซๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.publish_content).to eq(page.publish_content) end end end context "page_contentใŒๆŒ‡ๅฎšใ•ใ‚ŒใŸๅ ดๅˆ" do let(:top_genre) { create(:top_genre) } let(:page) { create(:page_publish, genre_id: top_genre.id) } before do @page_view = Susanoo::PageView.new(page_content: page.publish_content) end it "@publish_contentใธๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.publish_content).to eq(page.publish_content) end it "@pageใธๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.page).to eq(page) end it "@genreใธๆญฃใ—ใ„ๅ€คใ‚’่จญๅฎšใ—ใฆใ„ใ‚‹ใ“ใจ" do expect(@page_view.genre).to eq(top_genre) end end end describe "#rendering_view_name" do let(:template) { 'show' } before do allow_any_instance_of(Susanoo::PageView).to receive(:template).and_return(template) end context "publish_contentใŒๅญ˜ๅœจใ™ใ‚‹ๅ ดๅˆ" do let(:top_genre) { create(:top_genre) } let(:page) { create(:page_publish, genre_id: top_genre.id) } before do @page_view = Susanoo::PageView.new(page.path) end it "ๆฑบใ‚ใ‚‰ใ‚ŒใŸtemplateใ‚’่ฟ”ใ™ใ“ใจ" do expect(@page_view.rendering_view_name(false)).to eq(template) end end context "mobileใฎๅ ดๅˆ" do let(:top_genre) { create(:top_genre) } let(:page) { create(:page_publish, genre_id: top_genre.id) } before do @page_view = Susanoo::PageView.new(page.path) end it "ใƒขใƒใ‚คใƒซ็”จใฎtemplateใ‚’่ฟ”ใ™ใ“ใจ" do expect(@page_view.rendering_view_name(true)).to eq('susanoo/visitors/mobiles/content') end end context "PageใŒๅญ˜ๅœจใ—ใชใ„ๅ ดๅˆ" do before do @page_view = Susanoo::PageView.new('/test/test/test.html') end it "not_foundใ‚’่ฟ”ใ™ใ“ใจ" do expect(@page_view.rendering_view_name(false)).to eq( action: 'not_found', status: 404, layout: false ) end end end end
# encoding: utf-8 class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :readings has_one :twine has_many :sensors belongs_to :building has_many :collaborations, dependent: :destroy has_many :collaborators, through: :collaborations belongs_to :unit validates :first_name, :length => { minimum: 2 } validates :last_name, :length => { minimum: 2 } #validate :sensor_codes_string_contains_only_valid_sensors validates_presence_of :address, :email, :zip_code validates_format_of :zip_code, with: /\A\d{5}-\d{4}|\A\d{5}\z/, message: "should be 12345 or 12345-1234", allow_blank: true validates :sms_alert_number, format: { with: /\A\+?[1-9]\d{1,14}\z/, message: 'must be E.164 format, e.g. +17241134455', allow_blank: true } before_save :clean_input # before_validation :associate_sensors before_destroy :destroy_all_collaborations include Timeable::InstanceMethods include Measurable::InstanceMethods extend Measurable::ClassMethods include Graphable::InstanceMethods include Regulatable::InstanceMethods extend Regulatable::ClassMethods include Permissionable::InstanceMethods include Messageable::InstanceMethods PERMISSIONS = { super_user: 0, team_member: 10, admin: 25, advocate: 50, user: 100 }.freeze METRICS = [:min, :max, :avg].freeze CYCLES = [:day, :night].freeze MEASUREMENTS = [:temp, :outdoor_temp].freeze DEMO_ACCOUNT_EMAILS = [ 'mbierut@heatseeknyc.com', 'bfried@heatseeknyc.com', 'dhuttenlocher@heatseeknyc.com', 'mkennedy@heatseeknyc.com', 'kkimball@heatseeknyc.com', 'mwiley@heatseeknyc.com', 'dwinshel@heatseeknyc.com', 'kjenkins@heatseeknyc.com', 'enelson@heatseeknyc.com', 'lbailey@heatseeknyc.com', 'csanders@heatseeknyc.com', 'jperry@heatseeknyc.com', 'rwalker@heatseeknyc.com', 'jwilliams@heatseeknyc.com', 'aanderson@heatseeknyc.com', 'bjackson@heatseeknyc.com', 'nparker@heatseeknyc.com', 'cstewart@heatseeknyc.com', 'ahoward@heatseeknyc.com', 'fmurphy@heatseeknyc.com', 'srodriguez@heatseeknyc.com', 'jgriffin@heatseeknyc.com', 'sbryant@heatseeknyc.com', 'abell@heatseeknyc.com', 'cgonzalez@heatseeknyc.com', 'rgray@heatseeknyc.com', 'speterson@heatseeknyc.com', 'sjones@heatseeknyc.com', 'jhenderson@heatseeknyc.com', 'nlong@heatseeknyc.com', 'chernandez@heatseeknyc.com', 'dmorgan@heatseeknyc.com', 'demo-lawyer@heatseeknyc.com' ].freeze define_measureable_methods(METRICS, CYCLES, MEASUREMENTS) def self.new_with_building(params) set_location = params.delete(:set_location_data) user = self.new params building_params = { street_address: user.address, zip_code: user.zip_code } building = Building.find_by building_params unless building building = Building.new building_params building.set_location_data if set_location == 'true' end user.building = building user end def search(search) search_arr = search.downcase.split first_term = search_arr[0] second_term = search_arr[1] || search_arr[0] result = User.fuzzy_search(first_term, second_term).except_user_id(id).tenants_only.where.not(id: collaborators.pluck(:id)) is_demo_user? ? result.demo_users : result end def role PERMISSIONS.invert[permissions] end def self.tenants_only where(permissions: 100) end def self.judges last_names = [ "Bierut", "Fried", "Huttenlocher", "Kennedy", "Kimball", "Wiley", "Winshel" ] demo_users.where(last_name: last_names) end def self.fuzzy_search(first_term, second_term) where([ 'search_first_name LIKE ? OR search_last_name LIKE ?', "%#{first_term}%", "%#{second_term}%" ]) end def self.except_user_id(user_id) where.not(id: user_id) end # TODO: eliminate this method and use is_demo_user? instance method instead def self.account_demo_user?(user_id) DEMO_ACCOUNT_EMAILS.include?(User.find(user_id).email) end def self.create_demo_lawyer User.create( :first_name => "Demo Lawyer", :last_name => "Account", :address => "100 Fake St", :zip_code => "10004", :email => 'demo-lawyer@heatseeknyc.com', :password => '33west26', :permissions => 50 ) end def self.assign_demo_tenants_to(demo_lawyer) demo_tenants = demo_users.tenants_only.sample(5) demo_tenants.each do |demo_tenant| demo_lawyer.collaborators << demo_tenant end end def self.demo_lawyer demo_lawyer ||= find_by(first_name: 'Demo Lawyer') if demo_lawyer.nil? demo_lawyer = create_demo_lawyer assign_demo_tenants_to(demo_lawyer) end return demo_lawyer end def associate_sensors sensors.clear string = sensor_codes_string || "" string.upcase.delete(" ").split(",").each do |nick_name| sensor = Sensor.find_by(nick_name: nick_name) sensors << sensor if sensor end end def sensor_codes sensors.map(&:nick_name).join(", ").upcase end def twine_name=(twine_name) return nil if twine_name == "" twine_name = twine_name.strip temp_twine = Twine.find_by(:name => twine_name) temp_twine.reload_user update(twine: temp_twine) end def is_demo_user? DEMO_ACCOUNT_EMAILS.include?(email) end def self.demo_users where(email: DEMO_ACCOUNT_EMAILS) end def twine_name twine.name unless twine.nil? end def has_collaboration?(collaboration_id) !find_collaboration(collaboration_id).empty? end def find_collaboration(collaboration_id) collaborations.where(id: collaboration_id) end def clean_input strip_fields create_search_names end def add_to_get_response auth_token = "api-key #{ENV['GET_RESPONSE_API_KEY']}" response = HTTParty.post("https://api.getresponse.com/v3/contacts", headers: { "Content-Type": "application/json", "X-Auth-Token": auth_token }, body: { name: "#{self.first_name} #{self.last_name}", email: self.email, campaign: { campaignId: ENV['GET_RESPONSE_LIST_TOKEN'] }, customFieldValues: [ { customFieldId: "pMnvrJ", value: [self.first_name] }, { customFieldId: "pMKFRN", value: [self.last_name] }, ] }.to_json) end def strip_fields self.first_name = self.first_name.try(:strip) || self.first_name self.last_name = self.last_name.try(:strip) || self.last_name self.address = self.address.try(:strip) || self.address self.email = self.email.try(:strip) || self.email self.phone_number = self.phone_number.try(:strip) || self.phone_number self.zip_code = self.zip_code.try(:strip) || self.zip_code self.permissions = self.permissions.try(:strip) || self.permissions self.apartment = self.apartment.try(:strip) || self.apartment self.sms_alert_number = self.sms_alert_number.try(:strip) || self.sms_alert_number self.sensor_codes_string = self.sensor_codes_string.try(:strip) || self.sensor_codes_string end def create_search_names self.search_first_name = first_name.downcase self.search_last_name = last_name.downcase end def live_readings readings.order(created_at: :desc).limit(50).sort_by do |r| r.violation = true r.created_at end end def current_temp @current_temp ||= self.readings.order(:created_at => :desc, :id => :desc).limit(1).first.try :temp end def current_temp_string current_temp ? "#{current_temp}ยฐ" : "N/A" end def current_temp_is_severe current_temp ? current_temp <= 60 : false end def has_readings? !readings.empty? end def destroy_all_collaborations Collaboration.where("user_id = ? OR collaborator_id = ?", id, id).destroy_all end def get_latest_readings(count, offset) r = readings.order(created_at: :desc).offset(offset).first(count) puts r.first.created_at puts r.last.created_at r end def last_weeks_readings readings.where("created_at > ?", 7.days.ago).order(created_at: :asc) end def name "#{first_name} #{last_name}" end def name_and_email "#{last_name}, #{first_name} <#{email}>" end def self.published_addresses(date_range) joins(:readings).where(permissions: 100, dummy: [nil, false]). order(address: :asc).where(readings: { created_at: date_range }). pluck(:address, :zip_code).uniq end def sensor_codes_string_contains_only_valid_sensors return if sensor_codes == (sensor_codes_string || "").upcase errors.add :sensor_codes_string, "has an invalid sensor code" end def inspect return super unless ENV["ANONYMIZED_FOR_LIVESTREAM"] super. gsub(", first_name: \"#{first_name}\"", ""). gsub(", first_name: nil", ""). gsub(", last_name: \"#{last_name}\"", ""). gsub(", last_name: nil", ""). gsub(", search_first_name: \"#{search_first_name}\"", ""). gsub(", search_first_name: nil", ""). gsub(", search_last_name: \"#{search_last_name}\"", ""). gsub(", search_last_name: nil", ""). gsub(", email: \"#{email}\"", ""). gsub(", email: nil", ""). gsub(", apartment: \"#{apartment}\"", ""). gsub(", apartment: nil", ""). gsub(", phone_number: \"#{phone_number}\"", ""). gsub(", phone_number: nil", "") end def collaborations_with_violations recent_violations = Reading .where("readings.created_at > ?", 7.days.ago) .where(violation: true).to_sql users_with_recent_violations = User.select("users.id, COUNT(readings.id) as violations_count") .joins("LEFT OUTER JOIN (#{recent_violations}) AS readings ON readings.user_id = users.id") .group("users.id").to_sql @collaborations_with_violations ||= begin collaborations .joins("INNER JOIN (#{users_with_recent_violations}) users ON users.id = collaborations.collaborator_id") .select("collaborations.*, users.violations_count AS violations_count") .order("violations_count desc") .includes(:collaborator) end end def get_oldest_reading_date(format) if last_reading = self.readings.order(:created_at, :id).limit(1).first last_reading.created_at.strftime(format) end end def first_reading_this_year(format) if last_reading = self.readings.this_year.order(:created_at, :id).limit(1).first last_reading.created_at.strftime(format) end end def get_newest_reading_date(format) if newest_reading = self.readings.order(:created_at => :desc, :id => :desc).limit(1).first newest_reading.created_at.strftime(format) end end def get_collaboration_with_user(user) self.collaborations.find_by(collaborator: user) end def available_pdf_reports ActiveRecord::Base.connection.execute( <<-SQL SELECT CASE WHEN (EXTRACT(month from created_at))::int > 9 THEN extract(year from created_at)::int + 1 ELSE extract(year from created_at)::int END as date_part FROM readings WHERE user_id = #{id} GROUP BY CASE WHEN (EXTRACT(month from created_at))::int > 9 THEN extract(year from created_at)::int + 1 ELSE extract(year from created_at)::int END; SQL ).to_a.map { |r| r["date_part"].to_i }.map do |year| [year-1, year] end end def generate_password_reset_token raw_token = set_reset_password_token # this is protected, so we have to create another method raw_token end end
class Function < ActiveRecord::Base #ไปฅไธ‹ไธบๅปบ็ซ‹ๅŠŸ่ƒฝ็‚น->่ง’่‰ฒ->็”จๆˆท็š„ๅคš้‡ m:n ๅ…ณ่”ๅ…ณ็ณป has_many :role_functions has_many :roles , through: :role_functions, inverse_of: :functions has_many :role_users, through: :roles has_many :users , through: :role_users default_scope {order(:controller, :action)} end
Rails.application.routes.draw do root 'questions#index' devise_for :users resources :questions resources :answers, only: [:new, :create, :index, :show, :update] end
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] before_action :require_login, except: [:new, :create] before_action :require_correct_user, only: [:show, :edit, :update, :destroy] def index if current_user redirect_to "/users/#{current_user.id}" else redirect_to "/sessions/new" end end def show @seeks = Seek.all # if current_user # render 'show' # else # redirect_to '/sessions/new' # end end def new user = current_user if current_user redirect_to "/users/#{user.id}" else render 'new' end end def create user = User.new(get_user_info) if user.valid? user.save session[:user_id] = user.id redirect_to "/users/#{user.id}", notice: "You have successfully registered!" else redirect_to :back , alert: user.errors.full_messages end end def edit # if current_user # render 'edit' # else # redirect_to '/sessions/new' # end end def update user = User.update(@user.id, get_user_info) # user = User.update(current_user.id, get_user_info) # updated = current_user.update(get_user_info) if user.valid? redirect_to "/users/#{current_user.id}", notice: "You have successfully updated your profile!" else redirect_to :back, alert: user.errors.full_messages end end def destroy user = @user.destroy if user session[:user_id] = nil redirect_to "/sessions/new", notice: "You have successfully deleted the user!" else redirect_to :back, alert: "Somethinfg went wrong while deleiting!" end end private def set_user @user = User.find(params[:id]) # @user = current_user end def get_user_info # params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation) params.require(:user).permit(:name, :email, :password, :password_confirmation) end end
#!/usr/bin/env ruby -S rspec require 'spec_helper' require 'semantic_puppet' require 'puppet/pops/lookup/context' require 'yaml' require 'fileutils' puppetver = SemanticPuppet::Version.parse(Puppet.version) requiredver = SemanticPuppet::Version.parse("4.10.0") describe 'lookup' do # Generate a fake module with dummy data for lookup(). profile_yaml = { 'version' => '2.0.0', 'profiles' => { '00_profile_test' => { 'controls' => { '00_control1' => true, }, }, '00_profile_with_check_reference' => { 'checks' => { '00_check2' => true, }, }, }, }.to_yaml ces_yaml = { 'version' => '2.0.0', 'ce' => { '00_ce1' => { 'controls' => { '00_control1' => true, }, }, }, }.to_yaml checks_yaml = { 'version' => '2.0.0', 'checks' => { '00_check1' => { 'type' => 'puppet-class-parameter', 'settings' => { 'parameter' => 'test_module_00::test_param', 'value' => 'a string', }, 'ces' => [ '00_ce1', ], }, '00_check2' => { 'type' => 'puppet-class-parameter', 'settings' => { 'parameter' => 'test_module_00::test_param2', 'value' => 'another string', }, 'ces' => [ '00_ce1', ], }, }, }.to_yaml fixtures = File.expand_path('../../fixtures', __dir__) compliance_dir = File.join(fixtures, 'modules', 'test_module_00', 'SIMP', 'compliance_profiles') FileUtils.mkdir_p(compliance_dir) File.open(File.join(compliance_dir, 'profile.yaml'), 'w') do |fh| fh.puts profile_yaml end File.open(File.join(compliance_dir, 'ces.yaml'), 'w') do |fh| fh.puts ces_yaml end File.open(File.join(compliance_dir, 'checks.yaml'), 'w') do |fh| fh.puts checks_yaml end on_supported_os.each do |os, os_facts| context "on #{os} with compliance_markup::enforcement and a non-existent profile" do let(:facts) do os_facts.merge('target_compliance_profile' => 'not_a_profile') end let(:hieradata) { 'compliance-engine' } it { is_expected.to run.with_params('test_module_00::test_param').and_raise_error(Puppet::DataBinding::LookupError, "Function lookup() did not find a value for the name 'test_module_00::test_param'") } end context "on #{os} with compliance_markup::enforcement and an existing profile" do let(:facts) do os_facts.merge('target_compliance_profile' => '00_profile_test') end let(:hieradata) { 'compliance-engine' } # Test unconfined data. it { is_expected.to run.with_params('test_module_00::test_param').and_return('a string') } it { is_expected.to run.with_params('test_module_00::test_param2').and_return('another string') } end context "on #{os} with compliance_markup::enforcement and a profile directly referencing a check" do let(:facts) do os_facts.merge('target_compliance_profile' => '00_profile_with_check_reference') end let(:hieradata) { 'compliance-engine' } # Test unconfined data. it { is_expected.to run.with_params('test_module_00::test_param').and_raise_error(Puppet::DataBinding::LookupError, "Function lookup() did not find a value for the name 'test_module_00::test_param'") } it { is_expected.to run.with_params('test_module_00::test_param2').and_return('another string') } end end end
class CreateTrips < ActiveRecord::Migration def change create_table :trips do |t| t.string :title t.text :description t.float :start_latitude t.float :start_longitude t.float :end_latitude t.float :end_longitude t.timestamp :start_time t.timestamp :end_time t.integer :owner_id t.integer :contributors_limit t.timestamps null: false end end end
require 'spec_helper' describe Elaios, integration: true do before(:each) do @port = random_port end around(:each) do |example| Timeout::timeout(5) do example.run end end it 'works when used with a threaded server' do done = false requests = [] responses = [] # TCP server. server = TCPServer.open(@port) Thread.new do loop do break if done # New incoming socket connection. Thread.fork(server.accept) do |socket| # We need a new Elaios instance for every incoming connection. elaios_responder = Elaios::Responder.new # Create a server handler. elaios_responder.ping do |data| requests << data res(data['method'], data['id'], { foo: 'bar' }) end # Incoming socket data. Thread.new do loop do break if done result = socket.gets.chomp elaios_responder << result end end # Outgoing socket data. loop do break if done result = elaios_responder.pop socket.puts(result) if result sleep(Float::MIN) end end end end # TCP client. socket = TCPSocket.open('127.0.0.1', @port) elaios_requester = Elaios::Requester.new # Incoming socket data. Thread.new do loop do break if done result = socket.gets.chomp elaios_requester << result end end # Outgoing socket data. Thread.new do loop do break if done result = elaios_requester.pop socket.puts(result) if result end end # Try making some service calls. elaios_requester.ping('foo') elaios_requester.ping('foo') do |response| responses << response done = true end # Wait for everything to finish. sleep Float::MIN until done # Inspect the requests the server received. expect(requests.length).to eq(2) request_1 = requests.first expect(request_1['id']).to be_nil expect(request_1['method']).to eq('ping') expect(request_1['params']).to eq('foo') request_2 = requests.last expect(request_2['id']).to_not be_nil expect(request_2['method']).to eq('ping') expect(request_2['params']).to eq('foo') # Inspect the responses the client received. expect(responses.length).to eq(1) response = responses.last expect(response['id']).to_not be_nil expect(response['method']).to eq('ping') expect(response['result']).to eq({ 'foo' => 'bar' }) end end
class Hadupils::RunnersTest < Test::Unit::TestCase include Hadupils::Extensions::Runners context Hadupils::Runners::Base do setup do @runner = Hadupils::Runners::Base.new(@params = mock()) end should 'expose initialization params as attr' do assert_equal @params, @runner.params end context 'wait!' do setup do @command = [mock(), mock(), mock()] # This will ensure that $? is non-nil system(RbConfig.ruby, '-v') end context 'with semi-modern ruby' do setup do @runner.expects(:command).with.returns(@command) end should 'assemble system call via command method' do $?.stubs(:exitstatus).with.returns(mock()) last_status = $? Shell.stubs(:command).with(*@command).returns([nil, nil, last_status]) @runner.wait! end should 'return 255 when system returns nil' do Shell.stubs(:command).returns([nil, nil, nil]) assert_equal [nil, 255], @runner.wait! end should 'return Process::Status#exitstatus when non-nil system result' do $?.stubs(:exitstatus).with.returns(status = mock()) last_status = $? Shell.stubs(:command).returns([nil, nil, last_status]) assert_equal [nil, status], @runner.wait! end end context 'with ruby pre 1.9' do setup do @orig_ruby_version = ::RUBY_VERSION ::RUBY_VERSION = '1.8.7' end teardown do ::RUBY_VERSION = @orig_ruby_version end should 'handle command without env hash normally' do @runner.expects(:command).with.returns(@command) Open3.expects(:popen3).with(*@command) $?.stubs(:exitstatus).with.returns(mock) @runner.wait! end should 'handle environment hash specially and restore env' do # A defined environment variable to play with. var = ::ENV.keys.find {|k| ENV[k].strip.length > 0} orig = ::ENV[var] to_be_removed = ::ENV.keys.sort[-1] + 'X' removal_val = mock.to_s replacement = "#{orig}-#{mock.to_s}" @runner.expects(:command).with.returns([{var => replacement, to_be_removed => removal_val}] + @command) $?.stubs(:exitstatus).with.returns(mock) begin # Environment variable is overridden during system call last_status = $? matcher = Shell.stubs(:command).returns([nil, nil, last_status]).with do |*args| args == @command and ::ENV[var] == replacement and ::ENV[to_be_removed] == removal_val end matcher.returns true @runner.wait! # But is restored afterward assert_equal orig, ::ENV[var] assert_equal false, ::ENV.has_key?(to_be_removed) ensure ::ENV[var] = orig end end end end end context Hadupils::Runners::Hadoop do setup do @klass = Hadupils::Runners::Hadoop end should 'be a runner' do assert_kind_of Hadupils::Runners::Base, @klass.new([]) end should 'use $HADOOP_HOME/bin/hadoop as the base runner' do ENV.expects(:[]).with('HADOOP_HOME').returns(home = mock().to_s) assert_equal ::File.join(home, 'bin', 'hadoop'), @klass.base_runner end context '#command' do setup do @klass.stubs(:base_runner).returns(@hadoop_path = mock().to_s + '-hadoop') end should 'provide invocation for bare hadoop if given empty parameters' do assert_equal [@hadoop_path], @klass.new([]).command end should 'provide invocation for hadoop with all given parameters' do params = [mock().to_s, mock().to_s, mock().to_s, mock().to_s] assert_equal [@hadoop_path] + params, @klass.new(params).command end should 'provide args for hadoop with :hadoop_opts on supporting params' do p1 = mock() p1.expects(:hadoop_opts).with.returns(p1_opts = ['-conf', mock().to_s]) p2 = mock() p2.expects(:hadoop_opts).with.returns(p2_opts = ['-conf', mock().to_s]) s1 = mock().to_s s2 = mock().to_s assert_equal [@hadoop_path, s1] + p1_opts + p2_opts + [s2], @klass.new([s1, p1, p2, s2]).command end end end context Hadupils::Runners::Hive do setup do @klass = Hadupils::Runners::Hive end should 'be a runner' do assert_kind_of Hadupils::Runners::Base, @klass.new([]) end should 'use $HIVE_HOME/bin/hive as the base runner' do ENV.expects(:[]).with('HIVE_HOME').returns(home = mock().to_s) assert_equal ::File.join(home, 'bin', 'hive'), @klass.base_runner end context '#command' do setup do @klass.stubs(:base_runner).returns(@hive_path = mock().to_s + '-hive') end should 'provide invocation for bare hive if given empty parameters' do assert_equal [{}, @hive_path], @klass.new([]).command end should 'provide invocation with aux jars and bare hive given empty params but aux jars path' do ENV.stubs(:[]=).with('HIVE_AUX_JARS_PATH').returns(nil) assert_equal [{'HIVE_AUX_JARS_PATH' => 'foo'}, @hive_path], @klass.new([], 'foo').command end should 'provide invocation with merged aux jars given otherwise bare stuff' do ::ENV.stubs(:[]).with('HIVE_AUX_JARS_PATH').returns(orig = mock.to_s) additional = mock.to_s assert_equal [{'HIVE_AUX_JARS_PATH' => "#{additional},#{orig}"}, @hive_path], @klass.new([], additional).command end should 'provide invocation for hive with all given parameters' do params = [mock().to_s, mock().to_s, mock().to_s, mock().to_s] assert_equal [{}, @hive_path] + params, @klass.new(params).command end should 'provide args for hive with :hive_opts on supporting params' do p1 = mock() p1.expects(:hive_opts).with.returns(p1_opts = ['-i', mock().to_s]) p2 = mock() p2.expects(:hive_opts).with.returns(p2_opts = ['-i', mock().to_s]) s1 = mock().to_s s2 = mock().to_s assert_equal [{}, @hive_path, s1] + p1_opts + [s2] + p2_opts, @klass.new([s1, p1, s2, p2]).command end end end end
class Passport < ActiveRecord::Base belongs_to :company validates :title, :company, presence: true has_attached_file :file #validates_attachment_presence :file validates_attachment_size :file, less_than: 2.megabytes validates_attachment :file, content_type: { content_type: "application/pdf" } end
class Comment < ApplicationRecord belongs_to :user belongs_to :gossip validates :content, presence:true end
module Susanoo module Assets class HelpAttachmentFile < Base attr_accessor :help_content_id has_attached_file :data, url: ':help_content_data/:basename.:extension', path: ':rails_root/files/help/:rails_env/:help_content_id/:basename.:extension' Paperclip.interpolates :help_content_id do |attachment, style| attachment.instance.help_content_id end # # ใƒšใƒผใ‚ธใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใซใ‚ใ‚‹ใƒ•ใ‚กใ‚คใƒซใ‚’ๆคœ็ดขใ™ใ‚‹ # def self.find(params = {}) files = Dir.glob(Rails.root.join('files', 'help', Rails.env.to_s, params[:id], params[:data_file_name])).sort asset = new asset.help_content_id = params[:id] asset.data = File.open(files.first) return asset end def self.all(params = {}) assets = [] files = Dir.glob(Rails.root.join('files', 'help', Rails.env.to_s, params[:help_content_id], '*')).sort files.grep(regex[:attachment_file]).each do |i| asset = new asset.help_content_id = params[:help_content_id] asset.data = File.open(i) assets << asset end assets end def initialize(params = {}) @messages = [] self.help_content_id = params[:help_content_id] end def url_thumb @url_thumb ||= Ckeditor::Utils.filethumb(filename) end # #=== ๆทปไป˜ใƒ•ใ‚กใ‚คใƒซใ‹ใฉใ†ใ‹ใ‚’่ฟ”ใ™ # def attachment_files? extname =~ regex[:attachment_file] end def url "/susanoo/admin/help_content_assets/#{help_content_id}?data_file_name=#{data_file_name}" end def url_content url end end end end
class DropEmployeeMachinesTable < ActiveRecord::Migration def change drop_table :employee_machines end end
class Santa attr_reader :ethnicity attr_accessor :gender, :age def initialize(gender, ethnicity) p "Initializing Santa instance ..." @gender = gender @ethnicity = ethnicity @reindeer_ranking = reindeer_ranking end def speak puts "Ho, ho, ho! Haaaappy holidays!" end def eat_milk_and_cookies(cookie_type) p "That was a good #{cookie_type}!" end def reindeer_ranking ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"] end def celebrate_birthday(age) @age = age + 1 end def get_mad_at(reindeer_name) #delete the reindeer's name in the reindeer ranking array #and add it to the end of the reindeer ranking array @reindeer_ranking.delete(reindeer_name) @reindeer_ranking << reindeer_name end #def change_gender(new_gender) # @gender = new_gender #end end #SANTA PROGRAM example_genders = ["agender", "female", "bigender", "male", "female", "gender fluid", "N/A"] example_ethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A"] new_santa_instances = [] 25.times do |i| new_santa_instances << Santa.new(example_genders.sample[i], example_ethnicities.sample[i]) new_santa_instances[i].age = rand(0..140) end #driver code p new_santa_instances p new_santa_instances[20].age #p joe = Santa.new("Irish", "undecided") #joe.age = 23 #p joe =begin OLD DRIVER CODE: joe = Santa.new("male", "African") michael = Santa.new("male", "Irish") joe.speak joe.eat_milk_and_cookies("snickerdoodle") p joe.age p joe.celebrate_birthday(3) p joe.reindeer_ranking p joe.get_mad_at("Prancer") p joe.gender p joe.change_gender("female") p joe.age p joe.ethnicity p joe = Santa.new("male", "African") p joe.ethnicity p joe.gender = "undecided" p joe.gender p joe.age =end #DIFFERENT WAYS TO INITIALIZE SANTA INSTANCES: santas = [] santas << Santa.new("agender", "black") santas << Santa.new("female", "Latino") santas << Santa.new("bigender", "white") santas << Santa.new("male", "Japanese") santas << Santa.new("female", "prefer not to say") santas << Santa.new("gender fluid", "Mystical Creature (unicorn)") santas << Santa.new("N/A", "N/A") santas = [] example_genders = ["agender", "female", "bigender", "male", "female", "gender fluid", "N/A"] example_ethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A"] example_genders.length.times do |i| santas << Santa.new(example_genders[i], example_ethnicities[i]) end i = 0 santas = [] example_genders = ["agender", "female", "bigender", "male", "female", "gender fluid", "N/A"] example_ethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A"] while santas.length <= example_genders.length santas << Santa.new(example_genders[i], example_ethnicities[i]) i+=1 end p santas gender = ["agender", "female", "bigender", "male", "female", "gender fluid", "N/A"] ethnicity = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A"] santas = [] santas << Santa.new(gender[0], ethnicity[0]) santas << Santa.new(gender[1], ethnicity[1]) santas << Santa.new(gender[2], ethnicity[2]) santas << Santa.new(gender[3], ethnicity[3]) santas << Santa.new(gender[4], ethnicity[4]) santas << Santa.new(gender[5], ethnicity[5]) santas << Santa.new(gender[6], ethnicity[6]) santas << Santa.new(gender[7], ethnicity[7]) p santas
class AddAddressIdToDamage < ActiveRecord::Migration[5.2] def change add_column :damages, :address_id, :integer end end
require 'test/unit' module Given def self.assertion_failed_exception Test::Unit::AssertionFailedError end module TestUnit module Adapter def given_failure(message, code=nil) if code message = "\n#{code.file_line} #{message}\n" end raise Test::Unit::AssertionFailedError.new(message) end def given_assert(clause, code) _wrap_assertion do ok = code.run(self) if ! ok given_failure("#{clause} Condition Failed", code) end end end end end end
require "rake" require "pathname" desc "Install the dotfiles" task :default do FileLinker.link_files puts "\n xoxo\n" end class FileLinker DOTFILES_PATH = Pathname.new(Dir.pwd) LINK_PATH = DOTFILES_PATH.join("link") HOME_PATH = Pathname.new(ENV["HOME"]) attr_reader :source_path def initialize(source_path) @source_path = source_path end def self.link_files files = Dir.glob(LINK_PATH.join("*"), File::FNM_DOTMATCH).reject{ |e| e.end_with?("/.", "/..") } files.each do |file| new(file).handle end end def handle if exist? if identical? puts "identical #{source_path}" else print "overwrite #{source_path}? [ynq] " case $stdin.gets.chomp when 'y' replace_file when 'q' exit else puts "skipping #{file}" end end else link_file end end private def identical? File.identical?(source_path, target_path) end def exist? File.exist?(target_path) end def target_path HOME_PATH.join(file_name) end def file_name File.basename(source_path) end def replace_file FileUtils.rm(target_path) link_file end def link_file puts "linking #{source_path}" FileUtils.ln_s source_path, target_path, force: true end end
require 'nokogiri' require 'open-uri' class Parser private def parse(arg = nil) Nokogiri::HTML(URI.open(@url)) if arg.nil? rescue OpenURI::HTTPError => e raise e unless e.message == 'Error 404 Not Found' end end
class Ship attr_accessor :name, :type, :booty @@ships = [] def initialize(attributes) attributes.each do |k, v| send("#{k}=", v) end self.class.all << self end def self.all @@ships end def self.clear all.clear end end
class ClientsController < ApplicationController include TenantScopedController load_and_authorize_resource before_action :set_model def upload_staff @upload_model = ClientStaffList.new end def do_upload_staff d = SimpleXlsxReader.open(params['user']['file'].open) hash = d.to_hash columns = [ 'Employee_Code', 'FName', 'LName', 'Job_Title', 'Phone', 'Email_Address', 'CLS Auth', 'Employment_Status', 'Cost_Group', 'Cost_Center', 'Termination_Date', 'ModifiedDate' ] hash.each do |sheet_name,rows| rows.each_with_index do |row,i| if i == 0 if columns.each_with_index.select{|c,i| row[i] != c}.any? raise 'Please upload a spreadsheet with the proper header formatting' end else employee_code = row[0] first_name = row[1] last_name = row[2] job_title = row[3] phone = row[4] email = row[5] is_foreman = row[6].try(:strip) employment_status = row[7] cost_group = row[8] cost_center = row[9] termination_date = row[10] modified_date = row[11] # Foremen must have an email address raise "Each foreman has to have an email address - #{first_name} / #{last_name}" if is_foreman == "Yes" && email.blank? # Make up an email if email.blank? email = "#{first_name.gsub(/\s+/, "")}.#{last_name.gsub(/\s+/, "")}@#{@model.domain_name}" end # See if we can find the user user = User.find_by_email(email) if user.nil? random_password = SecureRandom.uuid user = User.new user.email = email.try(:strip) user.first = first_name.try(:strip) user.last = last_name.try(:strip) user.password = random_password user.password_confirmation = random_password user.skip_confirmation! end user.update({ first: first_name.try(:strip), last: last_name.try(:strip), client: @model, is_foreman: is_foreman == "Yes", employee_id: employee_code.try(:strip), phone: phone.try(:strip), job_title: job_title.try(:strip), employment_status: employment_status.try(:strip), cost_group: cost_group.try(:strip), cost_center: cost_center.try(:strip), termination_date: termination_date.try(:strip), modified_date: modified_date.try(:strip) }) end end end return redirect_to tenant_client_path(@model.tenant, @model) end def users @q = @model.users.order(last: :asc).ransack(params[:q]) @models = @q.result(distinct: true).page(params[:page]) end def index @q = Client.ransack(params[:q]) @models = @q.result(distinct: true).includes(:bookings).page(params[:page]) end def new @model = Client.new({tenant_id: params[:tenant_id]}) end def edit; end def create @model = Client.new(client_params) @model.tenant_id = params[:tenant_id] if @model.save redirect_to [@model.tenant, @model] else render "new" end end def update if @model.update(client_params) redirect_to [@model.tenant, @model] else render "edit" end end def show end private def set_model @model = Client.where(id: params[:id]).first if params[:id] end def client_params params.require(:client).permit(:name, :tenant_id, :billing_fee, :domain_name, :confirmation_email) end end
require 'spec_helper' describe Url do describe ".scrape_matches" do it "returns the page title" do report = Report.create(:name => "Test Report", :useragent => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36") url = Url.create(:report_id => report.id, :uri => "www.bbc.co.uk/news/") VCR.use_cassette('www.bbc.co.uk/news/') do url.scrape_matches end expect url.title.should eql "BBC News - Home" end it "returns the meta description" do report = Report.create(:name => "Test Report", :useragent => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36") url = Url.create(:report_id => report.id, :uri => "www.bbc.co.uk/news/") VCR.use_cassette('www.bbc.co.uk/news/') do url.scrape_matches end expect url.description.should eql "Visit BBC News for up-to-the-minute news, breaking news, video, audio and feature stories. BBC News provides trusted World and UK news as well as local and regional perspectives. Also entertainment, business, science, technology and health news." end it "returns the canonical tag" do report = Report.create(:name => "Test Report", :useragent => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36") url = Url.create(:report_id => report.id, :uri => "www.bbc.co.uk/news/") VCR.use_cassette('www.bbc.co.uk/news/') do url.scrape_matches end expect url.canonical.should eql "http://www.bbc.co.uk/news/" end it "returns the first matching twitter URL" do report = Report.create(:name => "Test Report", :useragent => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36") url = Url.create(:report_id => report.id, :uri => "www.propellernet.co.uk") VCR.use_cassette('www.propellernet.co.uk') do url.scrape_matches end expect url.twitter.should eql "https://twitter.com/Propellernet" end it "follows redirections and scrapes final page" do report = Report.create(:name => "Test Report", :useragent => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36") url = Url.create(:report_id => report.id, :uri => "news.bbc.co.uk") VCR.use_cassette('news.bbc.co.uk') do url.scrape_matches end expect url.title.should eql "BBC News - Home" end it "should set a scrape status of finished on successful completion" do report = Report.create(:name => "Test Report", :useragent => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36") url = Url.create(:report_id => report.id, :uri => "www.bbc.co.uk/news/") VCR.use_cassette('www.bbc.co.uk/news/') do url.scrape_matches end expect url.scrape_status.should eql "finished" end it "returns the HTTP code 301 when a permanent redirect exists" do pending end it "returns the HTTP code 200 when no redirection exists" do pending end end describe ".normalise" do it "remove http:// from the URL" do url = Url.normalise("http://www.test.com") expect url.should eql "www.test.com" end it "remove https:// from the URL" do url = Url.normalise("https://www.test.com") expect url.should eql "www.test.com" end it "remove white space either side of the URL" do url = Url.normalise(" http://www.test.com ") expect url.should eql "www.test.com" end it "should not alter an already normalised URL" do url = Url.normalise("www.test.com ") expect url.should eql "www.test.com" end end end
require 'rubygems/package' require 'zlib' require 'json' require 'nokogiri' require 'distro-package.rb' module PackageUpdater class Updater def self.friendly_name name.gsub(/^PackageUpdater::/,"").gsub("::","_").downcase.to_sym end def self.log Log end def self.http_agent agent = Mechanize.new agent.user_agent = 'NixPkgs software update checker' return agent end def self.version_cleanup!(version) 10.times do # _all was added for p7zip # add -stable? version.gsub!(/\.gz|\.Z|\.bz2?|\.tbz|\.tbz2|\.lzma|\.lz|\.zip|\.xz|[-\.]tar$/, "") version.gsub!(/\.tgz|\.iso|\.dfsg|\.7z|\.gem|\.full|[-_\.]?src|[-_\.]?[sS]ources?$/, "") version.gsub!(/\.run|\.otf|-dist|\.deb|\.rpm|[-_]linux|-release|-bin|\.el$/, "") version.gsub!(/[-_\.]i386|-i686|[-\.]orig|\.rpm|\.jar|_all$/, "") end end def self.parse_tarball_name(tarball) package_name = file_version = nil if tarball =~ /^(.+?)[-_][vV]?([^A-Za-z].*)$/ package_name = $1 file_version = $2 elsif tarball =~ /^([a-zA-Z]+?)\.?(\d[^A-Za-z].*)$/ package_name = $1 file_version = $2 else log.info "failed to parse tarball #{tarball}" return nil end version_cleanup!(file_version) return [ package_name, file_version ] end def self.parse_tarball_from_url(url) return parse_tarball_name($1) if url =~ %r{/([^/]*)$} log.info "Failed to parse url #{url}" return [nil, nil] end # FIXME: add support for X.Y.Z[-_]?(a|b|beta|c|r|rc|pre)?\d* # FIXME: add support for the previous case when followed by [-_]?p\d* , # which usually mentions date, but may be a revision. the easiest way is to detect date by length and some restricitons # find out what is the order of preference of such packages. # FIXME: support for abcd - > a.bc.d versioning scheme. compare package and tarball versions to detect # FIXME: support date-based versioning: seems to be automatic as long as previous case is handled correctly # Returns true if the version format can be parsed and compared against another def self.usable_version?(version) return (tokenize_version(version) != nil) end def self.tokenize_version(v) return nil if v.start_with?('.') or v.end_with?('.') result = [] vcp = v.downcase.dup while vcp.length>0 found = vcp.sub!(/\A(\d+|[a-zA-Z]+)\.?/) { result << $1; "" } return nil unless found end result.each do |token| return nil unless token =~ /^(\d+)$/ or ['alpha','beta','pre','rc'].include?(token) or ('a'..'z').include?(token) end result.map! do |token| token = 'a' if token == 'alpha' token = 'b' if token == 'beta' token = 'p' if token == 'pre' token = 'r' if token == 'rc' #puts "<#{token}>" if ('a'..'z').include? token -100 + token.ord - 'a'.ord elsif token =~ /^(\d+)$/ (token ? token.to_i : -1) else return nil end end result.fill(-1,result.length, 10-result.length) return result end def self.is_newer?(v1, v2) t_v1 = tokenize_version(v1) t_v2 = tokenize_version(v2) return( (t_v1 <=> t_v2) >0 ) end # check that package and tarball versions match def self.versions_match?(pkg) (package_name, file_version) = parse_tarball_from_url(pkg.url) if file_version and package_name and true # test only v1 = file_version.downcase # removes haskell suffix, gimp plugin suffix and FIXME: linux version # FIXME: linux version removal breaks a couple of matches v2 = pkg.version.downcase unless (v1 == v2) or (v1.gsub(/[-_]/,".") == v2) or (v1 == v2.gsub(".","")) log.info "version mismatch: #{package_name} #{file_version} #{pkg.url} #{pkg.name} #{pkg.version}" return false end return true else log.info "failed to parse tarball #{pkg.url} #{pkg.internal_name}" end return false end # returns an array of major, minor and fix versions from the available_versions array def self.new_versions(version, available_versions, package_name) t_pv = tokenize_version(version) return nil unless t_pv max_version_major = version max_version_minor = version max_version_fix = version available_versions.each do |v| t_v = tokenize_version(v) if t_v #check for and skip 345.gz == v3.4.5 versions for now if t_v[0]>9 and t_v[1] = -1 and t_pv[1] != -1 and t_v[0]>5*t_pv[0] log.info "found weird(too high) version of #{package_name} : #{v}. skipping" else max_version_major = v if (t_v[0] != t_pv[0]) and is_newer?(v, max_version_major) max_version_minor = v if (t_v[0] == t_pv[0]) and (t_v[1] != t_pv[1]) and is_newer?(v, max_version_minor) max_version_fix = v if (t_v[0] == t_pv[0]) and (t_v[1] == t_pv[1]) and (t_v[2] != t_pv[2]) and is_newer?(v, max_version_fix) end else log.info "can't parse update version candidate of #{package_name} : #{v}. skipping" end end return( (max_version_major != version ? [ max_version_major ] : []) + (max_version_minor != version ? [ max_version_minor ] : []) + (max_version_fix != version ? [ max_version_fix ] : []) ) end def self.new_tarball_versions(pkg, tarballs) (package_name, file_version) = parse_tarball_from_url(pkg.url) return nil if file_version.to_s.empty? or package_name.to_s.empty? return nil unless versions_match?(pkg) vlist = tarballs[package_name.downcase] return nil unless vlist return new_versions(pkg.version.downcase, vlist, package_name) end def self.tarballs_from_dir(dir, tarballs = {}) begin http_agent.get(dir).links.each do |l| next if l.href.end_with?('.asc', '.exe', '.dmg', '.sig', '.sha1', '.patch', '.patch.gz', '.patch.bz2', '.diff', '.diff.bz2', '.xdelta') (name, version) = parse_tarball_name(l.href) if name and version tarballs[name] = [] unless tarballs[name] tarballs[name] = tarballs[name] << version end end return tarballs rescue Mechanize::ResponseCodeError log.warn $! return {} end end def self.tarballs_from_dir_recursive(dir) tarballs = {} log.debug "#{dir}" http_agent.get(dir).links.each do |l| next if l.href == '..' or l.href == '../' if l.href =~ %r{^[^/]*/$} log.debug l.href tarballs = tarballs_from_dir(dir+l.href, tarballs) end end return tarballs end def self.newest_versions_of(pkg) v = newest_version_of(pkg) (v ? [v] : nil) end def self.find_tarball(pkg, version) return nil if pkg.url.to_s.empty? or version.to_s.empty? or pkg.version.to_s.empty? new_url = (pkg.url.include?(pkg.version) ? pkg.url.gsub(pkg.version, version) : nil ) return nil unless new_url bz_url = new_url.sub(/\.tar\.gz$/, ".tar.bz2") xz_url = bz_url.sub(/\.tar\.bz2$/, ".tar.xz") [ xz_url, bz_url, new_url ] end end class GentooDistfiles < Updater def self.covers?(pkg) return false if Repository::CPAN.covers?(pkg) or Repository::Pypi.covers?(pkg) or Repository::RubyGems.covers?(pkg) or Repository::Hackage.covers?(pkg) (package_name, file_version) = parse_tarball_from_url(pkg.url) return( package_name and file_version and distfiles[package_name] and usable_version?(pkg.version) and usable_version?(file_version) ) end def self.distfiles unless @distfiles @distfiles = {} files = http_agent.get('http://distfiles.gentoo.org/distfiles/').links.map(&:href) files.each do |tarball| (name, version) = parse_tarball_name(tarball) if name and name != "v" name = name.downcase version = version.downcase unless version.include? 'patch' or version.include? 'diff' @distfiles[name] = [] unless @distfiles[name] @distfiles[name] = @distfiles[name] << version end end end log.debug @distfiles.inspect end @distfiles end def self.newest_versions_of(pkg) return nil unless covers?(pkg) return new_tarball_versions(pkg, distfiles) end end class DirTraversal < Updater end class HomePage < Updater # try homepage from metadata # try dirtraversal-like fetching or parent dirs to see if they contain something # follow links like source/download/development/contribute end class VersionGuess < Updater end module Repository # FIXME: nixpkgs has lots of urls which don't use mirror and instead have direct links :( # handles packages hosted at SourceForge class SF < Updater def self.tarballs @tarballs ||= Hash.new do |h, sf_project| tarballs = Hash.new{|h,k| h[k] = Array.new } begin data = http_agent.get("http://sourceforge.net/projects/#{sf_project}/rss").body Nokogiri.XML(data).xpath('rss/channel/item/title').each do |v| next if v.inner_text.end_with?('.asc', '.exe', '.dmg', '.sig', '.sha1', '.patch', '.patch.gz', '.patch.bz2', '.diff', '.diff.bz2', '.xdelta') (name, version) = parse_tarball_from_url(v.inner_text) tarballs[name] << version if name and version end rescue Net::HTTPForbidden, Mechanize::ResponseCodeError end h[sf_project] = tarballs end end def self.covers?(pkg) pkg.url =~ %r{^mirror://sourceforge/(?:project/)?([^/]+).*?/([^/]+)$} and usable_version?(pkg.version) end def self.newest_versions_of(pkg) return nil unless pkg.url return nil unless %r{^mirror://sourceforge/(?:project/)?(?<sf_project>[^/]+).*?/([^/]+)$} =~ pkg.url return new_tarball_versions(pkg, tarballs[sf_project]) end end # handles Node.JS packages hosted at npmjs.org class NPMJS < Updater def self.metadata unless @metadata @metadata = Hash.new{|h, pkgname| h[pkgname] = JSON.parse(http_agent.get("http://registry.npmjs.org/#{pkgname}/").body) } end @metadata end def self.covers?(pkg) return( pkg.url and pkg.url.start_with?("http://registry.npmjs.org/") and usable_version?(pkg.version) ) end def self.newest_version_of(pkg) return nil unless pkg.url return nil unless %r{http://registry.npmjs.org/(?<pkgname>[^\/]*)/} =~ pkg.url new_ver = metadata[pkgname]["dist-tags"]["latest"] return nil unless usable_version?(new_ver) and usable_version?(pkg.version) return( is_newer?(new_ver, pkg.version) ? new_ver : nil ) end end # handles Perl packages hosted at mirror://cpan/ class CPAN < Updater def self.tarballs unless @tarballs @tarballs = Hash.new{|h,k| h[k] = Array.new } @locations = {} z = Zlib::GzipReader.new(StringIO.new(http_agent.get("http://www.cpan.org/indices/ls-lR.gz").body)) unzipped = z.read dirs = unzipped.split("\n\n") dirs.each do |dir| lines = dir.split("\n") next unless lines[0].include? '/authors/' #remove dir and total dir = lines[0][2..-2] lines.delete_at(0) lines.delete_at(0) lines.each do |line| next if line[0] == 'd' or line [0] == 'l' tarball = line.split(' ').last next if tarball.end_with?('.txt', "CHECKSUMS", '.readme', '.meta', '.sig', '.diff', '.patch') (package_name, file_version) = parse_tarball_name(tarball) if file_version and package_name package_name = package_name.downcase @tarballs[package_name] << file_version @locations[[package_name, file_version]] = "mirror://cpan/#{dir}/#{tarball}" else log.debug "weird #{line}" end end end log.debug @tarballs.inspect end @tarballs end def self.find_tarball(pkg, version) return nil if pkg.url.to_s.empty? or version.to_s.empty? or pkg.version.to_s.empty? (package_name, file_version) = parse_tarball_from_url(pkg.url) return nil unless package_name tarballs # workaround to fetch data @locations[[package_name.downcase, version]] end def self.covers?(pkg) return( pkg.url and pkg.url.start_with? 'mirror://cpan/' and usable_version?(pkg.version) ) end def self.newest_versions_of(pkg) return nil unless pkg.url if pkg.url.start_with? 'mirror://cpan/' return new_tarball_versions(pkg, tarballs) end end end # handles Ruby gems hosted at http://rubygems.org/ class RubyGems < Updater def self.covers?(pkg) return( pkg.url and pkg.url.include? 'rubygems.org/downloads/' and usable_version?(pkg.version) ) end def self.newest_versions_of(pkg) return nil unless pkg.url return nil unless pkg.url.include? 'rubygems.org/downloads/' (package_name, file_version) = parse_tarball_from_url(pkg.url) return nil unless package_name @tarballs ||= {} vdata = http_agent.get("http://rubygems.org/api/v1/versions/#{package_name}.json") @tarballs[package_name] = JSON.parse(vdata.body).map{|v| v["number"]} return new_tarball_versions(pkg, @tarballs) end end # handles Haskell packages hosted at http://hackage.haskell.org/ class Hackage < Updater def self.tarballs unless @tarballs @tarballs = Hash.new{|h,k| h[k] = Array.new } index_gz = http_agent.get('https://hackage.haskell.org/packages/index.tar.gz').body tgz = Zlib::GzipReader.new(StringIO.new(index_gz)).read tar = Gem::Package::TarReader.new(StringIO.new(tgz)) tar.each do |entry| log.warn "failed to parse #{entry.full_name}" unless %r{^(?<pkg>[^/]+)/(?<ver>[^/]+)/} =~ entry.full_name @tarballs[pkg] << ver end tar.close end @tarballs end def self.covers?(pkg) return( pkg.url and pkg.url.start_with? 'mirror://hackage/' and usable_version?(pkg.version) ) end def self.newest_versions_of(pkg) return nil unless pkg.url if pkg.url.start_with? 'mirror://hackage/' return new_tarball_versions(pkg, tarballs) end end end # handles Python packages hosted at http://pypi.python.org/ class Pypi < Updater def self.releases @releases ||= Hash.new do |h, pkgname| h[pkgname] = JSON.parse(http_agent.get("http://pypi.python.org/pypi/#{pkgname}/json") .body)["releases"].keys end end def self.covers?(pkg) return( pkg.url =~ %r{^https?://pypi.python.org/packages/source/./([^/]*)/[^/]*$} and usable_version?(pkg.version) ) end def self.newest_versions_of(pkg) return nil unless pkg.url and %r{^https?://pypi.python.org/packages/source/./(?<pkgname>[^/]*)/[^/]*$} =~ pkg.url return new_versions(pkg.version.downcase, releases[pkgname], pkg.internal_name) end end # handles GNU packages hosted at mirror://gnu/ class GNU < Updater def self.tarballs unless @tarballs @tarballs = Hash.new{|h,path| h[path] = tarballs_from_dir("http://ftpmirror.gnu.org#{path}") } end @tarballs end def self.covers?(pkg) return( pkg.url and pkg.url =~ %r{^mirror://gnu(/[^/]*)/[^/]*$} and usable_version?(pkg.version) ) end def self.newest_versions_of(pkg) return nil unless pkg.url return nil unless pkg.url =~ %r{^mirror://gnu(/[^/]*)/[^/]*$} path = $1 return new_tarball_versions(pkg, tarballs[path]) end end # handles X.org packages hosted at mirror://xorg/ class Xorg < Updater def self.tarballs unless @tarballs @tarballs = tarballs_from_dir_recursive("http://xorg.freedesktop.org/releases/individual/") log.debug @tarballs.inspect end @tarballs end def self.covers?(pkg) return( pkg.url and pkg.url.start_with? "mirror://xorg/" and usable_version?(pkg.version) ) end def self.newest_versions_of(pkg) return nil unless pkg.url return nil unless pkg.url.start_with? "mirror://xorg/" return new_tarball_versions(pkg, tarballs) end end # handles KDE stable packages hosted at mirror://kde/stable/ class KDE < Updater def self.tarballs unless @tarballs @tarballs = {} dirs = http_agent.get("http://download.kde.org/ls-lR").body.split("\n\n") dirs.each do |dir| lines = dir.split("\n") next unless lines[0].include? '/stable' next if lines[0].include? '/win32:' lines.delete_at(0) lines.each do |line| next if line[0] == 'd' or line [0] == 'l' tarball = line.split(' ').last next if ['.xdelta', '.sha1', '.md5', '.CHANGELOG', '.sha256', '.patch', '.diff'].index{ |s| tarball.include? s} (package_name, file_version) = parse_tarball_name(tarball) if file_version and package_name @tarballs[package_name] = [] unless @tarballs[package_name] @tarballs[package_name] = @tarballs[package_name] << file_version end end end end log.debug @tarballs.inspect @tarballs end def self.covers?(pkg) return( pkg.url and pkg.url.start_with? 'mirror://kde/stable/' and usable_version?(pkg.version) ) end def self.newest_versions_of(pkg) return nil unless pkg.url if pkg.url.start_with? 'mirror://kde/stable/' return new_tarball_versions(pkg, tarballs) end end end # handles GNOME packages hosted at mirror://gnome/ class GNOME < Updater def self.tarballs unless @tarballs @tarballs = Hash.new{|h, path| h[path] = JSON.parse(http_agent.get("http://download.gnome.org#{path}cache.json").body) } end @tarballs end def self.covers?(pkg) return( pkg.url and pkg.url =~ %r{^mirror://gnome(/sources/[^/]*/)[^/]*/[^/]*$} and usable_version?(pkg.version) ) end def self.find_tarball(pkg, version) return nil if pkg.url.to_s.empty? or version.to_s.empty? or pkg.version.to_s.empty? (package_name, file_version) = parse_tarball_from_url(pkg.url) return nil unless package_name repo = tarballs["/sources/#{package_name}/"][1][package_name][version] return nil unless repo file ||= repo["tar.xz"] || repo["tar.bz2"] || repo["tar.gz"] return (file ? "mirror://gnome/sources/#{package_name}/#{file}" : nil ) end def self.newest_versions_of(pkg) return nil unless pkg.url return nil unless pkg.url =~ %r{^mirror://gnome(/sources/[^/]*/)[^/]*/[^/]*$} path = $1 return new_tarball_versions(pkg, tarballs[path][2]) end end # Generic git-based updater. Discovers new versions using git repository tags. class GitUpdater < Updater def self.ls_remote(repo) @repo_cache = {} unless @repo_cache unless @repo_cache[repo] @repo_cache[repo] = %x(GIT_ASKPASS="echo" SSH_ASKPASS= git ls-remote #{repo}).force_encoding("iso-8859-1").split("\n") end @repo_cache[repo] end # Tries to handle the tag as a tarball name. # if parsing it as a tarball fails, treats it as a version. def self.tag_to_version(tag_line) if %r{refs/tags.*/[vr]?(?<tag>\S*?)(\^\{\})?$} =~ tag_line if tag =~ /^[vr]?\d/ return tag else (name, version) = parse_tarball_name(tag) return (version ? version : tag) end else return nil end end def self.repo_contents_to_tags(repo_contents) tags = repo_contents.select{ |s| s.include? "refs/tags/" } return tags.map{ |tag| tag_to_version(tag) } end end # Handles fetchgit-based packages. # Tries to detect which tag the current revision corresponds to. # Otherwise assumes the package is tracking master because # there's no easy way to be smarter without checking out the repository. # Tries to find a newer tag or if tracking master, newest commit. class FetchGit < GitUpdater def self.covers?(pkg) return( pkg.url and not(pkg.revision.to_s.empty?) and pkg.url.include? "git" ) end def self.newest_version_of(pkg) return nil unless covers?(pkg) repo_contents = ls_remote(pkg.url).select{|s| s.include?("refs/tags") or s.include?("refs/heads/master") } tag_line = repo_contents.index{|line| line.include? pkg.revision } log.debug "for #{pkg.revision} found #{tag_line}" if tag_line # revision refers to a tag? return nil if repo_contents[tag_line].include?("refs/heads/master") current_version = tag_to_version(repo_contents[tag_line]) if current_version and usable_version?(current_version) versions = repo_contents_to_tags(repo_contents) max_version = versions.reduce(current_version) do |v1, v2| ( usable_version?(v2) and is_newer?(v2, v1) ) ? v2 : v1 end return (max_version != current_version ? max_version : nil) else log.warn "failed to parse tag #{repo_contents[tag_line]} for #{pkg.name}. Assuming tracking master" end end # assuming tracking master master_line = repo_contents.index{|line| line.include? "refs/heads/master" } if master_line /^(?<master_commit>\S*)/ =~ repo_contents[master_line] log.info "new master commit #{master_commit} for #{pkg.name}:#{pkg.revision}" return( master_commit.start_with?(pkg.revision) ? nil : master_commit ) else log.warn "failed to find master for #{pkg.name}" return nil end end end # Handles GitHub-provided tarballs. class GitHub < GitUpdater def self.covers?(pkg) return( pkg.url and pkg.revision.to_s.empty? and pkg.url =~ %r{^https?://github.com/} and usable_version?(pkg.version) ) end def self.newest_version_of(pkg) return nil unless covers?(pkg) return nil unless %r{^https?://github.com/(?:downloads/)?(?<owner>[^/]*)/(?<repo>[^/]*)/} =~ pkg.url available_versions = repo_contents_to_tags( ls_remote( "https://github.com/#{owner}/#{repo}.git" ) ) return new_versions(pkg.version.downcase, available_versions, pkg.internal_name) end end # Handles packages which specify meta.repositories.git. class MetaGit < GitUpdater # if meta.repository.git is the same as src.url, defer to FetchGit updater def self.covers?(pkg) return( not(pkg.repository_git.to_s.empty?) and (pkg.repository_git != pkg.url) and usable_version?(pkg.version) ) end def self.newest_version_of(pkg) return nil unless covers?(pkg) available_versions = repo_contents_to_tags( ls_remote( pkg.repository_git ) ) return new_versions(pkg.version.downcase, available_versions, pkg.internal_name) end end class XFCE < Updater end end module Distro # checks package versions against Arch Core, Community and Extra repositories class Arch < Updater def self.covers?(pkg) return ( DistroPackage::Arch.list[pkg.name.downcase] and usable_version?(pkg.version) ) end def self.newest_version_of(pkg) arch_pkg = DistroPackage::Arch.list[pkg.name.downcase] return nil unless arch_pkg return nil unless usable_version?(arch_pkg.version) and usable_version?(pkg.version) return ( is_newer?(arch_pkg.version, pkg.version) ? arch_pkg.version : nil) end end # checks package versions against Arch AUR class AUR < Updater def self.covers?(pkg) return ( DistroPackage::AUR.list[pkg.name.downcase] and usable_version?(pkg.version) ) end def self.newest_version_of(pkg) arch_pkg = DistroPackage::AUR.list[pkg.name.downcase] return nil unless arch_pkg return nil unless usable_version?(arch_pkg.version) and usable_version?(pkg.version) return ( is_newer?(arch_pkg.version, pkg.version) ? arch_pkg.version : nil) end end # TODO: checks package versions against Debian Sid class Debian < Updater def self.covers?(pkg) return ( DistroPackage::Debian.match_nixpkg(pkg) and usable_version?(pkg.version) ) end def self.newest_version_of(pkg) deb_pkg = DistroPackage::Debian.match_nixpkg(pkg) return nil unless deb_pkg return nil unless usable_version?(deb_pkg.version) and usable_version?(pkg.version) return ( is_newer?(deb_pkg.version, pkg.version) ? deb_pkg.version : nil) end end # checks package versions agains those discovered by http://euscan.iksaif.net, # which include Gentoo portage, Gentoo developer repositories, euscan-discovered upstream. class Gentoo < Updater def self.covers?(pkg) return ( DistroPackage::Gentoo.match_nixpkg(pkg) and usable_version?(pkg.version) and not Repository::CPAN.covers?(pkg) and not Repository::Hackage.covers?(pkg) ) end def self.newest_version_of(pkg) return nil unless covers?(pkg) gentoo_pkg = DistroPackage::Gentoo.match_nixpkg(pkg) return nil unless gentoo_pkg return nil unless usable_version?(gentoo_pkg.version) and usable_version?(pkg.version) return ( is_newer?(gentoo_pkg.version, pkg.version) ? gentoo_pkg.version : nil) end end end Updaters = [ Repository::CPAN, Repository::RubyGems, Repository::Xorg, Repository::GNOME, Distro::Gentoo, Repository::Hackage, Repository::Pypi, Repository::KDE, Repository::GNU, Repository::SF, Repository::NPMJS, Repository::FetchGit, Repository::GitHub, Repository::MetaGit, GentooDistfiles, Distro::Arch, Distro::Debian, Distro::AUR, ] end
require 'watirspec_helper' describe WatirCss do before do browser.goto(WatirSpec.url_for("non_control_elements.html")) end it "returns true if the element exists" do xpath_class = Watir::Locators::Element::SelectorBuilder::XPath expect_any_instance_of(xpath_class).to_not receive(:build) expect(browser.div(id: /header/)).to exist expect(browser.div(title: "Header and primary navigation")).to exist expect(browser.div(title: /Header and primary navigation/)).to exist expect(browser.div(text: /This is a footer\./)).to exist expect(browser.div(class: "profile")).to exist expect(browser.div(class: /profile/)).to exist expect(browser.div(index: 0)).to exist expect(browser.div(xpath: "//div[@id='header']")).to exist end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :invoice_detail do invoice nil employee nil service_item nil new_price "9.99" discount_type "MyString" discount_value "9.99" end end
Gem::Specification.new do |s| s.name = 'rake_routes_raw' s.version = '0.0.1' s.platform = Gem::Platform::RUBY s.summary = "Provides rake_routes_raw.rake task for use in rails project. rake routes:raw command appends a commented/formatted list of all of apps routes to the config/routes file. It also provides the identical output as 'rake routes' command." s.description = "Provides rake_routes_raw.rake task for use in rails project. The rake routes:raw command appends a complete route list to the config/routes file, for reference. The list provides all pertinent route info (verb, path, controller#action), for all routes including resources. Each route is commented and given its own line with the format: verb 'path' => 'controller#action' The first line of the appended route provides the command name, and the date/time the command was run. In addition to the appended list, the 'rake routes:raw' command produces identical terminal output as running 'rake routes'." s.authors = ['Alex Szabo'] s.email = '87szabo@gmail.com' s.files = ["lib/rake_routes_raw.rb", "lib/rake_routes_raw/railtie.rb", "lib/rake_routes_raw/raw.rake"] s.require_paths = ["lib"] end
require 'rails_helper' context 'logged out' do it 'should take us to a sign up page' do visit '/restaurants' click_link 'Add a restaurant' expect(page).to have_content 'Sign up' end end context 'logged in' do before do nikesh = User.create(email: 'n@n.com', password: '12345678', password_confirmation: '12345678') login_as nikesh end context 'creating a restaurant' do it 'should fill in a form with the details and end up on the index page' do visit '/restaurants' click_link 'Add a restaurant' fill_in 'Name', with: "Nandos" fill_in 'Location name', with: 'shoreditch' click_button 'Create Restaurant' expect(page).to have_content 'Nandos' expect(current_path).to eq '/restaurants' end it 'should show a new form page if the details are not filled in properly' do visit '/restaurants' click_link 'Add a restaurant' fill_in 'Name', with: "Nandos" fill_in 'Location name', with: 'shoreditch' click_button 'Create Restaurant' expect(current_path).to eq '/restaurants' end end end
class PlayersController < ApplicationController before_action :set_tournament before_action :set_admin, only: [:edit, :update, :destroy] before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy] def index @players = @tournament.players.all end def show @player = Player.find(params[:id]) end def new @player = @tournament.players.new end def create if current_user.player.nil? @player = @tournament.players.new(player_params) @player.user_id = current_user.id if @player.save redirect_to @tournament else render 'new' end else flash[:error] = "You're already in tournament." redirect_to tournaments_url end end def edit if current_user == @admin @player = Player.find(params[:id]) else redirect_to @tournament end end def update if current_user == @admin @player = Player.find(params[:id]) if @player.update_attributes(player_params) flash[:success] = "Player was updated successful" redirect_to @tournament else redirect_to @tournament end else redirect_to @tournament end end def destroy if current_user == @admin @player = Player.find(params[:id]).destroy flash[:success] = "Player deleted" redirect_to @tournament else redirect_to @tournament end end private def player_params params.require(:player).permit(:wins, :loses, :draws) end def set_tournament @tournament = Tournament.find(params[:tournament_id]) end def set_admin @tournament = Tournament.find(params[:tournament_id]) @admin = @tournament.user end end
class Hash # Dig a value of hash, by a series of keys # # info = { # order: { # customer: { # name: "Tom", # email: "tom@mail.com" # }, # total: 100 # } # } # # puts info.dig :order, :customer # # => {name: "Tom", email: "tom@mail.com"} # # puts info.dig :order, :customer, :name # # => "Tom" def dig(*keys) keys.flatten! raise if keys.empty? current_key = keys.shift current_value = self.[](current_key) if keys.size == 0 return current_value end if current_value.is_a?(Hash) return current_value.dig(keys) else return nil end end end
require 'test_helper' class PlayAgentsSearchTest < ActiveSupport::TestCase test "Search agent query empty" do user = users(:admin) s = PlayAgentsSearch.new(user) assert_equal "", s.options[:query] assert_equal user.id, s.options[:user_id] end test "Search agent by name" do user = users(:admin) s = PlayAgentsSearch.new(user) assert_equal 2, Agent.search(s.options).count s = PlayAgentsSearch.new(user, query: '800') assert_equal 1, Agent.search(s.options).count expected = ['terminator'] assert_equal expected, Agent.search(s.options).collect(&:agentname) end test "Search selected params" do user = users(:admin) s = PlayAgentsSearch.new(user, selected_ids: [agents(:terminator).id]) expected = ['weather', 'terminator'] assert_equal expected, Agent.search(s.options).order(name: :asc).collect(&:agentname) s = PlayAgentsSearch.new(user, selected_ids: [agents(:terminator).id], selected: 'not true not false') expected = ['weather', 'terminator'] assert_equal expected, Agent.search(s.options).order(name: :asc).collect(&:agentname) s = PlayAgentsSearch.new(user, selected_ids: [agents(:terminator).id], selected: 'true') expected = ['terminator'] assert_equal expected, Agent.search(s.options).order(name: :asc).collect(&:agentname) s = PlayAgentsSearch.new(user, selected_ids: [agents(:terminator).id], selected: 'false') expected = ['weather'] assert_equal expected, Agent.search(s.options).order(name: :asc).collect(&:agentname) end test "Search filter_owner params" do user = users(:admin) s = PlayAgentsSearch.new(user, filter_owner: 'owned') expected = ['weather', 'terminator'] assert_equal expected, Agent.search(s.options).order(name: :asc).collect(&:agentname) s = PlayAgentsSearch.new(user, filter_owner: 'favorites') assert_equal [], Agent.search(s.options).order(name: :asc).collect(&:agentname) end end
# -*- coding: utf-8 -*- =begin Faรงa um programa que carregue uma lista com os modelos de cinco carros (exemplo de modelos: FUSCA, GOL, VECTRA etc). Carregue uma outra lista com o consumo desses carros, isto รฉ, quantos quilรดmetros cada um desses carros faz com um litro de combustรญvel. Calcule e mostre: a. O modelo do carro mais econรดmico; b. Quantos litros de combustรญvel cada um dos carros cadastrados consome para percorrer uma distรขncia de 1000 quilรดmetros e quanto isto custarรก, considerando um que a gasolina custe R$ 2,25 o litro. Abaixo segue uma tela de exemplo. O disposiรงรฃo das informaรงรตes deve ser o mais prรณxima possรญvel ao exemplo. Os dados sรฃo fictรญcios e podem mudar a cada execuรงรฃo do programa. Comparativo de Consumo de Combustรญvel: Veรญculo 1 Nome: fusca Km por litro: 7 Veรญculo 2 Nome: gol Km por litro: 10 Veรญculo 3 Nome: uno Km por litro: 12.5 Veรญculo 4 Nome: Vectra Km por litro: 9 Veรญculo 5 Nome: Peugeout Km por litro: 14.5 Relatรณrio Final 1 - fusca - 7.0 - 142.0 litros - R$ 321.43 2 - gol - 10.0 - 100.0 litros - R$ 225.00 3 - uno - 12.5 - 80.0 litros - R$ 180.00 4 - vectra - 9.0 - 111.1 litros - R$ 250.00 5 - peugeout - 14.5 - 69.0 litros - R$ 155.17 O menor consumo รฉ do peugeout. =end puts "======================================================" modelos = {} modmenor = 0 for i in (0..4) print "Qual o modelo do carro?: " modelo = gets.chomp.to_s print "Digite o consumo: " consumo = gets.chomp.to_f if modmenor == 0 or consumo < modelos[modmenor] modmenor = modelo end modelos[modelo] = consumo end puts puts "---Comparativo de consumo de combustivel---" puts "----------------------------------------------" i = 0 for m in modelos # Erro puts "Veiculo #{i}, #{m}: " puts "Km por litro: #{modelos[m]}" puts "------------------------------------------" i += 1 end i = 0 puts puts "--Relatorio Final--" puts "----------------------" for m in modelos # Erro puts "#{i}, #{m}, #{modelos[m]}, #{(1000 / modelos[m]).to_f} litros R$ #{((1000/modelos[m]) * 2.25).to_f}" # Erro puts "Km por litro: #{modelos[m]}" puts "-----------------------------------------" i += 1 end puts "O menor consumo e do #{modmenor}." puts "======================================================"
class AddLatitudeAndLongitudeToCrime< ActiveRecord::Migration def change add_column :crimes, :latitude, :float add_column :crimes, :longitude, :float end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) User.destroy_all User.create!({ email: 'guest@guest.com', username: 'guest', password: 'guestpass' }) all_users = []; 20.times do email = Faker::Internet.free_email username = Faker::Internet.user_name email = Faker::Internet.free_email while (User.find_by(email: email)) user = User.create!({ email: email, username: username, password: '123456' }) all_users.push(user) end Genre.destroy_all all_genres = [ #0 Genre.create!(name: "Thrillers"), #1 Genre.create!(name: "Crime Shows"), #2 Genre.create!(name: "Comedies"), #3 Genre.create!(name: "Action and Adventure"), #4 Genre.create!(name: "Mysteries"), #5 Genre.create!(name: "Sports"), #6 Genre.create!(name: "Documentaries"), #7 Genre.create!(name: "Coding"), #8 ] Serie.destroy_all all_series = [ #0 Walking Dead Serie.create!({ title: 'The Walking Dead', description: 'Waking up in an empty hospital after weeks in a coma, County Sheriff Rick Grimes (Andrew Lincoln) finds himself utterly alone. The world as he knows it is gone, ravaged by a zombie epidemic.', year: 2014, image: File.open('app/assets/images/series/the-walking-dead.jpg'), genres: [all_genres[0]] }), #1 Breaking Bad Serie.create!({ title: 'Breaking Bad', description: 'A high school chemistry teacher diagnosed with inoperable lung cancer turns to manufacturing and selling methamphetamine in order to secure his family''s future.', year: 2008, image: File.open('app/assets/images/series/breaking_bad/breaking-bad-season-4.jpg'), genres: [all_genres[1], all_genres[0]] }), #2 Conan O'Brien Serie.create!({ title: 'Conan O''Brien', description: 'A late-night comedy show hosted by writer, comedian and performer Conan O''Brien', year: 2002, image: File.open('app/assets/images/series/conan/conan-o-brien.jpg'), genres: [all_genres[2]] }), #3 SuperGirl Serie.create!({ title: 'SuperGirl', description: 'The adventures of Superman''s cousin in her own superhero career.', year: 2015, image: File.open('app/assets/images/series/supergirl/supergirl.png'), genres: [all_genres[3], all_genres[1]] }), #4 NBA Knicks Highlights Serie.create!({ title: 'NBA Knicks Highlights', description: 'Watch the Knicks as they wheel and deal through the 2016-17 season!', year: 2016, image: File.open('app/assets/images/series/knicks/knicks.jpg'), genres: [all_genres[5]] }), #5 Ruby Serie.create!({ title: 'Ruby', description: 'Learn the basics of Ruby!', year: 2013, image: File.open('app/assets/images/series/ruby.jpg'), genres: [all_genres[7]] }), #6 Javascript Serie.create!({ title: 'Javascript', description: 'Learn to the basics of Javascript!', year: 2015, image: File.open('app/assets/images/series/javascript.png'), genres: [all_genres[7]] }), #7 React Serie.create!({ title: 'React', description: 'Improve your Javascript capabilities with React!', year: 2016, image: File.open('app/assets/images/series/react.png'), genres: [all_genres[7]] }), #8 Redux Serie.create!({ title: 'Redux', description: 'Mastered Javascript and React? Learn Redux!', year: 2016, image: File.open('app/assets/images/series/redux.png'), genres: [all_genres[7]] }), #9 Rails Serie.create!({ title: 'Ruby on Rails', description: 'Mastered Ruby? Learn to become a Ruby on Rails developer!', year: 2016, image: File.open('app/assets/images/series/rails.jpg'), genres: [all_genres[7]] }), #10 Westworld Serie.create!({ title: 'Westworld', description: 'The one-hour drama series Westworld is a dark odyssey about the dawn of artificial consciousness and the evolution of sin. Set at the intersection of the near future and the reimagined past, it explores a world in which every human appetite, no matter how noble or depraved, can be indulged.', year: 2016, image: File.open('app/assets/images/series/westworld/westworld-cover.jpg'), genres: [all_genres[0], all_genres[4]] }), #11 Criminal Minds Serie.create!({ title: 'Criminal Minds', description: 'Based in Quantico, Virginia, the Behavioral Analysis Unit (BAU) is a subsection of the FBI. Called in by local police departments to assist in solving crimes of a serial and/or extremely violent nature where the perpetrator is unknown (referred to by the Unit as the unknown subject or unsub for short), the BAU uses the controversial scientific art of profiling to track and apprehend the unsub. ', year: 2005, image: File.open('app/assets/images/series/criminal_minds/criminal-minds-cover.jpg'), genres: [all_genres[1], all_genres[4]] }), #12 Dexter Serie.create!({ title: 'Dexter', description: 'Dexter Morgan is a Forensics Expert, a loyal brother, boyfriend, and friend. That''s what he seems to be, but that''s not what he really is. Dexter Morgan is a Serial Killer that hunts the bad.', year: 2006, image: File.open('app/assets/images/series/dexter/dexter-cover.jpg'), genres: [all_genres[1]] }), #13 Sherlock Serie.create!({ title: 'Sherlock', description: 'A modern update finds the famous sleuth and his doctor partner solving crime in 21st century London.', year: 2010, image: File.open('app/assets/images/series/sherlock/sherlock-cover.jpg'), genres: [all_genres[4], all_genres[1]] }), #14 Homeland Serie.create!({ title: 'Homeland', description: 'A bipolar CIA operative becomes convinced a prisoner of war has been turned by al-Qaeda and is planning to carry out a terrorist attack on American soil.', year: 2011, image: File.open('app/assets/images/series/homeland/homeland-cover.jpg'), genres: [all_genres[4], all_genres[0]] }), #15 American Crime Serie.create!({ title: 'American Crime', description: 'The lives of the participants in a trial with significant racial motives are forever changed during the legal process.', year: 2015, image: File.open('app/assets/images/series/american_crime/american-crime-cover.jpg'), genres: [all_genres[1]] }), #16 Kevin Hart Serie.create!({ title: 'Kevin Hart', description: 'Comedian and actor Kevin Hart came to fame as a stand-up comic. He has appeared in several films and has three albums, including the 2011 hit Laugh at My Pain.', year: 2010, image: File.open('app/assets/images/series/kevin_hart/kevin-hart-cover.png'), genres: [all_genres[2]] }), #17 Jay Pharoah Serie.create!({ title: 'Jay Pharoah', description: 'A comedic wizard, watch Jay Pharoah as he creates spot-on impressions of celebrities around the world.', year: 2011, image: File.open('app/assets/images/series/jay_pharoah/jay-pharoah-cover.jpg'), genres: [all_genres[2]] }), #18 Jimmy Fallon Tonight Show Serie.create!({ title: 'The Tonight Show', description: 'Emmy Award and Grammy Award winner Jimmy Fallon brought NBC''s "The Tonight Show" back to its New York origins when he launched "The Tonight Show Starring Jimmy Fallon" from Rockefeller Center. Fallon puts his own stamp on the storied NBC late-night franchise with his unique comedic wit, on-point pop culture awareness, welcoming style and impeccable taste in music with the award-winning house band, The Roots.', year: 2014, image: File.open('app/assets/images/series/the_tonight_show/jimmy-fallon-cover.jpg'), genres: [all_genres[2]] }), #19 Last Week Tonight with John Oliver Serie.create!({ title: 'Last Week Tonight', description: 'An American late-night talk and news satire television program hosted by comedian John Oliver', year: 2014, image: File.open('app/assets/images/series/john_oliver/john-oliver.jpg'), genres: [all_genres[2]] }), #20 SNL Serie.create!({ title: 'Saturday Night Live', description: 'The famous guest host stars in parodies and sketches created by the cast of this witty show.', year: 2002, image: File.open('app/assets/images/series/snl/snl-cover.jpg'), genres: [all_genres[2]] }), #21 The Daily Show Serie.create!({ title: 'The Daily Show', description: 'Trevor Noah takes on the very tall task of replacing longtime host Jon Stewart on Comedy Central''s Emmy- and Peabody Award-winning talk/news satire program.', year: 2015, image: File.open('app/assets/images/series/the_daily_show/the-daily-show-cover.jpg'), genres: [all_genres[2]] }), #22 Node Serie.create!({ title: 'Node.JS', description: 'Learn Node!', year: 2015, image: File.open('app/assets/images/series/node/node-cover.png'), genres: [all_genres[7]] }), #23 24 Serie.create!({ title: '24', description: 'Jack Bauer, Director of Field Ops for the Counter-Terrorist Unit of Los Angeles, races against the clock to subvert terrorist plots and save his nation from ultimate disaster.', year: 2001, image: File.open('app/assets/images/series/24/24-cover.jpg'), genres: [all_genres[3]] }), #24 Stranger Things Serie.create!({ title: 'Stranger Things', description: 'When a young boy disappears, his mother, a police chief, and his friends must confront terrifying forces in order to get him back.', year: 2016, image: File.open('app/assets/images/series/stranger_things/stranger-things-cover.jpg'), genres: [all_genres[0], all_genres[4]] }), #25 Arrow Serie.create!({ title: 'Arrow', description: 'Spoiled billionaire playboy Oliver Queen is missing and presumed dead when his yacht is lost at sea. He returns five years later a changed man, determined to clean up the city as a hooded vigilante armed with a bow.', year: 2012, image: File.open('app/assets/images/series/arrow/arrow-cover.jpg'), genres: [all_genres[3]] }), #26 Prison Break Serie.create!({ title: 'Prison Break', description: 'Due to a political conspiracy, an innocent man is sent to death row and his only hope is his brother, who makes it his mission to deliberately get himself sent to the same prison in order to break the both of them out, from the inside.', year: 2005, image: File.open('app/assets/images/series/prison_break/prison-break-cover.jpg'), genres: [all_genres[3], all_genres[1], all_genres[0]] }), #27 Supernatural Serie.create!({ title: 'Supernatural', description: 'Two brothers follow their father''s footsteps as "hunters" fighting evil supernatural beings of many kinds including monsters, demons, and gods that roam the earth.', year: 2005, image: File.open('app/assets/images/series/supernatural/supernatural-cover.png'), genres: [all_genres[0], all_genres[3], all_genres[4]] }), #28 Game of Thrones Serie.create!({ title: 'Game of Thrones', description: 'Nine noble families fight for control over the mythical lands of Westeros. Meanwhile, a forgotten race, hell-bent on destruction, returns after being dormant for thousands of years.', year: 2011, image: File.open('app/assets/images/series/game_of_thrones/game-of-thrones-cover.jpg'), genres: [all_genres[3]] }), #29 Lost Serie.create!({ title: 'Lost', description: 'The survivors of a plane crash are forced to work together in order to survive on a seemingly deserted tropical island.', year: 2011, image: File.open('app/assets/images/series/lost/lost-cover.jpg'), genres: [all_genres[4]] }), #30 Shaqtin A Fool Serie.create!({ title: 'Shaqtin A Fool', description: 'A hilarious segment that covers the most humorous and uncommon basketball plays that have occurred during NBA games in the past week. Hosted by Shaquille O''Neal', year: 2016, image: File.open('app/assets/images/series/shaqtin/shaqtin-cover.jpg'), genres: [all_genres[5]] }), #31 Premier League Highlights Serie.create!({ title: 'Barclays Premier League', description: 'Highlights from the 2016-17 Premier League', year: 2016, image: File.open('app/assets/images/series/premier_league/premier-league-cover.jpg'), genres: [all_genres[5]] }), #32 NFL Highlights Serie.create!({ title: 'NFL', description: 'Highlights from the 2016-17 National Football League', year: 2016, image: File.open('app/assets/images/series/nfl/nfl-cover.jpg'), genres: [all_genres[5]] }), #33 PGA Tour Serie.create!({ title: 'PGA Tour', description: 'Highlights from the 2016-17 Professional Golf Association', year: 2016, image: File.open('app/assets/images/series/golf/pga-cover.jpg'), genres: [all_genres[5]] }), #34 Rio Olympics Serie.create!({ title: 'Rio Olympics 2016', description: 'Highlights from the 2016 Rio Olympics', year: 2016, image: File.open('app/assets/images/series/rio/rio-cover.jpg'), genres: [all_genres[5]] }), # 35 Vice Documentaries Serie.create!({ title: 'Vice Documentaries', description: 'A documentary TV series created and hosted by Shane Smith of Vice magazine. Produced by Bill Maher, it uses CNN journalist Fareed Zakaria as a consultant, and covers topics using an immersionist style of documentary filmmaking.', year: 2013, image: File.open('app/assets/images/series/vice/vice-cover.jpg'), genres: [all_genres[6]] }), # 36 4K Videos Serie.create!({ title: '4K Videos', description: 'A series of beautiful, 4K videos with soothing background music', year: 2016, image: File.open('app/assets/images/series/4K/4K-cover.jpg'), genres: [all_genres[6]] }), ] Episode.destroy_all all_episodes = [ #Walking Dead Episode.create!({ title: 'Days Gone Bye', synopsis: 'Wounded in the line of duty, King County sheriff''s deputy, Rick Grimes, wakes from a coma to find the world infested by zombies. Alone and disoriented, he sets off in search of his wife and son.', serie_id: all_series[0].id, image: File.open('app/assets/images/series/walking_dead/walking-dead-episode-1.png'), video_url: 'GJRNHAJAcYg', episode_number: 1 }), Episode.create!({ title: 'Guts', synopsis: 'Rick unknowingly causes a group of survivors to be trapped by walkers. The group dynamic devolves from accusations to violence, as Rick must confront an enemy far more dangerous than the undead.', serie_id: all_series[0].id, image: File.open('app/assets/images/series/walking_dead/walking-dead-episode-2.jpg'), video_url: 'fYIqssyz-sI', episode_number: 2 }), Episode.create!({ title: 'Tell It to the Frogs', synopsis: 'Driving back to camp, Morales warns Rick about Merle''s brother, Daryl, who will be irate about his brother''s abandonment. Glenn arrives at camp first, and Shane and Dale chastise him about drawing walkers with the alarm. Jim disconnects the alarm just as the cube van approaches.', serie_id: all_series[0].id, image: File.open('app/assets/images/series/walking_dead/walking-dead-episode-3.png'), video_url: 'PRUO5fMR8xk', episode_number: 3 }), Episode.create!({ title: 'Vatos', synopsis: 'Rick''s mission to Atlanta is jeopardized when things go awry. Jim becomes unhinged in camp.', serie_id: all_series[0].id, image: File.open('app/assets/images/series/walking_dead/walking-dead-episode-4.jpg'), video_url: 'z5lQQZ7i15A', episode_number: 4 }), Episode.create!({ title: 'Wildfire', synopsis: 'Rick leads the group to the CDC after the attack. Jim must make a terrible life and death decision.', serie_id: all_series[0].id, image: File.open('app/assets/images/series/walking_dead/walking-dead-episode-5.jpg'), video_url: 'DJb7tK_VaaE', episode_number: 5 }), Episode.create!({ title: 'TS-19', synopsis: 'Driving back to camp, Morales warns Rick about Merle''s brother, Daryl, who will be irate about his brother''s abandonment. Glenn arrives at camp first, and Shane and Dale chastise him about drawing walkers with the alarm. Jim disconnects the alarm just as the cube van approaches.', serie_id: all_series[0].id, image: File.open('app/assets/images/series/walking_dead/walking-dead-episode-6.jpg'), video_url: 'cDFk39WJxCw', episode_number: 6 }), #Breaking Bad Episode.create!({ title: 'Pilot', synopsis: 'Walter White, a 50-year-old chemistry teacher, secretly begins making crystallized methamphetamine to support his family after learning that he has terminal lung cancer', serie_id: all_series[1].id, image: File.open('app/assets/images/series/breaking_bad/breaking-bad-episode-1.jpeg'), video_url: 'HhesaQXLuRY', episode_number: 1 }), Episode.create!({ title: 'Cat''s In the Bag', synopsis: 'Walt and Jesse try to dispose of the two bodies in the RV, which becomes increasingly complicated when one of them, Krazy-8, wakes up.', serie_id: all_series[1].id, image: File.open('app/assets/images/series/breaking_bad/breaking-bad-episode-2.jpeg'), video_url: 'T-E8rbHLSW8', episode_number: 2 }), Episode.create!({ title: 'โ€ฆAnd the Bag''s in the River', synopsis: 'Walt and Jesse clean up last week''s mess and Walt must face holding up his end of the deal. Walt''s DEA agent brother-in-law, Hank (Dean Norris), warns Walt, Jr. (RJ Mitte) about the dangers of drugs.', serie_id: all_series[1].id, image: File.open('app/assets/images/series/breaking_bad/breaking-bad-episode-3.jpeg'), video_url: '9jWlHk1LNXg', episode_number: 3 }), Episode.create!({ title: 'Cancer Man', synopsis: 'Hank starts looking for the new drug kingpin. Walter reveals that he has cancer at a family barbecue. Jesse goes to visit his family.', serie_id: all_series[1].id, image: File.open('app/assets/images/series/breaking_bad/breaking-bad-episode-4.jpeg'), video_url: 'lrcqbavlbyQ', episode_number: 4 }), #Westworld Episode.create!({ title: 'The Original', synopsis: 'Dolores Abernathy, a blood-spattered young host, sits naked in a diagnostic room. A voice interviews her, and Dolores flatly describes her world as she wakes up on her familyโ€™s ranch and begins her day.', serie_id: all_series[10].id, image: File.open('app/assets/images/series/westworld/westworld-episode-1.jpg'), video_url: 'AZBDXqDBo_c', episode_number: 1 }), Episode.create!({ title: 'Chestnut', synopsis: 'Dolores is roused in the middle of the night by a strange voice. โ€œDo you remember?โ€ the voice asks, prompting Dolores to walk outside.', serie_id: all_series[10].id, image: File.open('app/assets/images/series/westworld/westworld-episode-2.jpg'), video_url: 'pXKjjg4R-Is', episode_number: 2 }), Episode.create!({ title: 'The Stray', synopsis: 'Bernard begins a diagnostic with Dolores, who assures him she has not told anyone of their conversations. He brings her a gift, Alice in Wonderland, asking her if the passages in the book remind her of anything. โ€œBut if Iโ€™m not the same,โ€ she reads, โ€œthe next question is, who in the world am I?โ€', serie_id: all_series[10].id, image: File.open('app/assets/images/series/westworld/westworld-episode-3.jpg'), video_url: '52ic4_2lkWk', episode_number: 3 }), Episode.create!({ title: 'Dissonance Theory', synopsis: 'In a diagnostic session, Bernard asks Dolores why she ran from the ranch. She explains that even though her family is gone, she holds on to the pain of their loss. โ€œI feel spaces opening up inside me,โ€ she continues, โ€œlike a building with rooms Iโ€™ve never explored.โ€ Bernard tells Dolores she can be free if she can find the center of the maze. Dolores wakes up at William and Loganโ€™s campsite, gun in her hand.', serie_id: all_series[10].id, image: File.open('app/assets/images/series/westworld/westworld-episode-4.jpg'), video_url: 'b6NpfamnhYU', episode_number: 4 }), Episode.create!({ title: 'Contrapasso', synopsis: 'Dr. Ford tells Old Bill the story of his childhood greyhound; when it was let off-leash one day at the park, it killed a cat, mistaking it for the rabbit plush used in training races. โ€œThat dog had spent its whole life trying to catch that thing,โ€ Ford explains. โ€œNow it had no idea what to do.โ€', serie_id: all_series[10].id, image: File.open('app/assets/images/series/westworld/westworld-episode-5.jpg'), video_url: 'qPCwi92Jofw', episode_number: 5 }), # Conan Episode.create!({ title: 'Clueless Gamer: "Battlefield 1" With Terry Crews', synopsis: 'The WWI first person shooter game is so intense, Conan and Terry need some fuzzy bunnies to help calm their nerves.', serie_id: all_series[2].id, image: File.open('app/assets/images/series/conan/conan-terry.jpg'), video_url: 'jLhjsPjR-xk', episode_number: 1 }), # Supergirl Episode.create!({ title: 'The Adventures of Supergirl', synopsis: 'The premiere picks up right where the finale left off: Kara and Martian Manhunter fly to the crash site and find Mon-El (Chris Wood) peacefully asleep in the pod.', serie_id: all_series[3].id, image: File.open('app/assets/images/series/supergirl/supergirl-episode-1.jpg'), video_url: '7vGuQ17HkTc', episode_number: 1 }), # Knicks Highlights Episode.create!({ title: 'New York Knicks vs. LA Lakers', synopsis: 'The New York Knicks take on the LA Lakers at the Staples Center', serie_id: all_series[4].id, image: File.open('app/assets/images/series/knicks/knicks-episode-1.jpg'), video_url: 'xxnSoXJHjqA', episode_number: 1 }), # Ruby Episode.create!({ title: 'Ruby - An Overview', synopsis: 'A complete tutorial on Ruby.', serie_id: all_series[5].id, image: File.open('app/assets/images/series/ruby.jpg'), video_url: 'Dji9ALCgfpM', episode_number: 1 }), # Javascript Episode.create!({ title: 'Javascript - An Overview', synopsis: 'A complete tutorial on Javascript.', serie_id: all_series[6].id, image: File.open('app/assets/images/series/javascript.png'), video_url: 'fju9ii8YsGs', episode_number: 1 }), # React Episode.create!({ title: 'React - Introduction & Workspace Setup', synopsis: 'An introduction to React and a tutorial on setting it up!', serie_id: all_series[7].id, image: File.open('app/assets/images/series/react.png'), video_url: 'MhkGQAoc7bc', episode_number: 1 }), # Redux Episode.create!({ title: 'Redux - How Redux Works', synopsis: 'An introduction to Redux and why it is useful.', serie_id: all_series[8].id, image: File.open('app/assets/images/series/redux.png'), video_url: '1w-oQ-i1XB8', episode_number: 1 }), # Rails Episode.create!({ title: 'Ruby on Rails - Part One', synopsis: 'Part one of a Ruby On Rails series', serie_id: all_series[9].id, image: File.open('app/assets/images/series/rails.jpg'), video_url: 'GY7Ps8fqGdc', episode_number: 1 }), # Criminal Minds Episode.create!({ title: 'The Crimson King', synopsis: 'Agent Luke Alvez (Adam Rodriguez) joins the BAU team, which is tasked with capturing a killer who escaped prison with 13 other convicts at the end of last season.', serie_id: all_series[11].id, image: File.open('app/assets/images/series/criminal_minds/criminal-minds-episode-1.png'), video_url: 'XGTpYJ6jswQ', episode_number: 1 }), # Dexter Episode.create!({ title: 'Pilot', synopsis: 'By day he is a blood spatter analyst who works for the Homicide Department of the Miami Metro Police.', serie_id: all_series[12].id, image: File.open('app/assets/images/series/dexter/dexter-episode-1.jpg'), video_url: 'x9aGJeL_BRc', episode_number: 1 }), # Sherlock Episode.create!({ title: 'A Study in Pink', synopsis: 'War vet Dr. John Watson returns to London in need of a place to stay. He meets Sherlock Holmes, a consulting detective, and the two soon find themselves digging into a string of serial "suicides."', serie_id: all_series[13].id, image: File.open('app/assets/images/series/sherlock/sherlock-episode-1.jpg'), video_url: 'JP5Dr63TbSU', episode_number: 1 }), # Homeland Episode.create!({ title: 'Pilot', synopsis: 'A CIA case officer (Claire Danes) becomes suspicious that a Marine Sergeant rescued from captivity has been turned into a sleeper agent by Al Qaeda. ', serie_id: all_series[14].id, image: File.open('app/assets/images/series/homeland/homeland-episode-1.jpg'), video_url: 'N-1Jz8ZJjpA', episode_number: 1 }), # American Crime Episode.create!({ title: 'Episode One', synopsis: 'Social injustice stirs up tensions in a California city after a shocking crime.', serie_id: all_series[15].id, image: File.open('app/assets/images/series/american_crime/american-crime-episode-1.jpg'), video_url: 'Uu2P7ABRLRw', episode_number: 1 }), # Kevin Hart Episode.create!({ title: 'Let Me Explain', synopsis: 'Kevin Hart Let Me Explain 2013 | Kevin Hart Stand Up Comedy Show', serie_id: all_series[16].id, image: File.open('app/assets/images/series/kevin_hart/kevin-hart-episode-1.jpg'), video_url: 'kB7Pg_D89I0', episode_number: 1 }), # Jay Pharoah Episode.create!({ title: 'Jay Pharoah Impersonates Jay Z, Kendrick Lamar, Will Smith + More', synopsis: 'Jay Pharoah impersonates celebrities Jay-Z, Kendrick Lamar, Will Smith and others on Radio Malcolm.', serie_id: all_series[17].id, image: File.open('app/assets/images/series/jay_pharoah/jay-pharoah-episode-1.jpg'), video_url: '-BrWqNxXj40', episode_number: 1 }), # Jimmy Fallon Episode.create!({ title: 'Singing Whisper Challenge with Emma Stone', synopsis: 'Jimmy and Emma Stone take turns guessing random song titles and lyrics while wearing noise-canceling headphones.', serie_id: all_series[18].id, image: File.open('app/assets/images/series/the_tonight_show/the-tonight-show-episode-1.jpg'), video_url: 'zzWWmG3CUWc', episode_number: 1 }), # John Oliver Episode.create!({ title: 'Pumpkin Spice (Web Exclusive): Last Week Tonight with John Oliver (HBO)', synopsis: 'John Oliver investigates pumpkin spice lattes. Well, he doesn''t really investigate. He says things about it, though!', serie_id: all_series[19].id, image: File.open('app/assets/images/series/john_oliver/john-oliver-episode-1.jpg'), video_url: 'DeQqe0oj5Ls', episode_number: 1 }), # SNL Episode.create!({ title: 'A Thanksgiving Miracle - SNL', synopsis: 'There''s only one thing that can keep a family (Beck Bennett, Jay Pharoah, Cecily Strong, Aidy Bryant, Matthew McConaughey, Kate McKinnon, Vanessa Bayer) from fighting at Thanksgiving: Adele.', serie_id: all_series[20].id, image: File.open('app/assets/images/series/snl/snl-episode-1.jpg'), video_url: 'e2zyjbH9zzA', episode_number: 1 }), # The Daily Show Episode.create!({ title: 'The Daily Show with Trevor Noah - Ben Carson Blames the Victims', synopsis: 'Presidential hopeful Ben Carson doubles down on condemnatory remarks he made about victims of a mass shooting at an Oregon community college.', serie_id: all_series[21].id, image: File.open('app/assets/images/series/the_daily_show/the-daily-show-episode-1.jpg'), video_url: 'oe06jLcpjYI', episode_number: 1 }), # Node.js Episode.create!({ title: 'What is Node.js Exactly? - a beginners introduction to Nodejs', synopsis: 'What exactly is node.js? Is it a command-line tool, a language, the same thing as Ruby on Rails, a cure for cancer?', serie_id: all_series[22].id, image: File.open('app/assets/images/series/node/node-cover.png'), video_url: 'pU9Q6oiQNd0', episode_number: 1 }), # 24 Episode.create!({ title: 'Midnight - 1:00 A.M.', synopsis: 'Jack Bauer comes out of hiding in London to head off a massive terrorist attack ', serie_id: all_series[23].id, image: File.open('app/assets/images/series/24/24-episode-1.jpg'), video_url: 'Do_LT2xbFXo', episode_number: 1 }), # Stranger Things Episode.create!({ title: 'Chapter One: The Vanishing of Will Byers', synopsis: 'In a small Indiana town, the disappearance of a young boy sparks a police investigation.', serie_id: all_series[24].id, image: File.open('app/assets/images/series/stranger_things/stranger-things-episode-1.jpg'), video_url: '5kRo6Yg091o', episode_number: 1 }), # Arrow Episode.create!({ title: 'Pilot', synopsis: 'Billionaire playboy Oliver Queen is discovered on a remote Pacific island, having been shipwrecked for the previous five years. Oliver is welcomed back home to Starling City by his mother Moira, stepfather Walter Steele, younger sister Thea, and best friend Tommy Merlyn. They can sense that Oliver has changed, and try to question him about his time on the island after viewing the numerous scars that have riddled his body.', serie_id: all_series[25].id, image: File.open('app/assets/images/series/arrow/arrow-episode-1.jpg'), video_url: 'ofzPONG8hDU', episode_number: 1 }), # Prison Break Episode.create!({ title: 'Pilot', synopsis: 'Burrows'' brother Michael Scofield, a structural engineer, plans to get himself incarcerated so he can save his brother from his death sentence, by using his new body tattoo.', serie_id: all_series[26].id, image: File.open('app/assets/images/series/prison_break/prison-break-episode-1.jpg'), video_url: 'AL9zLctDJaU', episode_number: 1 }), # Supernatural Episode.create!({ title: 'Pilot', synopsis: 'Sam and Dean Winchester were trained by their father to hunt the creatures of the supernatural. Now, their father has mysteriously disappeared while hunting the demon that killed their mother, 22 years ago.', serie_id: all_series[27].id, image: File.open('app/assets/images/series/supernatural/supernatural-episode-1.jpg'), video_url: '8AyCXsVrLhY', episode_number: 1 }), # Game of Thrones Episode.create!({ title: 'Winter Is Coming', synopsis: 'Jon Arryn, the Hand of the King, is dead. King Robert Baratheon plans to ask his oldest friend, Eddard Stark, to take Jon''s place. Across the sea, Viserys Targaryen plans to wed his sister to a nomadic warlord in exchange for an army.', serie_id: all_series[28].id, image: File.open('app/assets/images/series/game_of_thrones/game-of-thrones-episode-1.jpg'), video_url: 'iGp_N3Ir7Do&t=7s', episode_number: 1 }), # Lost Episode.create!({ title: 'Pilot', synopsis: 'Forty-eight survivors of an airline flight originating from Australia, bound for the U.S., which crash-lands onto an unknown island 1000 miles off course, struggle to figure out a way to survive while trying to find a way to be rescued.', serie_id: all_series[29].id, image: File.open('app/assets/images/series/lost/lost-episode-1.png'), video_url: 'KTu8iDynwNc', episode_number: 1 }), # Shaqtin A Fool Episode.create!({ title: 'Shaqtin'' A Fool | December 8, 2016 | 2016-17 NBA Season', synopsis: 'Shaqtin'' A Fool highlights from December 8th, 2016.', serie_id: all_series[30].id, image: File.open('app/assets/images/series/shaqtin/shaqtin-episode-1.jpg'), video_url: 'vJMIGI7FZtY', episode_number: 1 }), # Premier League Highlights Episode.create!({ title: 'Barcelona vs Malaga 3-0 Highlights', synopsis: 'Barcelona vs. Malaga', serie_id: all_series[31].id, image: File.open('app/assets/images/series/premier_league/premier-league-episode-1.jpg'), video_url: 'rFqLo39ja_Y', episode_number: 1 }), # 4K Videos Episode.create!({ title: 'Alchemy', synopsis: 'Alchemy is a short film about transformation. In nature, everything is constantly changing: the earth, the sky, the stars, and all living things. Spring is followed by summer, fall and winter. Water turns into clouds, rain and ice. Over time, rivers are created, canyons carved, and mountains formed. All of these elements, mixed together, create the magic of nature''s alchemy.', serie_id: all_series[36].id, image: File.open('app/assets/images/series/4K/4K-episode-1.png'), video_url: 'eYqIEBpbRhg', episode_number: 1 }), Episode.create!({ title: 'Ink Drops', synopsis: 'Ink in action', serie_id: all_series[36].id, image: File.open('app/assets/images/series/4K/4K-episode-2.jpg'), video_url: 'k_okcNVZqqI', episode_number: 2 }), Episode.create!({ title: 'Postcard from Innsbruck', synopsis: 'Filmed in Innsbruck, Austria on the Canon 1DC in 4K', serie_id: all_series[36].id, image: File.open('app/assets/images/series/4K/4K-episode-3.jpg'), video_url: 'EbvVpvXwlKU', episode_number: 3 }), Episode.create!({ title: 'Australia', synopsis: 'Filming in Australia. Observe the natural beauty of an amazing place.', serie_id: all_series[36].id, image: File.open('app/assets/images/series/4K/4K-episode-4.jpg'), video_url: 'tJGnHB3rtMU', episode_number: 4 }), Episode.create!({ title: 'Wildlife', synopsis: 'Majestic animals in their natural habitats', serie_id: all_series[36].id, image: File.open('app/assets/images/series/4K/4K-episode-5.jpg'), video_url: 'xDMP3i36naA', episode_number: 5 }), Episode.create!({ title: 'The Nepalese Honey That Makes People Hallucinate', synopsis: 'Nepalโ€™s Gurung people live mostly in small villages in the vast Annapurna mountain ranges. In this remote region, they practice an ancient tradition of honey hunting where they descend towering cliffs on handmade ladders, to harvest honey nestled under jagged overhangs. ', serie_id: all_series[35].id, image: File.open('app/assets/images/series/vice/vice-episode-1.jpg'), video_url: 'wDOvmhqvIA8', episode_number: 1 }), Episode.create!({ title: 'Top 10 Divisional Playoff Moments of All Time | NFL', synopsis: 'We count down the top 10 moments in NFL Divisional Playoff history!', serie_id: all_series[32].id, image: File.open('app/assets/images/series/nfl/nfl-episode-1.jpg'), video_url: 'CcDovivXSGE', episode_number: 1 }), Episode.create!({ title: 'Highlights | Race continues for the FedExCup at the TOUR Championship', synopsis: 'In the third round of the 2016 TOUR Championship, Dustin Johnson stumbles down the stretch and settles into a tie for the lead with Kevin Chappell entering Championship Sunday.', serie_id: all_series[33].id, image: File.open('app/assets/images/series/golf/golf-episode-1.jpg'), video_url: '8i5zpqSi4Ik', episode_number: 1 }), Episode.create!({ title: 'Rio Replay: Men''s High Jump Final', synopsis: 'Canada''s Derek Drouin wins gold in men''s high jump in Rio 2016.', serie_id: all_series[34].id, image: File.open('app/assets/images/series/rio/rio-episode-1.jpg'), video_url: 'zW87tVnDKIU', episode_number: 1 }), ] reviews = []; random_reviews = [ "Great movie!", "I'm interested in this movie.", "Why am I laughing so hard?", "I remember the good old days...", "Having a blast watching this while eating my cheetos.", "Someday I'll be a superhero too.", "LOL!", "LMAO!", "Dude... what am I watching?", "Glad that I got through this without shedding a tear.", "When the world ends, I'm going to make sure to hide in a bunker.", "lovely~~~~ :)", "nostalgia at its finest", "this was definitely the main character's finest hour", "dopest movie on the planet!", "IT WAS LITTTTTT", "good old times", "When did this movie first come out?", "stressed...", "im 18 and i love cartoons - give me some of those saturday morning cartoons", "I feel like a kid again.", "giddy up horsey!", "This needs a sequel ASAP", "My mind is running with the rap lyrics from Tupac's Changes", "HILARIOUS. OMG.", "CineFlix is the greatest site in the nation", "You guys at CineFlix better work harder... Netflix is catching up!", "This stuff cracks me up", "Lame brains", "I am writing this without any thoughts going on in my head.", "Actually, writing these reviews are making me quite nostalgic", "Goodness, I laughed and my breath stinks.", "Ballin on the streets every day. Go hard or go home.", "I wish I worked harder when I was younger...", "I wish I started programming at an earlier age...", "Thank you so much for CINEFLIX!", "I'm getting sleepy.", "YAWN", "My father always told me to believe in myself. Today, I do.", "53 years old here and I cannot get over how beautiful movies have become. Oh joy.", "WOOT", "The ChainSmokers told me that we ain't never gettin older. I feel older everyday.", "Buzzzzzzz lightyear please come in star command.", "Duck duck goose was my favorite game back in the day.", "When I grow up, I want to become like SuperGirl. NOT Superman.", "I LOVE WENDYS MORE THAN MCDONALDS.", "Some day I am going to meet Kobe and he will tell me that I am the best baller he has ever seen.", "Do people even read these reviews?", "Shake shack or In-N-Out? The great debate.", "Hassan told me to write this.", "My life is brilliant, my love is pure. I saw an angel of that I am definitely sure.", "wake me up when 2017 ends.", "I need a soda.", "Life ain't easy sometimes, but we just gotta stay in line.", "Okay. This movie was absolutely amazing. The cinematography reminds me of traditional East Asian movies from the 1970s.", "What...", "Amazing", "WOW", "So cool", "That was incredible", "4K is so cool", "I love this tv show", "Meh...", "Sometimes when I sit and watch TV, I think of my ex-girlfriend", "WOOHOO!", "Cineflix... cineflix... CINEFLIX!!!!", "Star wars or Legos?", "I'm going to the gym now... anyone wanna come with?", "I like to wash my hands after I watch movies... mostly because I eat a lot of popcorn", "MMMMmmmmmmmm POPCORN", "I need a soda.", "Life ain't easy sometimes, but we just gotta stay in line.", "Okay. This movie was absolutely amazing. The cinematography reminds me of traditional East Asian movies from the 1970s.", "What...", "Amazing", "WOW", "So cool", "That was incredible", "4K is so cool", "I love this tv show", "Meh...", "Sometimes when I sit and watch TV, I think of my ex-girlfriend", "WOOHOO!", "Cineflix... cineflix... CINEFLIX!!!!", "Star wars or Legos?", "I'm going to the gym now... anyone wanna come with?", "I like to wash my hands after I watch movies... mostly because I eat a lot of popcorn", ]; 200.times do serie_id = all_series[rand(36)].id user_id = all_users[rand(20)].id rating = rand(1..5) body = random_reviews.sample review = Review.new({ serie_id: serie_id, user_id: user_id, rating: rating, body: body }) reviews.push(review) if review.save end
class AddOneTimeFeeToService < ActiveRecord::Migration def change add_column :services, :one_time_fee, :boolean end end
class StaticPagesController < ApplicationController def index @header = true @nowrap = true end def show render template: "static_pages/#{params[:page]}" end end
require "rails_helper" describe "Cart Items" do it "can't have a negative quantity" do cart_item = CartItem.new(1, -5) expect(cart_item.quantity).to be >= 0 end end
# Numbers to Commas Solo Challenge # I spent 2.5 hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented in the file. # 0. Pseudocode # What is the input? # A positive integer # What is the output? (i.e. What should the code return?) # a comma-separated integer as a string # What are the steps needed to solve the problem? # convert integer into string # reverse string # set index counter variable to 0 # UNTIL index counter minus one is greater than string length # => See if there exists a number at index counter plus three # => IF true # => Insert a comma at index counter + 3 # => add four to counter # => IF false # => reverse string # return string # END # 1. Initial Solution def separate_comma(integer) answer_string = integer.to_s answer_string = answer_string.reverse counter_index = 0 until (counter_index + 1) == answer_string.length if answer_string[counter_index + 3] != nil answer_string = answer_string[0..(counter_index + 2)] << "," << answer_string[(counter_index + 3)..-1] counter_index += 4 #puts answer_string.reverse else break end end answer_string = answer_string.reverse return answer_string end # 2. Refactored Solution def separate_comma(integer) answer_string = integer.to_s.reverse index_counter = 0 while answer_string[index_counter + 3] != nil answer_string.insert((index_counter + 3), ",") index_counter += 4 end return answer_string.reverse end # 3. Reflection # My process is usually to sketch the problem like a flow chart. Each operation/method/question/definition is a bubble, and bubbles branch off and join others and loop. That helps me think about flow control and looping. I was debating whether to use the each_char method instead of using indices as variables. And I really really debated whether I should use the reverse method on the string, instead of inserting commas into the string from left to right. I took the solution I did because I felt that it was less likely to mess with the indexes and order. # My Pseudocode did help me. My initial solution was a more or less direct transcriptions of the pseudocode. I had to struggle with the combination of until and if loops, but it worked. My goal was that my code could run on the longest numbers, far longer than the spec tests specify. # I'll be honest, I didn't review the instructions as closely as I could have. Specifically, the part that directed me not to look up Ruby docs until I was refactoring. I looked at the docs while I was coding, found the insert method, and used it in the first version of my code. Just now, I went back and rewrote line 38 to incorporate the only other way I could think of to add a comma. A self punishment. And so I must conclude that insert was the best find I made, because line 38 is too long. # I initially had a loop that basically said "while true", and a nested if statement whose else condition was just "break". # I do think my refactored solution is more readable. It isn't redundant (most egregious is that I basically have a "while true" above a conditional), and I feel good about changing the name of the variable, because I feel the name in the refactored version is better.
class IncomingWebhooksController < ApplicationController skip_before_action :authenticate before_action :set_integration before_action :set_app before_action :set_user def invoke case params[:command] when 'update_app_configs' update_configs('App', @app.id, params[:configs].permit!.to_h) when 'update_device_configs' device = @user.devices.find_by_name!(params[:device]) update_configs('Device', device.id, params[:configs].permit!.to_h) else raise ActionController::BadRequest.new(), "unknown command" end head :ok end private def set_integration @integration = Integration.lookup_by_token(params[:token]) unless @integration head :forbidden return end end def set_app @app = @integration.app end def set_user @user ||= @app.user end def update_configs(owner_type, owner_id, configs) unless configs.is_a?(Hash) raise ActionController::BadRequest.new(), "`configs' must be a object'" end ActiveRecord::Base.transaction do configs.each do |key, value| config = Config.where(owner_type: owner_type, owner_id: owner_id, key: key).first_or_create config.data_type = determine_data_type(value) config.value = value config.save! end end end private def determine_data_type(value) case value when String then 'string' when TrueClass, FalseClass then 'bool' when Float then 'float' when Integer then 'integer' else raise 'unknown data type' end end end
# represent skill class SkillLancer include Mongoid::Document include Mongoid::Timestamps store_in database: 'sribulancer_development', collection: 'skills' include Elasticsearch::Model field :name validates :name, presence: true, :uniqueness => {:scope => :online_group_category_id} validates :online_group_category, presence: true belongs_to :online_group_category has_and_belongs_to_many :members has_many :member_skills def as_indexed_json(options={}) self.as_json( only: [:name], include: { online_group_category: { only: [:cname, :name] } } ) end def self.popular_skills popular = [ "Article Writing", "Copywriting", 'Blog Writing', 'Creative Writing', "Adobe Photoshop", "CorelDRAW", "Logo Design", "Graphic Design", "PHP", "Website Design", "HTML", "Website Development", "Microsoft Excel", "MS Word", "E-mail Handling", "Social Media Marketing", "Internet Marketing", "Translation Japanese to Indonesian", "Translation Indonesian to Japanese", "Mobile Web Development" ] SkillLancer.in(name: popular) end end
RSpec.describe Hash do # subject { {} } = let(:subject) { {} } # Whatever returns from the block becomes the subject subject(:subject_hash) do {a: 1, b: 2} end it 'has 2 keyvalue pairs' do expect(subject.length).to eq(2) expect(subject_hash.length).to eq(2) end context 'nested' do subject do {a: 1} end it 'inner can change and access outer' do expect(subject.length).to eq(1) expect(subject_hash.length).to eq(2) end end end
class Asteroids::BulletComponent include Gamey::Component attr_accessor :timer def initialize @timer = Gamey::Timer.new end end
require 'rspec/core/formatters/progress_formatter' require 'redis' require 'json' module RSpecPubsub class Formatter < RSpec::Core::Formatters::ProgressFormatter attr_reader :channel def initialize(output) super @channel = Channel.new end def start(example_count) super publish_status end def example_passed(example) super publish_status end def example_pending(example) super publish_status end def example_failed(example) super publish_status end private def status { :total_example_count => example_count, :run_example_count => run_example_count, :failure_count => failure_count, :pending_count => pending_count, :percent_complete => percent_complete } end def run_example_count examples.length end def failure_count failed_examples.length end def pending_count pending_examples.length end def percent_complete begin ((run_example_count / example_count.to_f ) * 100).to_i rescue FloatDomainError 0 end end def publish_status channel.publish(status) end end class Channel attr_reader :redis class << self attr_writer :channel_name def channel_name @channel_name || "pubsub_formatter" end end def initialize @redis = Redis.new end def publish(status) redis.publish(self.class.channel_name, status.to_json) end end end
require 'rubygems' require 'sinatra' require 'pry' set :sessions, true BLACKJACK_AMOUNT = 21 DEALER_MIN_HIT = 17 INITIAL_BET_AMOUNT = 500 helpers do def get_total(hand) total = 0 arr = hand.map{|element| element[1]} arr.each do |value| if value == 'ace' total < 11 ? total += 11 : total += 1 else total += (value.to_i == 0 ? 10 : value) end end total end def deal_card(hand, deck) hand << deck.shift end def initial_deal(hand, deck) 2.times do deal_card(hand, deck) end end def card_image(card) "<img src='/images/cards/#{card[0]}_#{card[1]}.svg' class='card'>" end def hide_play_again if session[:player_money] == 0 return true end end def winner!(msg) @show_buttons = false @reveal = true @message = "#{session[:player_name]} wins! #{msg}" session[:player_score] += 1 session[:player_money] += session[:bet_amount] end def loser!(msg) @show_buttons = false @reveal = true @message = "#{session[:player_name]} loses. #{msg}" session[:dealer_score] += 1 session[:player_money] -= session[:bet_amount] hide_play_again end def tie!(msg) @show_buttons = false @reveal = true @message = "Nobody wins - it's a draw. #{msg}" hide_play_again end end before do @show_buttons = true end get '/' do if session[:player_name] redirect '/game' else redirect '/get_name' end end get '/get_name' do erb :get_name end post '/get_name' do if params[:player_name].empty? @problem = true halt erb :get_name end @legal_chars = [] "a".upto("z") {|c| @legal_chars << c} params[:player_name].each_char do |c| if !@legal_chars.include? c.downcase @problem = true halt erb :get_name end end session[:player_name] = params[:player_name].capitalize session[:player_score] = 0 session[:dealer_score] = 0 session[:player_money] = INITIAL_BET_AMOUNT redirect '/bet' end get '/bet' do session[:bet_amount] = nil erb :bet_amount end post '/bet' do if params[:bet_amount].empty? || params[:bet_amount].to_i == 0 @problem = true halt erb :bet_amount elsif params[:bet_amount].to_i > session[:player_money] @problem = true halt erb :bet_amount else session[:bet_amount] = params[:bet_amount].to_i redirect '/game' end end get '/game' do @suits = ['hearts', 'clubs', 'diamonds', 'spades'] @cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king', 'ace'] @player_turn = 'initial' session[:deck] = @suits.product(@cards).shuffle! session[:player_hand] = [] session[:dealer_hand] = [] initial_deal(session[:player_hand], session[:deck]) initial_deal(session[:dealer_hand], session[:deck]) player_total = get_total(session[:player_hand]) dealer_total = get_total(session[:dealer_hand]) if player_total == BLACKJACK_AMOUNT winner!("You've got Blackjack!") elsif dealer_total == BLACKJACK_AMOUNT loser!("Sorry, but the dealer wins with Blackjack.") elsif dealer_total == BLACKJACK_AMOUNT && player_total == BLACKJACK_AMOUNT tie!("The dealer also had #{dealer_total}.") end erb :game end post '/game/player/hit' do deal_card(session[:player_hand], session[:deck]) player_total = get_total(session[:player_hand]) @player_turn = 'hit' if player_total == BLACKJACK_AMOUNT winner!("You've got Blackjack!") elsif player_total > BLACKJACK_AMOUNT loser!("Sorry, looks like you busted.") end erb :game, layout: false end post '/game/player/stay' do redirect '/game/dealer' end get '/game/dealer' do @player_turn = 'stay' player_total = get_total(session[:player_hand]) while get_total(session[:dealer_hand]) < DEALER_MIN_HIT deal_card(session[:dealer_hand], session[:deck]) # @delay still reveals dealer's first card but sets a delay # if not set reveal class automatically set in template @delay = true end dealer_total = get_total(session[:dealer_hand]) if dealer_total == BLACKJACK_AMOUNT loser!("Sorry, but the dealer wins with Blackjack.") elsif dealer_total > BLACKJACK_AMOUNT winner!("The dealer busted with #{dealer_total}!") else #compare scores if dealer_total > player_total loser!("Sorry, the dealer wins with #{dealer_total}.") elsif player_total > dealer_total winner!("The dealer loses with #{dealer_total}!") elsif player_total == dealer_total tie!("The dealer also had #{dealer_total}.") end end erb :game end
FactoryGirl.define do factory :location do |f| library_system_id LibrarySystem::MINUTEMAN.id sequence(:name) {|n| "location #{n}"} end end
require 'rails' module SimpleCalendar class Calendar delegate :capture, :concat, :content_tag, :link_to, :params, :raw, :safe_join, to: :view_context attr_reader :block, :events, :options, :view_context, :timezone def initialize(view_context, opts={}) @view_context = view_context @events = opts.delete(:events) { [] } @timezone = opts.fetch(:timezone, Time.zone) opts.reverse_merge!( header: {class: "calendar-header"}, previous_link: default_previous_link, title: default_title, next_link: default_next_link, td: default_td_classes, thead: default_thead, ) @options = opts end def render(block) @block = block capture do concat render_header concat render_table end end def render_header capture do content_tag :header, get_option(:header) do concat get_option(:previous_link, param_name, date_range) concat get_option(:title, start_date) concat get_option(:next_link, param_name, date_range) end end end def render_table content_tag :table, get_option(:table) do capture do concat get_option(:thead, date_range.to_a.slice(0, 7)) concat content_tag(:tbody, render_weeks, get_option(:tbody)) end end end def render_weeks capture do date_range.each_slice(7) do |week| concat content_tag(:tr, render_week(week), get_option(:tr, week)) end end end def render_week(week) results = week.map do |day| content_tag :td, get_option(:td, start_date, day) do block.call(day, events_for_date(day)) end end safe_join results end def param_name @param_name ||= options.fetch(:param_name, :start_date) end def events_for_date(current_date) if events.any? # First try to see if event spans over a date range (event_start_date..event_end_date) # then sort events selected by start date. # Warning: it may result that period with _same_ start date are *not* ordered by end date! # If :simple_calendar_range_date is not found then we try to find if event responds to # simple_calendar_range_time, then :simple_calendar_start_time (single date events), # else events is passed as is. case when events.first.respond_to?(:simple_calendar_range_date) events.select do |e| e.send(:simple_calendar_range_date).cover? current_date end.sort_by { |e| e.send(:simple_calendar_range_date).begin} when events.first.respond_to?(:simple_calendar_range_time) events.select do |e| e.send(:simple_calendar_range_time).cover? current_date end.sort_by { |e| e.send(:simple_calendar_range_time).begin} when events.first.respond_to?(:simple_calendar_start_time) events.select do |e| current_date == e.send(:simple_calendar_start_time).in_time_zone(@timezone).to_date end.sort_by(&:simple_calendar_start_time) else events end else events end end def default_previous_link ->(param, date_range) { link_to raw("&laquo;"), param => date_range.first - 1.day } end def default_title ->(start_date) { } end def default_next_link ->(param, date_range) { link_to raw("&raquo;"), param => date_range.last + 1.day } end def default_thead ->(dates) { content_tag(:thead) do content_tag(:tr) do capture do dates.each do |date| concat content_tag(:th, I18n.t(options.fetch(:day_names, "date.abbr_day_names"))[date.wday]) end end end end } end def start_date @start_date ||= (get_option(:start_date) || params[param_name] || timezone.now).to_date end def date_range @date_range ||= begin number_of_days = options.fetch(:number_of_days, 4) - 1 start_date..(start_date + number_of_days.days) end end def default_td_classes ->(start_date, current_calendar_date) { today = timezone.now.to_date td_class = ["day"] td_class << "today" if today == current_calendar_date td_class << "past" if today > current_calendar_date td_class << "future" if today < current_calendar_date td_class << 'start-date' if current_calendar_date.to_date == start_date.to_date td_class << "prev-month" if start_date.month != current_calendar_date.month && current_calendar_date < start_date td_class << "next-month" if start_date.month != current_calendar_date.month && current_calendar_date > start_date td_class << "current-month" if start_date.month == current_calendar_date.month td_class << "wday-#{current_calendar_date.wday.to_s}" td_class << "has-events" if events_for_date(current_calendar_date).any? { class: td_class.join(" ") } } end def get_option(name, *params) option = options[name] case option when Hash option else option.respond_to?(:call) ? option.call(*params) : option end end end end
Rails.application.routes.draw do resources :cards root 'cards#index' end
require 'rspec' require_relative '../lib/ruby_js_html_wrapper/html_document' require_relative '../lib/ruby_js_html_wrapper/bar_chart' describe 'Bar Chart' do let(:file) do File.join('barcharttest.html') end let(:barchart) do arr = [ {:name=> 'Rcompute', :data => [360] } , {:name => 'CPPcompute', :data => [40] } ] Wrapper::BarChart.new('test barchart','my yaxis title','seconds',arr) end it 'should generate html doc with bar chart' do arrSubDocs = Array.new arrSubDocs << barchart doc = Wrapper::Html_Document.new(false,arrSubDocs) doc.save file arr = File.readlines(file).grep(/test barchart/) expect(arr.size).to_not eq(0) end after :each do FileUtils.remove file end end
#!/usr/bin/ruby require 'json' require 'lib/homologenie/species_gene' module HomoloGenie class SpeciesPair # TODO initialize MUST be SpeciesGene object??? #parameters must be SpeciesGene object???? attr_reader :score #attr_reader :pair def initialize(species_a, species_b, score = 0) @pair = [species_a, species_b] @score = score end #def def set_score(new_score) @score = new_score end #def #if species pair already exists def exists?(species_a, species_b) if ( @pair[0] == species_a && @pair[1] == species_b ) || \ ( @pair[0] == species_b && @pair[1] == species_a ) return 1 end #if return nil end #def #if test_score is a better score def higher_score?(test_score) if test_score > @score return 1 end #if return nil end #def def to_json(*obj) { "json_class" => self.class.name, "data" => {"pair" => @pair, "score" => @score } }.to_json(*obj) end def self.json_create(obj) new(obj["data"]["pair"], obj["data"]["score"]) end end #class end #module
class EvalNginxModule < Formula desc "Evaluate memcached/proxy response into vars" homepage "https://github.com/vkholodkov/nginx-eval-module" url "https://github.com/vkholodkov/nginx-eval-module/archive/1.0.3.tar.gz" sha256 "849381433a9020ee1162fa6211b047369fde38dc1a8b5de79f03f8fff2407fe2" bottle :unneeded def install pkgshare.install Dir["*"] end end
# Be sure to restart your server when you modify this file. # # Points are a simple integer value which are given to "meritable" resources # according to rules in +app/models/merit/point_rules.rb+. They are given on # actions-triggered, either to the action user or to the method (or array of # methods) defined in the +:to+ option. # # 'score' method may accept a block which evaluates to boolean # (recieves the object as parameter) module Merit class PointRules include Merit::PointRulesMethods def initialize score 50, :on => 'registrations#create', model_name: "User" # Give points to research topic authors that get upvoted score 25, :on => 'votes#vote', :to => [:research_topic_author] do |vote| vote.research_topic.present? && (vote.rating > 0) end score 20, :on => 'research_topics#create' score 10, :on => 'comments#create' # Add points for every badge awarded? How? # Add some scoring here for data points that come from their connected devices, etc. # Add some scoring here for surveys that are anwered, longitudinal # Add some scoring here for surveys (freqent) that are done freq end end end
require 'sumac' # make sure it exists describe Sumac::Messenger do def build_messenger connection = instance_double('Sumac::Connection') messenger = Sumac::Messenger.new(connection) end # ::new example do connection = instance_double('Sumac::Connection') messenger = Sumac::Messenger.new(connection) expect(messenger.instance_variable_get(:@connection)).to be(connection) expect(messenger.instance_variable_get(:@ongoing)).to be(true) expect(messenger).to be_a(Sumac::Messenger) end # #close example do messenger = build_messenger connection = messenger.instance_variable_get(:@connection) message_broker = double expect(connection).to receive(:message_broker).with(no_args).and_return(message_broker) expect(message_broker).to receive(:close).with(no_args) messenger.close end # #closed example do messenger = build_messenger messenger.instance_variable_set(:@ongoing, true) messenger.closed expect(messenger.instance_variable_get(:@ongoing)).to be(false) end # #closed? example do messenger = build_messenger expect(messenger.closed?).to be(messenger.instance_variable_get(:@ongoing)) end # #kill example do messenger = build_messenger connection = messenger.instance_variable_get(:@connection) message_broker = double expect(connection).to receive(:message_broker).with(no_args).and_return(message_broker) expect(message_broker).to receive(:kill).with(no_args) messenger.kill end # #send example do messenger = build_messenger message = instance_double('Sumac::Messages::CallRequest') message_string = double expect(message).to receive(:to_json).and_return(message_string) connection = messenger.instance_variable_get(:@connection) message_broker = double expect(connection).to receive(:message_broker).with(no_args).and_return(message_broker) expect(message_broker).to receive(:send).with(message_string) messenger.send(message) end # #setup example do messenger = build_messenger connection = messenger.instance_variable_get(:@connection) message_broker = double expect(connection).to receive(:message_broker).with(no_args).and_return(message_broker) object_request_broker = double expect(connection).to receive(:object_request_broker).with(no_args).and_return(object_request_broker) expect(message_broker).to receive(:object_request_broker=).with(object_request_broker) messenger.setup end # #validate_message_broker # missing #close example do messenger = build_messenger connection = messenger.instance_variable_get(:@connection) message_broker = instance_double('Object') expect(connection).to receive(:message_broker).with(no_args).and_return(message_broker) expect(message_broker).to receive(:respond_to?).with(:close).and_return(false) expect{ messenger.validate_message_broker }.to raise_error(TypeError, /#close/) end # missing #kill example do messenger = build_messenger connection = messenger.instance_variable_get(:@connection) message_broker = instance_double('Object') expect(connection).to receive(:message_broker).with(no_args).and_return(message_broker) expect(message_broker).to receive(:respond_to?).with(:close).and_return(true) expect(message_broker).to receive(:respond_to?).with(:kill).and_return(false) expect{ messenger.validate_message_broker }.to raise_error(TypeError, /#kill/) end # missing #object_request_broker= example do messenger = build_messenger connection = messenger.instance_variable_get(:@connection) message_broker = instance_double('Object') expect(connection).to receive(:message_broker).with(no_args).and_return(message_broker) expect(message_broker).to receive(:respond_to?).with(:close).and_return(true) expect(message_broker).to receive(:respond_to?).with(:kill).and_return(true) expect(message_broker).to receive(:respond_to?).with(:object_request_broker=).and_return(false) expect{ messenger.validate_message_broker }.to raise_error(TypeError, /#object_request_broker=/) end # missing #send example do messenger = build_messenger connection = messenger.instance_variable_get(:@connection) message_broker = instance_double('Object') expect(connection).to receive(:message_broker).with(no_args).and_return(message_broker) expect(message_broker).to receive(:respond_to?).with(:close).and_return(true) expect(message_broker).to receive(:respond_to?).with(:kill).and_return(true) expect(message_broker).to receive(:respond_to?).with(:object_request_broker=).and_return(true) expect(message_broker).to receive(:respond_to?).with(:send).and_return(false) expect{ messenger.validate_message_broker }.to raise_error(TypeError, /#send/) end # valid example do messenger = build_messenger connection = messenger.instance_variable_get(:@connection) message_broker = instance_double('Object') expect(connection).to receive(:message_broker).with(no_args).and_return(message_broker) expect(message_broker).to receive(:respond_to?).with(:close).and_return(true) expect(message_broker).to receive(:respond_to?).with(:kill).and_return(true) expect(message_broker).to receive(:respond_to?).with(:object_request_broker=).and_return(true) expect(message_broker).to receive(:respond_to?).with(:send).and_return(true) messenger.validate_message_broker end end
class VenuesController < ApplicationController respond_to :js, :json, :html def index respond_with(@venues = Venue.includes(:options).all) end def show @venue = Venue.includes(:options).find(params[:id]) build_option respond_with(@venue) end alias :edit :show def create respond_with(@venue = Venue.new(params[:venue])) end def update params[:venue][:option_ids] ||= [] @venue = Venue.includes(:options).find(params[:id]) @venue.update_attributes(params[:venue]) respond_with(@venue) end private def new_venue @new_venue ||= Venue.new build_option(@new_venue) @new_venue end helper_method :new_venue def all_venues @all_venues ||= Venue.includes(:options).all end helper_method :all_venues def all_options @all_options ||= Option.includes(:venues).all end helper_method :all_options def build_option(venue = @venue) venue.options.build end end
# encoding: UTF-8 require 'helper' class TestTranslation < Test::Unit::TestCase def test_any_i18n_chronic_errors_message_with_interpolation key = "a key" string = I18n.t(:not_valid_key, key: key, scope: 'chronic.errors') assert_equal string, "a key is not a valid option key." end def test_a_i18n_chronic_errors_message_with_diacritic_letter key = "รฆรธรฅ" string = I18n.t(:fรธrste, key: key, scope: 'chronic.tests') assert_equal string, "รฆรธรฅ is not a valid option key." end end
module Types class AreaType < LocationType field :path, String, null: false, method: :map_path field :url, String, null: false, method: :map_url field :radius, Float, null: false field :region, Types::RegionType, null: false field :country, Types::CountryType, null: false field :events, [Types::EventType], null: false field :event_ids, [ID], null: false field :online_event_ids, [ID], null: false field :offline_event_ids, [ID], null: false def events object.events.publicly_visible.map { |event| event.extend(EventDecorator) } end def event_ids object.events.publicly_visible.pluck(:id) end def online_event_ids object.events.online.publicly_visible.pluck(:id) end def offline_event_ids object.events.offline.publicly_visible.pluck(:id) end def region object.region.extend(RegionDecorator) end def country object.country.extend(CountryDecorator) end end end