text
stringlengths
10
2.61M
require 'spec_helper' describe file('/opt/stager') do it { should be_directory } end describe file('/etc/nginx/sites-enabled') do it { should be_directory } it { should be_owned_by 'root' } it { should be_grouped_into 'docker' } it { should be_mode 775 } end # services we expect to be runnning stager_services = ['stager', 'nginx'] stager_services.each do |s| describe service(s) do it { should be_running } end end
#!/usr/bin/env ruby require 'rubygems' require 'monkeyshines' require 'monkeyshines/runner' require 'pathname' # # # require 'wuclan/twitter' # un-namespace request classes. include Wuclan::Twitter::Scrape Monkeyshines::WORK_DIR = '/tmp' WORK_DIR = Pathname.new(Monkeyshines::WORK_DIR).realpath.to_s # =========================================================================== # # scrape_shorturls.rb -- # # To scrape from a list of shortened urls: # # ./shorturl_random_scrape.rb --from-type=FlatFileStore --from=request_urls.tsv # # To do a random scrape: # # ./shorturl_random_scrape.rb --from-type=RandomUrlStream --base-url=tinyurl.com # --base-url="http://tinyurl.com" --min-limit= --max-limit= --encoding_radix= # # opts = Trollop::options do opt :log, "Log to file instead of STDERR" # input from file opt :from, "URI for scrape store to load from", :type => String opt :skip, "Initial lines to skip", :type => Integer # output storage opt :cache_uri, "URI for cache server", :type => String, :default => ':1978' opt :chunk_time, "Frequency to rotate chunk files (in seconds)", :type => Integer, :default => 60*60*4 opt :dest_dir, "Filename base to store output. default ./work/ripd", :default => WORK_DIR+'/ripd' opt :dest_pattern, "Pattern for dump file output", :default => ":dest_dir/:date/:handle+:timestamp-:pid.tsv" opt :into, "URI for scrape store into", :type => String end opts[:handle] ||= 'com.twitter' scrape_config = YAML.load(File.open(ENV['HOME']+'/.monkeyshines')) opts.merge! scrape_config # ******************** Log ******************** if (opts[:log]) opts[:log] = (WORK_DIR+'/log/'+File.basename(opts[:from],'.tsv')) $stdout = $stderr = File.open(opts[:log]+"-console.log", "a") end # # Execute the scrape # scraper = Monkeyshines::Runner.new( :dest_store => { :type => :conditional_store, :cache => { :type => :tyrant_rdb_key_store, :uri => opts[:cache_uri] }, :store => opts.merge({ :type => :chunked_flat_file_store }), }, # :store => { :type => :flat_file_store, :filename => opts[:into] }, }, :request_stream => { :type => :base, :klass => Monkeyshines::ScrapeRequest, :store => { :type => :flat_file_store, :filemode => 'r', :filename => opts[:from] } } ) scraper.run
Shows list page: *list of Shows As a user, when I visit home page, see list of shows. Each show should include Show Name and Show Picture. As an admin, on home page, 'add show' button click 'add show' button, new page Fill in how Name and Show Picture and click submit, success message. Then I visit home page, I should see new show. As an admin, on home page, 'edit show' button click 'edit show' button, new page Fill in how Name and Show Picture and click submit, success message. Then I visit home page, I should see edited show. As a user, when I visit home page, see list of shows. When I click on the 'Show Episodes', then I am taken to the Episodes Page. Episode list page: *list of episodes *click to see details Episode Detail page: *be able to watch episode
class AddStripeCardTokenToDonation < ActiveRecord::Migration def change add_column :donations, :card_token, :string end end
class BulkApiImport::Validator def initialize(organization:, resources:) @organization = organization @params = resources end def validate error = validate_schema unless error.present? error = validate_facilities end error end def validate_schema schema_errors = JSON::Validator.fully_validate( Api::V4::Imports.schema_with_definitions, @params.to_json ) {schema_errors: schema_errors} if schema_errors.present? end def validate_facilities facility_ids = [ *patient_resource_facilities, *appointment_resource_facilities, *observation_resource_facilities, *medication_request_resource_facilities ] found_facilities = FacilityBusinessIdentifier .joins(facility: :facility_group) .where(facility_business_identifiers: {identifier: facility_ids}, facility_groups: {organization_id: @organization}) .pluck(:identifier) unknown_facilities = facility_ids - found_facilities {invalid_facility_error: "found unmapped facility IDs: #{unknown_facilities}"} if unknown_facilities.present? end def patient_resource_facilities resources_by_type[:patient]&.flat_map do |resource| [resource.dig(:registrationOrganization, 0, :value), resource.dig(:managingOrganization, 0, :value)] end&.compact&.uniq end def appointment_resource_facilities resources_by_type[:appointment]&.flat_map do |resource| [resource.dig(:appointmentOrganization, :identifier), resource.dig(:appointmentCreationOrganization, :identifier)] end&.compact&.uniq end def observation_resource_facilities resources_by_type[:observation]&.map do |resource| resource[:performer][0][:identifier] end&.compact&.uniq end def medication_request_resource_facilities resources_by_type[:medication_request]&.map do |resource| resource[:performer][:identifier] end&.compact&.uniq end private def resources_by_type @resources_by_type ||= @params.group_by { |resource| resource[:resourceType].underscore.to_sym } end end
class CreateQuestions < ActiveRecord::Migration[6.0] def change create_table :questions do |t| t.integer :philosophy_id , null: false t.integer :color_id , null: false t.integer :my_type_id , null: false t.integer :like_type_id , null: false t.integer :prefecture_id , null: false t.integer :food_id , null: false t.integer :hobby_id , null: false t.integer :music_id , null: false t.integer :angry_id , null: false t.integer :improve_id , null: false t.text :text t.references :user t.timestamps end end end
class UserMap include MongoMapper::Document key :value, Integer ensure_index :_id end
module SNMP4EM # Returned from SNMP4EM::SNMPv1.set(). This implements EM::Deferrable, so you can hang a callback() # or errback() to retrieve the results. class SnmpSetRequest < SnmpRequest attr_accessor :snmp_id # For an SNMP-SET request, @pending_varbinds will by an SNMP::VarBindList, initially populated from the # provided oids hash. Variables can be passed as specific types from the SNMP library (i.e. SNMP::IpAddress) # or as ruby native objects, in which case they will be cast into the appropriate SNMP object. As responses # are returned, the @pending_varbinds object will be pruned of any error-producing varbinds. Once no errors # are produced, the @responses object is populated and returned. def initialize(sender, oids, args = {}) #:nodoc: _oids = [*oids] @sender = sender @timeout_timer = nil @timeout_retries = @sender.retries @error_retries = _oids.size @return_raw = args[:return_raw] || false @responses = Hash.new @pending_varbinds = SNMP::VarBindList.new() _oids.each_pair do |oid,value| if value.is_a? Integer snmp_value = SNMP::Integer.new(value) elsif value.is_a? String snmp_value = SNMP::OctetString.new(value) end @pending_varbinds << SNMP::VarBind.new(oid,snmp_value) end init_callbacks send end def handle_response(response) #:nodoc: if (response.error_status == :noError) # No errors, set any remaining varbinds to true response.each_varbind do |vb| response_vb = @pending_varbinds.shift @responses[response_vb.name.to_s] = true end else # Got an error, remove that varbind from @pending_varbinds so we can try again error_vb = @pending_varbinds.delete_at(response.error_index - 1) @responses[error_vb.name.to_s] = SNMP::ResponseError.new(response.error_status) end if (@pending_varbinds.empty? || @error_retries.zero?) until @pending_varbinds.empty? error_vb = @pending_varbinds.shift @responses[error_vb.name.to_s] = SNMP::ResponseError.new(:genErr) end unless @return_raw @responses.each_pair do |oid, value| @responses[oid] = value.rubify if value.respond_to?(:rubify) end end # Send the @responses back to the requester, we're done! succeed @responses else @error_retries -= 1 send end end private def send Manager.track_request(self) # Send the contents of @pending_varbinds vb_list = SNMP::VarBindList.new(@pending_varbinds) request = SNMP::SetRequest.new(@snmp_id, vb_list) message = SNMP::Message.new(@sender.version, @sender.community_ro, request) super(message) end end end
FactoryGirl.define do factory :treatment do patient doctor treatment_type sequence(:medicine) { |n| "medicine#{n}" } start_days 40 end end
# frozen_string_literal: true class MenuSeeds def initialize(db) @db = db @location_ids = @db["SELECT * FROM Restaurants.Locations"].to_a.map { |location| location[:id] } @chef_ids = @db[" SELECT e.id FROM Staff.Employees AS e INNER JOIN Staff.EmployeeLocationRoles AS er ON e.id = er.employeeId INNER JOIN Staff.Roles AS r ON er.roleId = r.id WHERE r.name = 'Executive Chef' "].to_a.map { |employee| employee[:id] } end def run %w[Summer Winter Spring Fall].each do |season| menu_id = create_menu(season) create_menu_locations(menu_id, season) create_menu_dishes(menu_id, season) end end def create_menu(season) menu_params = { name: "#{season} Menu", validFrom: season_start(season), validTo: season_end(season), executiveChefId: @chef_ids.sample, } data_set = @db["INSERT INTO Resources.Menus (name, validFrom, validTo, executiveChefId) VALUES (:name, :validFrom, :validTo, :executiveChefId)", menu_params] data_set.insert end def season_start(season) case season when "Winter" then Date.parse("2023-01-01") when "Summer" then Date.parse("2023-06-01") when "Spring" then Date.parse("2023-03-01") when "Fall" then Date.parse("2023-09-01") end end def season_end(season) case season when "Winter" then Date.parse("2023-02-28") when "Summer" then Date.parse("2023-08-31") when "Spring" then Date.parse("2023-05-31") when "Fall" then Date.parse("2023-12-31") end end def create_menu_locations(menu_id, season) @location_ids.each do |location_id| menu_location_params = { menuId: menu_id, locationId: location_id, validFrom: season_start(season), validTo: season_end(season), } data_set = @db["INSERT INTO Restaurants.LocationMenus (menuId, locationId, validFrom, validTo) VALUES (:menuId, :locationId, :validFrom, :validTo)", menu_location_params] data_set.insert end def create_menu_dishes(menu_id, season) 10.times do menu_dish_params = { menuId: menu_id, dishId: @db["SELECT * FROM Resources.Dishes"].to_a.sample[:id], validFrom: season_start(season), validTo: season_end(season), } data_set = @db["INSERT INTO Resources.MenuDishes (menuId, dishId, validFrom, validTo) VALUES (:menuId, :dishId, :validFrom, :validTo)", menu_dish_params] data_set.insert end end end end
module Net RSpec.describe ICAP do it "has a default port" do expect(ICAP.default_port).to eq 1344 end it "can be instantiated with an address" do icap = ICAP.new 'localhost' expect(icap.address).to eq 'localhost' end it "uses the default ICAP port" do icap = ICAP.new 'localhost' expect(icap.port).to eq 1344 end it "can be instantiated with a port" do icap = ICAP.new 'localhost', 1234 expect(icap.port).to eq 1234 end it "is not started when created" do icap = ICAP.new 'localhost' expect(icap.started?).to be_falsey end it "makes an OPTIONS request" do icap = ICAP.new 'localhost' icap.set_debug_output($stdout) response = icap.request_options 'echo' expect(response).to be_a Net::ICAPOK end it "makes a RESPMOD request" do virus = 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*' icap = ICAP.new 'localhost' icap.set_debug_output($stdout) response = icap.request_respmod 'avscan', virus, { 'encapsulated' => 'res-body=0' } expect(response.body).not_to be_nil end it "makes a RESPMOD request with a preview" do body = "a" * 500 icap = ICAP.new 'localhost' icap.set_debug_output($stdout) response = icap.request_respmod 'avscan', body, { 'encapsulated' => 'res-body=0', 'preview' => '100' } expect(response.body).not_to be_nil end end end
class HashTable attr_accessor :buckets def initialize @buckets = [] end def insert(key, val) index = index_from(key) buckets[index] ||= [] buckets[index] << [key, val] end def index_from(key) key.to_sym.object_id % 100 end def find(key) index = index_from(key) buckets[index].each do |item| return item[1] if item[0] == key end if buckets[index] end end
# frozen_string_literal: true class PageStats attr_reader :page, :total_visits def initialize(page:) @page = page @total_visits = 0 @visitors = Hash.new(0) end def add_visit(visitor:) @total_visits += 1 @visitors[visitor] += 1 end def unique_visits @visitors.size end end
module Misc defaults = { :domain => "clockingit.com", :replyto => "admin", :from => "admin", :prefix => "[ClockingIT]" } $CONFIG ||= { } defaults.keys.each do |k| $CONFIG[k] ||= defaults[k] end $CONFIG[:email_domain] = $CONFIG[:domain].gsub(/:\d+/, '') # Format minutes => <tt>1w 2d 3h 3m</tt> def format_duration(minutes, duration_format, day_duration, days_per_week = 5) res = '' weeks = days = hours = 0 day_duration ||= 480 minutes ||= 0 if minutes >= 60 days = minutes / day_duration minutes = minutes - (days * day_duration) if days > 0 weeks = days / days_per_week days = days - (weeks * days_per_week) if weeks > 0 hours = minutes / 60 minutes = minutes - (hours * 60) if hours > 0 res += "#{weeks}#{_('w')}#{' ' if duration_format == 0}" if weeks > 0 res += "#{days}#{_('d')}#{' ' if duration_format == 0}" if days > 0 res += "#{hours}#{_('h')}#{' ' if duration_format == 0}" if hours > 0 end res += "#{minutes}#{_('m')}" if minutes > 0 || res == '' if( duration_format == 2 ) res = if weeks > 0 format("%d:%d:%d:%02d", weeks, days, hours, minutes) elsif days > 0 format("%d:%d:%02d", days, hours, minutes) else format("%d:%02d", hours, minutes) end elsif( duration_format == 3 ) res = format("%d:%02d", ((weeks * day_duration * days_per_week) + (days * day_duration))/60 + hours, minutes) end res.strip end # Returns an array of languages codes that the client accepts sorted after # priority. Returns an empty array if the HTTP_ACCEPT_LANGUAGE header is # not present. def accept_locales return [] unless request.env.include? 'HTTP_ACCEPT_LANGUAGE' languages = request.env['HTTP_ACCEPT_LANGUAGE'].split(',').map do |al| al.gsub!(/-/, '_') al = al.split(';') (al.size == 1) ? [al.first, 1.0] : [al.first, al.last.split('=').last.to_f] end languages.reject {|x| x.last == 0 }.sort {|x,y| -(x.last <=> y.last) }.map {|x| x.first } end def html_encode(s) s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;") end end class OrderedHash < Hash alias_method :store, :[]= alias_method :each_pair, :each def initialize @keys = [] end def []=(key, val) @keys << key super end def delete(key) @keys.delete(key) super end def each @keys.each { |k| yield k, self[k] } end def each_key @keys.each { |k| yield k } end def each_value @keys.each { |k| yield self[k] } end end
require 'json' require 'open-uri' module Github class Client def self.fetch username new.fetch username end def fetch username records = JSON.parse get username records.each do |record| checksum_from_hash = Digest::MD5.hexdigest Marshal.dump(record) record['checksum'] = checksum_from_hash end records end private # Returns user feed as JSON def get username open("https://github.com/#{username}.json").read end end end
class CreateProviderProfiles < ActiveRecord::Migration def self.up create_table :provider_profiles do |t| t.integer :provider_id, :null => false t.string :user_key, :null => false t.string :name, :null => false t.string :pic_square, :null => false t.string :url, :null => false t.timestamps end add_index :provider_profiles, [:provider_id, :user_key], :name => 'idx_provider_id_user_key_on_provider_profiles', :unique => true end def self.down remove_index :provider_profiles, :name => 'idx_provider_id_user_key_on_provider_profiles' drop_table :provider_profiles end end
require 'rake/testtask' require 'rake/rdoctask' #require 'rake/packagetask' require 'rake/gempackagetask' Rake::TestTask.new 'test' do |t| t.pattern = 'test/**/test*.rb' end spec = Gem::Specification.new do |s| s.summary = "An interface to the Digital NZ public API." s.description = "An interface to the Digital NZ public API. See http://www.digitalnz.org/" s.name = "r4digitalnz" s.author = "Henry Maddocks" s.email = "henry.maddocks@gmail.com" s.homepage = "http://r4digitalnz.rubyforge.org" s.rubyforge_project = "r4digitalnz" s.version = "1.0.1" s.files = FileList["lib/r4digitalnz.rb", "copying.txt", "README", "TODO", "rakefile", "test/*.rb"].to_a s.test_files = FileList["test/*.rb"].to_a s.add_dependency('json', '>=1.1.6') s.add_dependency('activesupport', '>=2.1.0') s.requirements = ['JSON', 'Active Support'] end Rake::RDocTask.new do |rd| rd.rdoc_files.include "README", "lib/flickraw.rb", "TODO" rd.options << "--inline-source" end Rake::GemPackageTask.new spec do |p| p.need_tar_gz = true end task 'default' => ['test']
module Api class EventsController < ApplicationController skip_before_action :authenticate_user! respond_to :json def participant_form event = Event.find_by(unique_id: params[:event_id]) if event event_form_data_presenter = Api::EventFormDataPresenter.new(event) respond_with(event_form_data_presenter, status: :ok) else respond_with({}, status: :not_found) end end end end
%w{ git gcc openssl-devel readline-devel gdbm-devel db4-devel libffi-devel libyaml-devel tk-devel zlib-devel }.each do |pkg| package pkg end rbenv_path = "/home/#{node["rbenv"]["user"]}/.rbenv" plugin_path = "#{rbenv_path}/plugins" rbenv_command = "#{rbenv_path}/bin/rbenv" git rbenv_path do repository node["rbenv"]["repository"] user node["rbenv"]["user"] if node["rbenv"]["user"] not_if File.exists? rbenv_path end template "/etc/profile.d/rbenv.sh" do source "templates/rbenv.sh.erb" variables rbenv_path: rbenv_path end execute "chmod rbenv.sh" do command "chmod 755 /etc/profile.d/rbenv.sh" only_if File.exists? "/etc/profile.d/rbenv.sh" end directory plugin_path do owner node["rbenv"]["user"] group node["rbenv"]["group"] || node["rbenv"]["user"] mode "0755" action :create not_if File.exists? plugin_path end node["rbenv"]["plugins"].each do |plgin| git "#{plugin_path}/#{plgin["name"]}" do repository plgin["repository"] user node["rbenv"]["user"] not_if File.exists? "#{plugin_path}/#{plgin["name"]}" end end node["rbenv"]["versions"].each do |version| execute "Install Ruby v#{version}" do user node["rbenv"]["user"] command "#{rbenv_command} install #{version}" not_if "#{rbenv_command} versions | grep #{version}" end end execute "Set global ruby version #{node["rbenv"]["global_version"]}" do user node["rbenv"]["user"] command "#{rbenv_command} global #{node["rbenv"]["global_version"]}" end
class User < ActiveRecord::Base has_many :time_tickets has_secure_password validates_confirmation_of :password validate :username_not_changed attr_readonly :name validates :name, uniqueness: true private def username_not_changed if name_changed? && self.persisted? errors.add(:name, "Change of name not allowed!") end end end
json.array!(@activities) do |activity| json.extract! activity, :id, :name, :address, :city, :country, :lat, :lng, :days, :hrs, :rating, :description, :cost, :date json.url activity_url(activity, format: :json) end
require 'csv' require 'daru' require 'tmpdir' require 'yquotes/version' require 'yquotes/yahoo' module YQuotes class Client def initialize @yahoo_client = Yahoo.new end # get_quote: returns Daru::DataFrame of the quote with volume and close def get_quote(ticker, args = {}) if args.is_a? Hash start_date = args[:start_date] if args[:start_date] start_date ||= args[:s] if args[:s] end_date = args[:end_date] if args[:end_date] end_date ||= args[:e] if args[:e] period = args[:period] if args[:period] period ||= args[:p] if args[:p] end csv = @yahoo_client.get_csv(ticker, start_date, end_date, period, 'quote') create_quotes_from_csv(csv) end # get_splits: returns Daru::DataFrame of the splits with date and ratio def get_splits(ticker, args = {}) if args.is_a? Hash start_date = args[:start_date] if args[:start_date] start_date ||= args[:s] if args[:s] end_date = args[:end_date] if args[:end_date] end_date ||= args[:e] if args[:e] period = args[:period] if args[:period] period ||= args[:p] if args[:p] end csv = @yahoo_client.get_csv(ticker, start_date, end_date, period, 'splits') create_splits_from_csv(csv) end alias historical_data get_quote alias historical_quote get_quote private def create_splits_from_csv(data) return if Daru::DataFrame.new(date: []) if data.length <= 1 df = create_from_csv(data, 'splits') df.rename_vectors 'Date' => :date, 'Stock Splits' => :splits df end def create_quotes_from_csv(data) return if Daru::DataFrame.new(date: []) if data.length <= 1 df = create_from_csv(data, 'quote') df.rename_vectors 'Date' => :date, 'Volume' => :volume, 'Adj Close' => :adj_close, 'Open' => :open, 'Close' => :close, 'High' => :high, 'Low' => :low d = df.filter(:row) { |row| row[:volume] > 0 } end def create_from_csv(data, prefix) file_path = Dir.tmpdir + "/#{Time.now.to_i}_#{prefix}" CSV.open(file_path, 'w') do |out| data.each do |row| out << row unless row.include? 'null' end end df = nil df = Daru::DataFrame.from_csv(file_path, converters: :numeric) File.delete(file_path) if File.exist?(file_path) # sort from earlier to latest df = df.sort ['Date'], ascending: [false] # strip columns and create index df.index = Daru::Index.new(df['Date'].to_a) df end end end
class Patient < ApplicationRecord belongs_to :user belongs_to :appointment end
require('minitest/autorun') require('minitest/rg') require_relative('../bear.rb') require_relative('../river.rb') require_relative('river_spec.rb') # attr_reader :name :type class BearTest < MiniTest::Test def setup() @bear = Bear.new("Yogi", "Grizzly",[]) @fish_1 = Fish.new("Salmon") @fish_2 = Fish.new("Trout") @fish_3 = Fish.new("Cod") @fish_4 = Fish.new("Tuna") @fish_pool = [@fish_1, @fish_2, @fish_3, @fish_4] @river = River.new("Amazon",@fish_pool) @taken_fish = @fish_pool[0] end def test_bear_name() assert_equal("Yogi", @bear.name()) end def test_bear_type() assert_equal("Grizzly", @bear.type()) end def test_bear_stomach_count() assert_equal(0,@bear.bear_stomach_count()) end def test_bear_take_fish() @bear.bear_take_fish(@river, @taken_fish) # @river.lose_fish() assert_equal(1,@bear.bear_stomach_count()) end def test_bear_roar() assert_equal("Roooaaarrr", @bear.bear_roar()) end end
class Api::V1::RandomInvoicesController < Api::ApiController respond_to :json def show respond_with Invoice.random end end
class RemovePositionFromPhoneBook < ActiveRecord::Migration def up remove_column :phone_books, :position end def down add_column :phone_books, :position, :integer end end
#!/usr/bin/env ruby require 'rubygems' require 'fileutils' require 'thor' require 'yaml' require 'ostruct' class TvClean < Thor include Thor::Actions # -------------------------------------------------------------------------- def initialize(*args) super $config_file = "#{Dir.home}/tvclean_config.yml" configure unless read_config? verify_config end # -------------------------------------------------------------------------- desc "configure", "Set up tvclean", :hide => true def configure puts "To configure this application modify #{$config_file}" exit 1 # prompt(nil, "Please provide the directory where your TV shows reside:") end # -------------------------------------------------------------------------- desc "clean", "cleans the directory" method_option :test, :type => :boolean, :default => false, :aliases => "-t", :desc => "Display extra episodes, does NOT delete" def clean shows_to_work = scrape exit_with_message("Everything is clean") if shows_to_work.empty? shows_to_work.each do |show| to_delete = get_deletions(show) puts "#{to_delete.count} extra episode(s) of #{show.name}" exit 0 if to_delete.empty? unless options.test to_delete.each { |show| File.delete(show.fullpath) } end end end desc "list", "lists tv shows and their episode count" def list items = scrape(true).sort{|x,y| y.video_files.count <=> x.video_files.count}.each do |tv| puts "#{tv.name}: #{tv.video_files.count}" end end no_tasks do # -------------------------------------------------------------------------- def verify_config exit_with_message("Directory does not exist: #{$tv_dir}",1) unless Dir.exists?($tv_dir) end # -------------------------------------------------------------------------- def exit_with_message(message,status=0) puts message exit status end # -------------------------------------------------------------------------- def read_config? return false unless File.exists?($config_file) config = YAML.load_file($config_file) config.each { |key, value| eval("$#{key} = #{value.is_a?(String) ? 'value' : value}") } $configured # this is set in the config file end # -------------------------------------------------------------------------- def prompt(default, question) ask question || default end # -------------------------------------------------------------------------- def scrape unfiltered=false Dir.chdir $tv_dir all = Dir['**'] unless unfiltered $ignores.each do |exp| all.delete_if { |n| n =~ exp } end end to_work = Array.new all.each do |n| fullpath = File.expand_path(n) next unless File.directory?(fullpath) Dir.chdir fullpath do video_files = Dir['**/*'].select { |f| # is a file and is > min_media_size File.file?(f) and (('%.2f' % File.size(f)).to_i / 2**20) > $min_media_size }.map{ |v| File.expand_path(v) } to_work.push(TvShow.new(fullpath, video_files)) if (video_files.count > $episodes_limit) or unfiltered end end to_work end # -------------------------------------------------------------------------- def get_deletions(tvshow) raise ArgumentError, "Not a TvShow" unless tvshow.is_a?(TvShow) episodes = tvshow.video_files.map{ |file| Episode.new(file, tvshow) }.delete_if{ |e| not e.valid? } episodes.sort_by! { |a| [-a.season, -a.episode] } keepers = episodes[0..4] to_delete = episodes - keepers to_delete end default_task :start end end # -------------------------------------------------------------------------- class TvShow def initialize(fullpath, video_files) raise ArgumentError, "fullpath must be a String" unless fullpath.is_a?(String) raise ArgumentError, "video_files must be an array" unless video_files.is_a?(Array) @fullpath = fullpath @name = File.basename(fullpath) @video_files = video_files end def fullpath; @fullpath end def name; @name end def video_files; @video_files end end # -------------------------------------------------------------------------- class Episode def initialize(fullpath, tvshow) raise ArgumentError, "fullpath must be a String" unless fullpath.is_a?(String) raise ArgumentError, "tvshow must be a TvShow" unless tvshow.is_a?(TvShow) @valid = true unless File.basename(fullpath) =~ /[Ss]\d{1,2}[Ee]\d{1,2}/ puts "fullpath (#{fullpath}) is not named with the proper convention (eg. TV.Show.S01E02 or TV.Show.s1e2)" @valid = false end @fullpath = fullpath @tvshow = tvshow @season = File.basename(fullpath)[/([Ss])(\d{1,2})/, 2].to_i @episode = File.basename(fullpath)[/([Ee])(\d{1,2})/, 2].to_i end def fullpath; @fullpath end def tvshow; @tvshow end def season; @season end def episode; @episode end def valid?; @valid end end # Starts the process if this is being used as a script # If this is being used as a library this will be skipped if __FILE__ == $0 TvClean.start end
class UserGroup include Mongoid::Document include Mongoid::Timestamps field :team_id, type: String field :channel_id, type: String field :code, type: String field :last_message_thread, type: String end
require 'test_helper' class Links::Season::BtnPlayerBreakdownTest < ActiveSupport::TestCase test "#site_name" do assert_equal "Behind the Net", Links::Season::BtnPlayerBreakdown.new.site_name end test "#description" do assert_equal "Player Breakdown", Links::Season::BtnPlayerBreakdown.new.description end test "#url" do season = seasons(:fourteen) team = teams(:caps) game_type = "regular" url = "http://www.behindthenet.ca/nhl_statistics.php?ds=29&f1=2014_s&f2=5v5&f5=WSH&c=0+3+4+6+7+8+29+30+31+13+14+15+16+11+12+34+32+33+35+36+17+18+19+20+21+22+25+26+27+28+10+37+38+39+40+47+48+49+50+51+52+53+54+55+56+63+67+57+58+59+60+61+62+64+65+66+41+42+43+44+45+46" link = Links::Season::BtnPlayerBreakdown.new(team: team, season: season, game_type: game_type) assert_equal url, link.url end test "#group" do assert_equal 2, Links::Season::BtnPlayerBreakdown.new.group end test "#position" do assert_equal 0, Links::Season::BtnPlayerBreakdown.new.position end end
require "rails_helper" RSpec.describe Certificate, type: :model do let(:certificate) {FactoryGirl.create :certificate} subject {certificate} context "associations" do it {is_expected.to belong_to :user} end context "validates" do it {is_expected.to validate_presence_of :name} it {is_expected.to validate_length_of(:name).is_at_most(Setting.certificate.maximum)} it {is_expected.to validate_presence_of :majors} it {is_expected.to validate_length_of(:majors).is_at_most(Setting.certificate.maximum)} it {is_expected.to validate_presence_of :organization} it {is_expected.to validate_length_of(:organization).is_at_most(Setting.certificate.maximum)} it {is_expected.to validate_length_of(:classification).is_at_most(Setting.certificate.maximum)} it {is_expected.to validate_presence_of :received_time} end context "columns" do it {is_expected.to have_db_column(:name).of_type(:string)} it {is_expected.to have_db_column(:majors).of_type(:string)} it {is_expected.to have_db_column(:organization).of_type(:string)} it {is_expected.to have_db_column(:classification).of_type(:string)} it {is_expected.to have_db_column(:received_time).of_type(:date)} it {is_expected.to have_db_column(:user_id).of_type(:integer)} end context "when name is not valid" do before {subject.name = ""} it "matches the error message" do subject.valid? subject.errors[:name].should include("can't be blank") end end context "when majors is not valid" do before {subject.majors = ""} it "matches the error message" do subject.valid? subject.errors[:majors].should include("can't be blank") end end context "when organization is not valid" do before {subject.organization = ""} it "matches the error message" do subject.valid? subject.errors[:organization].should include("can't be blank") end end context "when received_time is not valid" do before {subject.received_time = ""} it "matches the error message" do subject.valid? subject.errors[:received_time].should include("can't be blank") end end context "when name is too long" do before {subject.name = Faker::Lorem.characters(260)} it "matches the error message" do subject.valid? subject.errors[:name].should include("is too long (maximum is 255 characters)") end end context "when majors is too long" do before {subject.majors = Faker::Lorem.characters(260)} it "matches the error message" do subject.valid? subject.errors[:majors].should include("is too long (maximum is 255 characters)") end end context "when organization is too long" do before {subject.organization = Faker::Lorem.characters(260)} it "matches the error message" do subject.valid? subject.errors[:organization].should include("is too long (maximum is 255 characters)") end end context "when classification is too long" do before {subject.classification = Faker::Lorem.characters(260)} it "matches the error message" do subject.valid? subject.errors[:classification].should include("is too long (maximum is 255 characters)") end end end
require 'rails_helper' describe Admin::Authenticator do describe '#authenticate' do it 'should return true if password is valid' do m = build(:administrator) expect(Admin::Authenticator.new(m).authenticate('pw')).to be_truthy end it 'should return false if password is invalid' do m = build(:administrator) expect(Admin::Authenticator.new(m).authenticate('as')).to be_falsey end it 'should return false if password is not set' do m = build(:administrator, password: nil) expect(Admin::Authenticator.new(m).authenticate('pw')).to be_falsey end it 'should return true even if suspended' do m = build(:administrator, suspended: true) expect(Admin::Authenticator.new(m).authenticate('pw')).to be_truthy end end end
class AddImageToPhotos < ActiveRecord::Migration def self.up add_column :photos, :image, :string remove_column :photos, :url remove_column :photos, :thumbnail_url rename_column :photos, :title, :notes end def self.down remove_column :photos, :image add_column :photos, :url, :string add_column :photos, :thumbnail_url, :string rename_column :photos, :notes, :title end end
require 'spec_helper' # require 'pry' describe Mastermind::Game_Engine do let(:game) { Mastermind::Game_Engine.new } before :each do allow_message_expectations_on_nil allow(game).to receive(:puts).and_return(nil) end describe "#exact_match" do it 'returns exact matches' do expect(game.exact_match(["r","r","r","r"], ["r","r","r","r"])).to eql([[0, 0, 0, 0], 4]) end end describe "#partial_match" do it 'returns partial matches' do expect(game.partial_match(["g", "y", "r", "b"], ["r", "g", "b", "y"])).to eql(4) end end describe "#game" do it 'plays the game' do allow(game.computer_code).to receive(:computer_choice).with(0).and_return(["r","r","r","r"]) allow(game.player).to receive(:player_entry).and_return(nil) allow(game).to receive(:exact_match).and_return([[nil, nil,nil, nil], 4]) allow(game).to receive(:partial_match).and_return(0) allow(game).to receive(:analysis).and_return(nil) allow(game).to receive(:winner).and_return("win") allow(game).to receive(:difficulty).and_return(0) expect(game.game).to eql("win") end end describe "#analysis" do it 'analyses the game' do game.instance_variable_set("@counter", 13) allow(game).to receive(:try_again).and_return("done") expect(game.analysis(["r", "g", "b", "y"], 2, 0)).to eql("done") end end describe "#winner" do it 'checks for winners' do allow(game).to receive(:start_time).and_return(1) allow(game).to receive(:final_time).and_return(2) allow(game).to receive(:namer).and_return("name") allow(game).to receive(:save_file).and_return("Saved") allow(game).to receive(:leaderboard).and_return("lead") allow(game).to receive(:ask).and_return("Asked") expect(game.winner).to eql("Asked") end end describe "#try_again" do it 'tells player to try again' do allow(game).to receive(:final_time).and_return(20) allow(game).to receive(:counter).and_return(0) allow(game).to receive(:ask).and_return("tried") expect(game.try_again(2,2)).to eql("tried") end end describe "#namer" do it 'asks for user name' do allow(game).to receive(:user_input).and_return("p") expect(game.namer).to eql("p") end end describe "#save_file" do it "should create 'filename' and put 'text' in it" do allow(game).to receive(:leaderboard).and_return("Done") expect(game.save_file("./bin/testgameresults.txt")).to be nil end end describe "#leaderboard" do it "should read the result file and print out top ten" do allow(game).to receive(:ask).and_return("Asked Again") expect(game.leaderboard("./bin/testgameresults.txt")).to eql("Asked Again") end end end
require 'test_helper' class FbAdresasControllerTest < ActionController::TestCase setup do @fb_adresa = fb_adresas(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:fb_adresas) end test "should get new" do get :new assert_response :success end test "should create fb_adresa" do assert_difference('FbAdresa.count') do post :create, :fb_adresa => @fb_adresa.attributes end assert_redirected_to fb_adresa_path(assigns(:fb_adresa)) end test "should show fb_adresa" do get :show, :id => @fb_adresa.to_param assert_response :success end test "should get edit" do get :edit, :id => @fb_adresa.to_param assert_response :success end test "should update fb_adresa" do put :update, :id => @fb_adresa.to_param, :fb_adresa => @fb_adresa.attributes assert_redirected_to fb_adresa_path(assigns(:fb_adresa)) end test "should destroy fb_adresa" do assert_difference('FbAdresa.count', -1) do delete :destroy, :id => @fb_adresa.to_param end assert_redirected_to fb_adresas_path end end
class Api::V1::CommitAdjustmentsController < ApplicationController skip_before_action :authorized, only: [:create, :show, :index, :update, :destroy] before_action :admin_authorized, only: [:create] def index commit_adjustments = CommitAdjustment.all render json: commit_adjustments end def show commit_adjustments = CommitAdjustment.all.select {|commit_adjustment| commit_adjustment.user_id === params[:id].to_i} render json: commit_adjustments end def create commit_adjustment = CommitAdjustment.create(user_id: params[:user_id], adjustment: params[:adjustment], note: params[:note]) render json: commit_adjustment end def destroy commit_adjustment = CommitAdjustment.find(params[:id]) commit_adjustment.destroy render json: commit_adjustment end private def user_params params.permit(:user_id, :adjustment, :note) end end
describe Catalog::SoftDelete do let(:tenant) { create(:tenant) } let(:portfolio_item) { create(:portfolio_item, :tenant_id => tenant.id) } describe "#process" do context "when soft-deleting a record" do let!(:subject) { described_class.new(portfolio_item).process } it "discards the record" do expect(portfolio_item.discarded?).to be_truthy end it "sets the restore_key to the hash of the discarded_at column" do expect(subject.restore_key).to eq Digest::SHA1.hexdigest(portfolio_item.discarded_at.to_s) end end end end
Deface::Override.new(:virtual_path => "spree/admin/shared/_order_details", :name => %q{replace_order_details_line_item}, :replace => %q{[data-hook='order_details_line_item_row']}, :partial => "spree/admin/orders/line_item_row", :disabled => false)
class Stop < ApplicationRecord belongs_to :route validates :patient_name, presence: true validates :patient_address, presence: true end
require 'sieve/version' module Sieve class Generator # infinite generator - we add a class level ordered member (array) # in order to reuse as much computation results over different instances (memoization) # Singleton is not an option :O # we need not to inherit from Enumerable, each, map and so on work even @@primes = [2,3,5] # we start with the basic ones def each return enum_for(:each) unless block_given? #cause we have infinite series n = 0 while true yield self[n] n+=1 end end def [](index) generate(index+1)[index] end private def generate(n) index = @@primes[-1] while @@primes.length < n index+=1 is_prime = true upper_bound = Math.sqrt(index).to_i + 1 @@primes.each do |i| break unless i < upper_bound && is_prime is_prime &&= (index % i !=0) end @@primes << index if is_prime end @@primes[0..n] end end end
require 'spec_helper' describe GroupDocs::Document::Annotation do it_behaves_like GroupDocs::Api::Entity include_examples GroupDocs::Api::Helpers::AccessMode subject do file = GroupDocs::Storage::File.new document = GroupDocs::Document.new(:file => file) described_class.new(:document => document) end it { should have_accessor(:document) } it { should have_accessor(:id) } it { should have_accessor(:guid) } it { should have_accessor(:sessionGuid) } it { should have_accessor(:documentGuid) } it { should have_accessor(:creatorGuid) } it { should have_accessor(:replyGuid) } it { should have_accessor(:createdOn) } it { should have_accessor(:type) } it { should have_accessor(:access) } it { should have_accessor(:box) } it { should have_accessor(:replies) } it { should have_accessor(:annotationPosition) } it { should alias_accessor(:session_guid, :sessionGuid) } it { should alias_accessor(:document_guid, :documentGuid) } it { should alias_accessor(:creator_guid, :creatorGuid) } it { should alias_accessor(:reply_guid, :replyGuid) } # Annotation#created_on is overwritten it { should have_alias(:created_on=, :createdOn=) } it { should alias_accessor(:annotation_position, :annotationPosition) } it { should have_alias(:annotationGuid=, :guid=) } describe '#initialize' do it 'raises error if document is not specified' do lambda { described_class.new }.should raise_error(ArgumentError) end it 'raises error if document is not an instance of GroupDocs::Document' do lambda { described_class.new(:document => '') }.should raise_error(ArgumentError) end end describe '#type=' do it 'saves type in machine readable format if symbol is passed' do subject.type = :text_strikeout subject.instance_variable_get(:@type).should == 'TextStrikeout' end it 'does nothing if parameter is not symbol' do subject.type = 'Area' subject.instance_variable_get(:@type).should == 'Area' end it 'raises error if type is unknown' do lambda { subject.type = :unknown }.should raise_error(ArgumentError) end end describe '#type' do it 'returns type in human-readable format' do subject.type = 'TextStrikeout' subject.type.should == :text_strikeout end end describe '#access=' do it 'converts symbol to string if passed' do subject.access = :public subject.instance_variable_get(:@access).should == 'Public' end it 'does nothing if not a symbol is passed' do subject.access = 'Blah' subject.instance_variable_get(:@access).should == 'Blah' end end describe '#created_on' do it 'returns converted to Time object Unix timestamp' do subject.created_on = 1332950825000 subject.created_on.should == Time.at(1332950825) end end describe '#box=' do it 'converts passed hash to GroupDocs::Document::Rectangle object' do subject.box = { :x => 0.90, :y => 0.05, :width => 0.06745, :height => 0.005967 } subject.box.should be_a(GroupDocs::Document::Rectangle) subject.box.x.should == 0.90 subject.box.y.should == 0.05 subject.box.w.should == 0.06745 subject.box.h.should == 0.005967 end end describe '#replies=' do it 'converts each reply to GroupDocs::Document::Annotation::Reply object if hash is passed' do subject.replies = [{ }] replies = subject.replies replies.should be_an(Array) replies.each do |reply| reply.should be_a(GroupDocs::Document::Annotation::Reply) reply.annotation.should == subject end end it 'saves each reply if it is GroupDocs::Document::Annotation::Reply object' do reply1 = GroupDocs::Document::Annotation::Reply.new(:annotation => subject) reply2 = GroupDocs::Document::Annotation::Reply.new(:annotation => subject) subject.replies = [reply1, reply2] subject.replies.should include(reply1) subject.replies.should include(reply2) end it 'does nothing if nil is passed' do lambda do subject.replies = nil end.should_not change(subject, :replies) end end describe '#add_reply' do it 'raises error if reply is not GroupDocs::Document::Annotation::Reply object' do lambda { subject.add_reply('Reply') }.should raise_error(ArgumentError) end it 'saves reply' do reply = GroupDocs::Document::Annotation::Reply.new(:annotation => subject) subject.add_reply(reply) subject.replies.should == [reply] end end describe '#create!' do before(:each) do mock_api_server(load_json('annotation_create')) end it 'accepts access credentials hash' do lambda do subject.create!(%w(info), :client_id => 'client_id', :private_key => 'private_key') end.should_not raise_error() end it 'updated self with response values' do lambda do subject.create! :box => '10', :annotationPosition => '100' end.should change { subject.id subject.guid subject.document_guid subject.reply_guid subject.session_guid } end end describe '#remove!' do before(:each) do mock_api_server(load_json('annotation_remove')) end it 'accepts access credentials hash' do lambda do subject.remove!(:client_id => 'client_id', :private_key => 'private_key') end.should_not raise_error() end end describe '#replies!' do it 'calls GroupDocs::Document::Annotation::Reply.get!' do GroupDocs::Document::Annotation::Reply.should_receive(:get!).with(subject, {}, {}) subject.replies! end end describe '#move!' do before(:each) do mock_api_server(load_json('annotation_move')) end it 'accepts access credentials hash' do lambda do subject.move!(10, 10, :client_id => 'client_id', :private_key => 'private_key') end.should_not raise_error() end it 'updates annotation position' do lambda do subject.move!(10, 10) end.should change(subject, :annotation_position).to(:x => 10, :y => 10) end end describe '#move_marker!' do before(:each) do mock_api_server('{ "status": "Ok", "result": {}}') end let(:marker) { GroupDocs::Document::Annotation::MarkerPosition.new(:position => {:x => 1, :y => 1}, :page=>1)} 1 it 'accepts access credentials hash' do lambda do subject.move_marker!(marker, :client_id => 'client_id', :private_key => 'private_key') end.should_not raise_error() end it 'raises error if marker is not GroupDocs::Document::Annotation::MarkerPosition object' do lambda { subject.move_marker!(['MarkerPosition']) }.should raise_error(ArgumentError) end end describe '#set_access!' do before(:each) do mock_api_server(load_json('annotation_access_set')) end it 'accepts access credentials hash' do lambda do subject.set_access!(:private, :client_id => 'client_id', :private_key => 'private_key') end.should_not raise_error() end it 'updates annotation access mode' do subject.set_access!(:private) subject.access.should == :private end end end
class RemoveExpireTimeFromPosts < ActiveRecord::Migration def change remove_column :posts, :expire_time, :datetime end end
require 'test_helper' class UserTest < ActiveSupport::TestCase def setup @user = User.new(name: 'Sterling Archer', email: 'archer@figgis.agency', admin: false, password: 'foobarfoobargoof', password_confirmation: 'foobarfoobargoof') end test 'should be valid' do assert @user.valid? end test 'name should be present' do @user.name = ' ' assert_not @user.valid? end test 'name should not be too long' do @user.name = 'a' * 51 assert_not @user.valid? end test 'email should be present' do @user.email = ' ' assert_not @user.valid? end test 'email should not be too long' do @user.email = 'a' * 244 + '@example.com' assert_not @user.valid? end test 'email validation should accept valid addresses' do valid_addresses = %w(user@example.com USER@foo.COM A_US-ER@foo.bar.org first.last@foo.jp alice+bob@baz.cn) valid_addresses.each do |address| @user.email = address assert @user.valid?, "#{address.inspect} should be valid" end end test 'email validation should reject bad addresses' do invalid_addresses = %w(user@example,com user_at_foo.org user.name@example. foo@bar_baz.com foo@bar+baz.com) invalid_addresses.each do |addy| @user.email = addy assert_not @user.valid?, "#{addy.inspect} should not be valid" end end test 'email addresses should be unique' do dupe_user = @user.dup @user.save assert_not dupe_user.valid? # make sure we catch case variation on repeated email addresses dupe_user.email.upcase! assert_not dupe_user.valid? end test 'email addresses should be saved as lowercase' do mixed_case_email = 'Foo@ExamPlE.Com' @user.email = mixed_case_email @user.save assert_equal mixed_case_email.downcase, @user.reload.email end test 'password should not be blank' do @user.password = @user.password_confirmation = ' ' * 16 assert_not @user.valid? end test 'password should have a minimum length' do @user.password = @user.password_confirmation = 'foobar' assert_not @user.valid? end test 'authenticated? should return false for a user with nil digest' do assert_not @user.authenticated?('') end end
module JeraPush module Service class SendMessage def initialize(*args) args[0].map { |attr_name, value| instance_variable_set("@#{attr_name}", value) } end def call return false unless valid? message_content = JeraPush::Message.format_hash @message case @type.to_sym when :broadcast JeraPush::Message.send_broadcast(content: message_content) when :specific target_devices = JeraPush::Device.where(id: @devices.uniq.map(&:to_i)) JeraPush::Message.send_to(target_devices, content: message_content) end end def valid? valid = @message.present? && @type.present? @type.to_sym == :broadcast ? valid : valid && @devices.present? end end end end
require 'test_helper' module KepplerLanguages class LanguagesControllerTest < ActionDispatch::IntegrationTest include Engine.routes.url_helpers setup do @language = keppler_languages_languages(:one) end test "should get index" do get languages_url assert_response :success end test "should get new" do get new_language_url assert_response :success end test "should create language" do assert_difference('Language.count') do post languages_url, params: { language: { deleted_at: @language.deleted_at, name: @language.name, position: @language.position } } end assert_redirected_to language_url(Language.last) end test "should show language" do get language_url(@language) assert_response :success end test "should get edit" do get edit_language_url(@language) assert_response :success end test "should update language" do patch language_url(@language), params: { language: { deleted_at: @language.deleted_at, name: @language.name, position: @language.position } } assert_redirected_to language_url(@language) end test "should destroy language" do assert_difference('Language.count', -1) do delete language_url(@language) end assert_redirected_to languages_url end end end
class HdfsFile attr_reader :hadoop_instance, :path def initialize(path, hadoop_instance, attributes={}) @attributes = attributes @hadoop_instance = hadoop_instance @path = path end def contents hdfs_query = Hdfs::QueryService.new(hadoop_instance.host, hadoop_instance.port, hadoop_instance.username, hadoop_instance.version) hdfs_query.show(path) end def modified_at @attributes[:modified_at] end def url hadoop_instance.url.chomp('/') + path end end
module PryIb module Command module Chart def self.build(commands) commands.create_command "chart" do description "Get Chart from stock quotes" group 'pry-ib' def options(opt) opt.on :m1, 'use 1 min period' opt.on :m5, 'use 5 min period' opt.on :h1, 'use one hour period' opt.on :h2, 'use two hour period' opt.on :d,:day, 'use day period' opt.on :w,:week, 'use week period' end def process raise Pry::CommandError, "Need a least one symbol" if args.size == 0 symbol = args.first #ib = PryIb::Connection::current period = '5min' period = '1min' if opts.m1? period = '5min' if opts.m5? period = '1hour' if opts.h1? period = '2hour' if opts.h2? period = 'day' if opts.day? period = 'week' if opts.week? output.puts "Chart: #{symbol} period:#{period}" chart = PryIb::Chart.new(nil,symbol) chart.open(period) end end end end end end
class AddNameRemoveQuestionsFromEvaluations < ActiveRecord::Migration def change add_column :evaluations, :name, :string remove_column :evaluations, :q1 remove_column :evaluations, :q2 remove_column :evaluations, :q3 remove_column :evaluations, :q4 end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # require "cases/helper" require 'models/topic' class FinderRespondToTest < ActiveRecord::TestCase fixtures :topics def test_should_preserve_normal_respond_to_behaviour_and_respond_to_newly_added_method class << Topic; self; end.send(:define_method, :method_added_for_finder_respond_to_test) { } assert Topic.respond_to?(:method_added_for_finder_respond_to_test) ensure class << Topic; self; end.send(:remove_method, :method_added_for_finder_respond_to_test) end def test_should_preserve_normal_respond_to_behaviour_and_respond_to_standard_object_method assert Topic.respond_to?(:to_s) end def test_should_respond_to_find_by_one_attribute_before_caching ensure_topic_method_is_not_cached(:find_by_title) assert Topic.respond_to?(:find_by_title) end def test_should_respond_to_find_all_by_one_attribute ensure_topic_method_is_not_cached(:find_all_by_title) assert Topic.respond_to?(:find_all_by_title) end def test_should_respond_to_find_all_by_two_attributes ensure_topic_method_is_not_cached(:find_all_by_title_and_author_name) assert Topic.respond_to?(:find_all_by_title_and_author_name) end def test_should_respond_to_find_by_two_attributes ensure_topic_method_is_not_cached(:find_by_title_and_author_name) assert Topic.respond_to?(:find_by_title_and_author_name) end def test_should_respond_to_find_or_initialize_from_one_attribute ensure_topic_method_is_not_cached(:find_or_initialize_by_title) assert Topic.respond_to?(:find_or_initialize_by_title) end def test_should_respond_to_find_or_initialize_from_two_attributes ensure_topic_method_is_not_cached(:find_or_initialize_by_title_and_author_name) assert Topic.respond_to?(:find_or_initialize_by_title_and_author_name) end def test_should_respond_to_find_or_create_from_one_attribute ensure_topic_method_is_not_cached(:find_or_create_by_title) assert Topic.respond_to?(:find_or_create_by_title) end def test_should_respond_to_find_or_create_from_two_attributes ensure_topic_method_is_not_cached(:find_or_create_by_title_and_author_name) assert Topic.respond_to?(:find_or_create_by_title_and_author_name) end def test_should_not_respond_to_find_by_one_missing_attribute assert !Topic.respond_to?(:find_by_undertitle) end def test_should_not_respond_to_find_by_invalid_method_syntax assert !Topic.respond_to?(:fail_to_find_by_title) assert !Topic.respond_to?(:find_by_title?) assert !Topic.respond_to?(:fail_to_find_or_create_by_title) assert !Topic.respond_to?(:find_or_create_by_title?) end private def ensure_topic_method_is_not_cached(method_id) class << Topic; self; end.send(:remove_method, method_id) if Topic.public_methods.any? { |m| m.to_s == method_id.to_s } end end
require_relative '../../db/config' class Student < ActiveRecord::Base validates :email, :uniqueness => true validates :age, numericality: {:greater_than => 5} validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i } validates :phone, length: {minimum: 10} def name "#{first_name} #{last_name}" end def age @age = ((Date.today - birthday)/365).to_i end end
class CreateCommentSnapTemplates < ActiveRecord::Migration def change create_table :comment_snap_templates do |t| t.string :name, :title_overlay, :body_overlay, null: false t.boolean :active, null: false, default: true t.timestamps end end end
class AddPreToCourses < ActiveRecord::Migration[5.0] def change add_column :courses, :pre, :string end end
class Admin::CommentsController < ApplicationController before_action :admin_access def index @comments = Comment.all.limit(100) end def destroy @comment = Comment.find(params[:id]) @comment.destroy end end
RSpec.describe MonstersController do describe "GET index" do it "blocks unauthenticated access" do sign_in nil get :index expect(response).to redirect_to(:root) end context 'with login' do before do @user = create(:user) @monster = create(:monster, user: @user) sign_in @user end it "assigns @monsters" do get :index expect(assigns(:monsters)).to eq([@monster]) end it "renders the index template" do get :index expect(response).to render_template("index") end end end describe "#create" do it "blocks unauthenticated access" do sign_in nil post :create, monster: {name: 'Monster1'} expect(response).to redirect_to(:root) end context 'with login' do before do @user = create(:user) sign_in @user end it "creates a monster" do expect { post :create, monster: attributes_for(:monster) }.to change { Monster.count }.by(1) expect(assigns(:monster)).to eq(Monster.last) end it "redirects to the monster page" do post :create, monster: attributes_for(:monster) expect(response).to redirect_to assigns(:monster) end end end describe "#update" do it "blocks unauthenticated access" do sign_in nil post :update, id: 1, monster: {name: 'Monster1o1'} expect(response).to redirect_to(:root) end context 'with login' do before do @user = create(:user) sign_in @user @monster = create(:monster, user: @user) end it "update a monster" do post :update, id: @monster.id, monster: {name: 'Monster1o1'} expect(assigns(:monster).name).to eq('Monster1o1') end it "redirects to the monster page" do post :update, id: @monster.id, monster: {name: 'Monster1o1'} expect(response).to redirect_to assigns(:monster) end end end describe "#destroy" do it "blocks unauthenticated access" do sign_in nil delete :destroy, id: 1 expect(response).to redirect_to(:root) end context 'with login' do before do @user = create(:user) sign_in @user @monster = create(:monster, user: @user) end it "destroy the monster" do delete :destroy, id: @monster.id expect(flash[:notice]).to eq "Monster was successfully destroyed." expect(response.status).to eq 302 #redirected end end end end
class WeightRate < ActiveRecord::Base belongs_to :calculator validates_presence_of :base_weight, :base_cost, :rate_per_unit named_scope :for_calculator, lambda{ |calc| if calc.is_a?(Calculator) {:conditions => {:calculator_id => calc.id}} else {:conditions => {:calculator_id => calc.to_i}} end } def unit calculator && calculator.unit end def validate if !base_cost.blank? && !base_weight.blank? errors.add(:base_cost, :base_weight) end end def <=>(other) self.base_weight <=> other.base_weight end end
class DealsNotification < ActiveRecord::Base validates_presence_of :email validates_format_of(:email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i) after_create :call_count_mailer belongs_to :city def call_count_mailer user_count = DealsNotification.count(:all) unless self.city.nil? city= self.city.name else city= "Other" end UserMailer.deliver_count_to_admin(user_count,self.email,"Deal Notification",self.source,city) end def self.find_by_email(email) DealsNotification.find(:first,:conditions => "email = '#{email}'") end def self.find_by_is_send_email(value) DealsNotification.find(:all,:conditions => "is_send_email = '#{value}'") end end
class AddTemplateFieldsToThankYouCards < ActiveRecord::Migration def change add_column :thank_you_cards, :template, :text end end
class FormMailer < ActionMailer::Base default :from => Noodall::FormBuilder.noreply_address def form_response(form, response) @form = form @response = response mail(:to => form.email, :reply_to => response.email, :subject => "[#{Noodall::UI.app_name}] Response to the #{form.title} form.") end def form_response_thankyou(form, response) @form = form @response = response mail(:to => response.email, :reply_to => form.email, :subject => "[#{Noodall::UI.app_name}] Thank you for getting in contact.") end end
class AddValidtimeToPartner < ActiveRecord::Migration def change add_column :Partner, :GueltigVon, :datetime add_column :Partner, :GueltigBis, :datetime 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) # When you run the Panamax container, a rake task executes to unload and load templates. We are disabling # the after_create callback here to avoid two sets of unload/loading of templates. default_source = GithubTemplateRepoProvider.create(name: TemplateRepo::DEFAULT_PROVIDER_NAME) TemplateRepo.skip_callback(:create, :after, :reload_templates) TemplateRepo.find_or_create_by(name: 'centurylinklabs/panamax-public-templates') do |repo| repo.template_repo_provider = default_source end TemplateRepo.set_callback(:create, :after, :reload_templates) Registry.find_or_create_by(id: 0, name: 'Docker Hub', endpoint_url: 'https://index.docker.io')
# == Schema Information # # Table name: sections # # id :integer not null, primary key # resource_id :integer # title :string # created_at :datetime not null # updated_at :datetime not null # row :integer # # Indexes # # index_sections_on_resource_id (resource_id) # require 'rails_helper' RSpec.describe Section, type: :model do context 'associations' do it { should belong_to :resource } it { should have_many(:lessons).dependent(:delete_all) } end context 'validations' do it { should validate_presence_of(:title) } end end
# coding: utf-8 require 'rails_helper' feature 'gerenciar Usuario' do scenario 'incluir Usuario' do # , :js => true do visit new_usuario_path preencher_e_verificar_usuario end scenario 'alterar Usuario' do #, :js => true do usuario = FactoryGirl.create(:usuario) visit edit_usuario_path(usuario) preencher_e_verificar_usuario end scenario 'excluir usuario' do #, :javascript => true do usuario = FactoryGirl.create(:usuario) visit usuarios_path click_link 'Excluir' end def preencher_e_verificar_usuario fill_in 'Nome', :with => "Fulano" fill_in 'Senha', :with => "12345" fill_in 'Email', :with => "fulano@fulano.com" click_button 'Salvar' expect(page).to have_content 'Nome: Fulano' expect(page).to have_content 'Senha: 12345' expect(page).to have_content 'Email: fulano@fulano.com' end end
class Room < ApplicationRecord mount_uploader :images, CoverUploaderUploader geocoded_by :address after_validation :geocode, if: :address_changed? belongs_to :user end
# frozen_string_literal: true class Question < ApplicationRecord belongs_to :lesson belongs_to :user has_many :answers has_many:qmetoos,class_name: "Metoo" validates :title, presence: true validates :body, presence: true default_scope -> { order(created_at: :desc) } end
module TestPassagesHelper def total_questions_helper t('helpers.test_passage.total', total: @test_passage.test.total_questions) end def result_message(result) if @test_passage.successful? content_tag(:h2, t('helpers.test_passage.success', result: result), class: 'text-success') elsif @test_passage.result >= TestPassage::SUCCESS_VALUE content_tag(:h2, t('helpers.test_passage.time', result: result, time: @test_passage.passage_duration, duration: @test_passage.test.duration), class: 'text-danger') else content_tag(:h2, t('helpers.test_passage.fail', result: result), class: 'text-danger') end end end
class EngineerHiring < ApplicationRecord belongs_to :office belongs_to :hiring_contact, class_name: "Contact", required: false belongs_to :engineer enum status:ApplicationRecord.cmn_statuses after_initialize :set_default_value, if: :new_record? scope :active, -> {where('status=1')} private def set_default_value self.status = 1 end end
require "mpipe.so" require "mpipe/version" class MPipe @@min_poll = 0.01 @@max_poll = 0.32 def self.min_polling_interval=(time) @@min_poll = time end def self.max_polling_interval=(time) @@max_poll = time end # emulate IO.select def self.select(rd_ary, wt_ary=nil, er_ary=nil, timeout=nil) rd_ary = [] if rd_ary.nil? wt_ary = [] if wt_ary.nil? rd_mpi = [] rd_io = [] wt_io = [] rd_ret = Array.new(rd_ary.size) wt_ret = Array.new(wt_ary.size) rd_idx = {} wt_idx = {} found = false rd_ary.each_with_index do |rd,i| rd_idx[rd] = i case rd when MPipe rd_mpi << rd if rd.test_recv rd_ret[i] = rd found = true end when IO rd_io << rd else raise ArgumentError, "elements should be IO or MPipe" end end wt_ary.each_with_index do |wt,i| wt_idx[wt] = i case wt when MPipe wt_ret[i] = wt found = true when IO wt_io << wt else raise ArgumentError, "elements should be IO or MPipe" end end if er_ary er_ary.each do |er| if !er.kind_of?(IO) raise ArgumentError, "er_ary contains non-IO object" end end end time_start = Time.now # first check rd_res,wt_res,er_res = IO.select(rd_io, wt_io, er_ary, 0) if rd_res rd_res.each{|io| rd_ret[rd_idx[io]] = io} found = true end if wt_res wt_res.each{|io| wt_ret[wt_idx[io]] = io} found = true end if er_res found = true end if found return [rd_ret.compact, wt_ret.compact, er_res] end dt = @@min_poll max_dt = @@max_poll loop do if timeout elap = Time.now - time_start if timeout <= elap return nil else dto = timeout - elap dt = (dto < dt) ? dto : dt end end # check with timeout rd_res,wt_res,er_res = IO.select(rd_io, wt_io, er_ary, dt) if rd_res rd_res.each{|io| rd_ret[rd_idx[io]] = io} found = true end if wt_res wt_res.each{|io| wt_ret[wt_idx[io]] = io} found = true end if er_res found = true end rd_mpi.each do |mp| if mp.test_recv rd_ret[rd_idx[mp]] = mp found = true end end if found return [rd_ret.compact,wt_ret.compact,er_res] end if dt != max_dt dt *= 2 if dt < max_dt dt = max_dt if dt > max_dt end end end end
FactoryBot.define do factory :item do name { Faker::Commerce.product_name } category_id { 2 } price { Faker::Number.between(300, 9_999_999) } status_id { 2 } description { Faker::Lorem.sentence } prefecture_id { 2 } date_of_shipment_id { 2 } burden_id { 2 } association :user after(:build) do |item| item.image.attach(io: File.open('app/assets/images/star.png'), filename: 'test_image.png') end end end
class CreateGames < ActiveRecord::Migration[5.2] def change create_table :games do |t| t.string :opposing_team t.string :oppsoing_game_id t.integer :goalie_id t.integer :period , default: 1 t.boolean :home_bool t.datetime :date t.timestamps end end end
# Instructions: # Count elements in an Array by returning a hash with keys of the elements and # values of the amount of times they occur. def count(array) hash = {} array.each do |item| hash[item] = array.count(item) end hash end test = ['cat', 'dog', 'fish', 'fish'] count(test) #=> { 'cat' => 1, 'dog' => 1, 'fish' => 2 })
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :omniauthable, omniauth_providers: [:facebook, :google_oauth2] has_many :sns_crendentials has_many :cards has_many :items has_many :addresses accepts_nested_attributes_for :addresses validates :family_name, :first_name, :family_name_kana, :first_name_kana, :nickname, :birthday, presence: true validates :password, length: {minimum: 7}, format: { with: /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]{7,}/i}, on: :create validates :password, length: {minimum: 7}, format: { with: /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]{7,}/i}, on: :update, allow_blank: true validates :email, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i } validates :phone_number, presence: true, format: {with: /\A\d{10,11}\z/} end
require 'nokogiri' require 'httparty' class Scraper def initialize(keywords, site) @keywords = keywords @site = site @jobs = [] end def scrape page = 1 last_page = last_page(@site, parse_html(make_url(@site, 1))) return 'no job found' if last_page.zero? puts "Total no. of pages: #{last_page}\n\n" if last_page > 50 last_page = 50 puts "Total no. of pages exceeds limit of 50.\nScraping first 50 pages...\n\n" end while page <= last_page puts "Scraping page #{page} of #{last_page}..." parsed_html = parse_html(make_url(@site, page)) case @site when 'freelancer' scrape_freelancer(parsed_html) when 'guru' scrape_guru(parsed_html) else scrape_peopleperhour(parsed_html) end page += 1 end @jobs end private def parse_keywords @keywords.map! { |keyword| keyword.gsub(' ', '-') } search_query = if @site == 'freelancer' || @site == 'peopleperhour' @keywords.join('%20') else @keywords.join('/skill/') end search_query end def make_url(site, page) search_url = case site when 'freelancer' "https://www.freelancer.com/jobs/#{page}/?keyword=#{parse_keywords}" when 'guru' "https://www.guru.com/d/jobs/skill/#{parse_keywords}/pg/#{page}" else "https://www.peopleperhour.com/freelance-#{parse_keywords}-jobs?page=#{page}" end search_url end def parse_html(url) unparsed_page = HTTParty.get(url).body parsed_page = Nokogiri::HTML(unparsed_page) parsed_page end def last_page(site, parsed_page) case site when 'freelancer' job_listings = parsed_page.css('div.JobSearchCard-item') total = parsed_page.css('span#total-results').text.gsub(',', '').to_f when 'guru' job_listings = parsed_page.css('div.jobRecord') total = parsed_page.css('h2.secondaryHeading').text.split(' ')[0].gsub(',', '').to_f else job_listings = parsed_page.css('#reactContainer > div > div.page-container > section > main > div > div.list⤍JobsList⤚2YMp7 > div > ul > li.list__item⤍List⤚2ytmm') total = parsed_page.css('#reactContainer > div > div.page-container > section > main > div > div.header⤍JobsList⤚Zv8FI > h1 > span:nth-child(2)').text.split('—')[1].split(' ')[0].to_f end return 0 if job_listings.count.zero? per_page = job_listings.count.to_f last_page = (total / per_page).ceil.to_i last_page end def scrape_freelancer(parsed_html) job_listings = parsed_html.css('div.JobSearchCard-item') job_url = 'https://www.freelancer.com' job_listings.each do |job_listing| tags = [] tags_text = job_listing.css('a.JobSearchCard-primary-tagsLink') tags_text.each do |tag| tags << tag.text end job = { title: job_listing.css('a.JobSearchCard-primary-heading-link').text.strip.gsub(/\\n/, ' '), rate: job_listing.css('div.JobSearchCard-secondary-price').text.delete(' ').delete("\n").delete('Avg Bid'), desc: job_listing.css('p.JobSearchCard-primary-description').text.strip, tags: tags.join(', '), url: job_url + job_listing.css('a.JobSearchCard-primary-heading-link')[0].attributes['href'].value } @jobs << job end @jobs end def scrape_guru(parsed_html) parsed_html.css('div.record__details').each do |job_listing| tags = [] job_listing.css('a.skillsList__skill').each { |tag| tags << tag.text.strip } budget_array = [] job_listing.css('div.jobRecord__budget').css('strong').each do |budget| budget_array << budget.text.strip end job = { title: job_listing.css('h2.jobRecord__title').text.strip, posted_by: job_listing.css('div.module_avatar').css('h3.identityName').text.strip, posted: job_listing.css('div.jobRecord__meta').css('strong')[0].text, send_before: job_listing.css('div.record__header__action').css('strong').text.strip, budget: budget_array.join(' , '), desc: job_listing.css('p.jobRecord__desc').text.strip, tags: tags.join(', '), url: 'https://www.guru.com' + job_listing.css('h2.jobRecord__title').css('a')[0].attributes['href'].value } @jobs << job end @jobs end def scrape_peopleperhour(parsed_html) job_listings = parsed_html.css('#reactContainer > div > div.page-container > section > main > div > div.list⤍JobsList⤚2YMp7 > div > ul > li.list__item⤍List⤚2ytmm') job_listings.each do |job_listing| job = { title: job_listing.css('h6.item__title⤍ListItem⤚2FRMT > a').text.strip, posted: job_listing.css('time.item__info-value⤍ListItem⤚1Kxws').text.strip, rate: job_listing.css('div.item__budget⤍ListItem⤚3P7Zd').text.strip, proposals: job_listing.css('div > div > div.item__container⤍ListItem⤚Fk4RX > div.pph-col-md-8.pph-col-xs-8 > ul > li:nth-child(3) > span').text, url: job_listing.css('h6.item__title⤍ListItem⤚2FRMT > a')[0].attributes['href'].value } @jobs << job end @jobs end end
class PlacesController < ApplicationController before_action :authenticate_user! def initialize @gooPla = GooglePlaces.new(ENV["GP_KEY"]) end def index render json: @gooPla.text_search(params[:type], params[:city]) end def show render json: @gooPla.detail_search(params[:place_id]) end end
# gen_node_tree.rb module Gen class Node attr_accessor :name, :symbol, :child_table_name, :child_table_join_column_name, :parent_table_join_column_name, :nodes def initialize(name, symbol=nil, child_table_name=nil, child_table_join_column_name=nil, parent_table_join_column_name=nil) @name = name @symbol = symbol @child_table_name = child_table_name @child_table_join_column_name = child_table_join_column_name @parent_table_join_column_name = parent_table_join_column_name @nodes = {} end def str_name return "#{name} #{symbol} #{child_table_name}.#{child_table_join_column_name.to_s[0..-4]}" if (child_table_join_column_name and (symbol == "<=" or symbol == "<-")) return "#{name} #{symbol} #{child_table_name}" if symbol "#{name}" end def to_str(level=0) indent = " " * level result = ["#{indent}#{str_name}"] nodes.each do |k, v| if v.class == ::Array v.each do |item| result << item.to_str(level + 1) end else result << v.to_str(level + 1) end end result.join("\n") end end def self.gen_node_tree(tables_hash) # create tree structure based on pk/fk releationships of tables. tables = tables_hash.values.sort {|a, b| a.table_name <=> b.table_name} root = Node.new "root" tables.each do |v| #puts "v.table_name: #{v.table_name}." table_node = Node.new(v.table_name) root.nodes[v.table_name] = table_node # make sub nodes for each column columns = v.columns_sequence_order columns.each do |column| if column.foreign_key? name = column.name.to_s[0..-4].to_sym # cut off "..._id" from column name and use as node name. symbol = "->" child_table_name = column.foreign_key_table_name child_table_join_column_name = tables_hash[column.foreign_key_table_name].primary_key_columns.first[0] parent_table_join_column_name = column.name else name = column.name symbol = nil child_table_name = nil child_table_join_column_name = nil parent_table_join_column_name = nil end #puts " #{name}, symbol: #{symbol}." table_node.nodes[name] = Gen::Node.new(name, symbol, child_table_name, child_table_join_column_name, parent_table_join_column_name) end # make sub nodes for each table having a fk reference to this (the parent) table -- exclude self. tables.each do |child_table| if v.table_name != child_table.table_name #nor own table fk_columns = child_table.foreign_key_columns_by_table_name[v.table_name] if fk_columns #puts " #{child_table.table_name}. count: #{fk_columns.count}." name = child_table.table_name table_node.nodes[name] = [] fk_columns.each do |key, fk_column| #puts " fk_column: #{fk_column.name}." #puts " name: #{name}, #{name.class}." #puts " class: #{table_node.nodes[name].class}." #puts " count: #{table_node.nodes[name].count}." if fk_column.primary_key? and child_table.primary_key_columns.count == 1 symbol = "<-" else symbol = "<=" end child_table_name = child_table.table_name child_table_join_column_name = fk_column.name parent_table_join_column_name = v.primary_key_columns.first[0] table_node.nodes[name] << Gen::Node.new(name, symbol, child_table_name, child_table_join_column_name, parent_table_join_column_name) #puts " nodes[name].count: #{table_node.nodes[name].count}." end end end end end root end end
require "rails_helper" RSpec.describe OverviewQuery do around do |example| with_reporting_time_zone { example.run } end describe "#inactive_facilities" do let!(:active_facility) { create(:facility) } let!(:inactive_facility) { create :facility } let!(:inactive_facility_with_zero_bps) { create :facility } let!(:inactive_facility_with_bp_outside_period) { create :facility } let!(:user) { create(:user, registration_facility: active_facility) } let!(:non_htn_patient) { create(:patient, registration_user: user, registration_facility: user.facility) } threshold_days = 30 threshold_bps = 1 date = threshold_days.days.ago.beginning_of_day + 1.day let!(:blood_pressures_for_active_facility) do create_list(:blood_pressure, threshold_bps, facility: active_facility, recorded_at: date) create(:blood_pressure, patient: non_htn_patient, facility: active_facility, recorded_at: date) end let!(:blood_pressures_for_inactive_facility) do create_list(:blood_pressure, threshold_bps - 1, facility: inactive_facility, recorded_at: date) end let!(:blood_pressures_for_inactive_facility_with_bp_outside_period) do create_list(:blood_pressure, threshold_bps, user: user, facility: inactive_facility_with_bp_outside_period, recorded_at: date - 1.month) end before do BloodPressuresPerFacilityPerDay.refresh end it "returns only inactive facilities" do facility_ids = [active_facility.id, inactive_facility.id, inactive_facility_with_zero_bps.id, inactive_facility_with_bp_outside_period.id] expect(described_class.new(facilities: Facility.where(id: facility_ids)).inactive_facilities.map(&:id)) .to match_array([inactive_facility.id, inactive_facility_with_zero_bps.id, inactive_facility_with_bp_outside_period.id]) end end describe "#total_bps_in_last_n_days" do let!(:facility) { create(:facility) } let!(:user) { create(:user, registration_facility: facility) } let!(:htn_patient) { create(:patient, registration_user: user, registration_facility: facility) } let!(:non_htn_patient) { create(:patient, :without_hypertension, registration_user: user, registration_facility: facility) } let!(:bp_for_htn_patient) do create(:blood_pressure, user: user, facility: facility, patient: htn_patient, recorded_at: 1.day.ago) end let!(:bp_for_non_htn_patient) do create(:blood_pressure, user: user, facility: facility, patient: non_htn_patient, recorded_at: 1.day.ago) end before do BloodPressuresPerFacilityPerDay.refresh end context "considers only htn diagnosed patients" do specify { expect(described_class.new(facilities: facility).total_bps_in_last_n_days(n: 2)[facility.id]).to eq(1) } end end end
# Kubernetes REST-API Client module Kubeclient VERSION = '4.1.2'.freeze end
module ApplicationHelper def hdate(dt, divider={}) return '' if dt.blank? divider = "." if divider.blank? dt.strftime("%Y#{divider}%m#{divider}%d") end def hdatetime(dt, divider={}) return '' if dt.blank? divider = "." if divider.blank? dt.strftime("%Y#{divider}%m#{divider}%d %H:%M") end def htime(dt) return '' if dt.blank? divider = ":" dt.strftime("%H:%M") end # for form error message def flash_error_message(association) if @errors[association].present? @errors.each do |a, message| concat "<div class='flash_error_message'>#{message.to_sentence}</div>".html_safe end end end # == Navigation Tag Helpers == def navigation_tag(options = {}, &block) b = NavigationBuilder.new(self, options) yield b concat(b.to_html) unless b.empty? nil end class NavigationBuilder include ActionView::Helpers::TagHelper include ActionView::Helpers::CaptureHelper def initialize(template, options = {}) @template = template @items = [] @container_id = options.delete(:id) @container_class = options.delete(:class) @spacer = options.delete(:spacer) || "\n" end def empty? @items.empty? end def item(caption, path, options = {}) anchor_option = options.delete(:anchor_option) || {} if options[:icon].present? caption = "<i class=\"#{options.delete(:icon)}#{ ' icon-white' if options[:current] }\"></i> #{caption}".html_safe end if options[:count].present? model = caption.singularize.constantize caption = "#{caption} <span class=\"num_badge\">#{model.count}</span>".html_safe end @items << [@template.link_to(caption, path, anchor_option), options] nil end def item_html(options = {}, &block) content = @template.capture(&block) @items << [content, options] nil end def item_wrapper(content, options = {}) classes = [] html_option = options.delete(:html) || {} classes << html_option.delete(:class) classes << "first" if @items.first[0] == content classes << "last" if @items.last[0] == content if options.delete(:current) classes << "active" content = content + content_tag(:div, "", class: "arrow") end if classes == [nil] content_tag :li, content else html_option[:class] = classes.join(" ").strip content_tag :li, content, html_option end end def build content_tag :ul, @items.collect{|t| item_wrapper(*t)}.join(@spacer).html_safe, :id => @container_id, :class => @container_class end alias :to_html :build end end
# encoding: UTF-8 require File.join(File.dirname(__FILE__), "helper") setup do "Similique quibusdam consectetur provident sit aut in. Quia dolorem qui nihil expedita quod. Doloremque nobis et labore. Fugit facilis eveniet similique voluptatem dolore rerum laboriosam occaecati. Veniam voluptatem autem in." end test "should format the paragraphs to the default 60 characters wide" do |source| expected = <<-EOS Similique quibusdam consectetur provident sit aut in. Quia dolorem qui nihil expedita quod. Doloremque nobis et labore. Fugit facilis eveniet similique voluptatem dolore rerum laboriosam occaecati. Veniam voluptatem autem in. EOS assert Par.new(source) == expected end test "should relay the passed parameters to par" do |source| expected = <<-EOS Similique quibusdam consectetur provident sit aut in. Quia dolorem qui nihil expedita quod. Doloremque nobis et labore. Fugit facilis eveniet similique voluptatem dolore rerum laboriosam occaecati. Veniam voluptatem autem in. EOS assert Par.new(" #{source}", p: 2) == expected end puts " ✔ All tests passed"
require 'set' # @param {Integer[]} nums # @return {Boolean} def contains_duplicate(nums) set = Set.new nums.each do |elem| return true if set.include? elem set.add elem end return false end nums = [1, 2, 3] p contains_duplicate nums
class PurchasedCustomization < ApplicationRecord belongs_to :order belongs_to :customization end
# frozen_string_literal: true class AddCarrierwaveAssetsToFieldTests < ActiveRecord::Migration[5.0] def change add_column :field_tests, :carrierwave_assets, :string, after: :carrierwave_asset end end
log "Installing gradle version #{node[:gradle][:version]}" do level :info end # On Ubuntu apt installs same version '1.5' of package 'gradle' as chef recipe package 'gradle' do action :install end # NOTE: ignoring possible collsion. include_recipe 'gradle' log 'Finished configuring gradle.' do level :info end
class ExtendAccountTypesDropValues < ActiveRecord::Migration def self.up drop_table :account_values add_column :account_types, :max_monthly_sales, :integer add_column :account_types, :max_products, :integer add_column :account_types, :commission, :boolean add_column :account_types, :flat_fee, :boolean add_column :account_types, :private_storefront, :boolean add_column :account_types, :allow_paypal, :boolean add_column :account_types, :allow_merchant_account, :boolean end def self.down # account values not the right approach remove_column :account_types, :max_monthly_sales remove_column :account_types, :max_products remove_column :account_types, :commission remove_column :account_types, :flat_fee remove_column :account_types, :private_storefront remove_column :account_types, :allow_paypal remove_column :account_types, :allow_merchant_account end end
# frozen_string_literal: true require 'test_helper' class AttachmentsControllerTest < ActionDispatch::IntegrationTest test 'should destroy attachment' do event = events(:one) event.attachments.attach(io: StringIO.new('Test Data'), filename: 'file.pdf') attachment = event.attachments.first assert_difference('ActiveStorage::Attachment.count', -1) do delete attachment_url(attachment) end assert_redirected_to edit_event_url(event) end end
$:.push File.expand_path("../lib", __FILE__) require "coercell/version" Gem::Specification.new do |s| s.name = "coercell" s.version = Coercell::VERSION s.authors = ["Rafael Barros","Gustavo Sales"] s.email = ["rafael.barros@jazz.etc.br","vatsu21@gmail.com"] s.homepage = "https://github.com/inovecomjazz/coercell" s.summary = "A spreadsheet parser and importer to ActiveRecord models" s.description = <<-EOS Parses spreadsheets, validates its data against ActiveRecord model and instanciates valid data EOS s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.add_dependency "rails", "~> 3.2.13" s.add_dependency "roo", "~> 1.12.1" s.add_dependency "rubyzip", "< 1" s.add_development_dependency "sqlite3" s.add_development_dependency "rspec-rails" end
class Asset < ActiveRecord::Base belongs_to :project validates :file, presence: true mount_uploader :file, FileUploader end
class User < ApplicationRecord has_secure_password mount_uploader :image, UserUploader has_many :following_friends, foreign_key: "follower_id", class_name: "Friend", dependent: :destroy has_many :followings, through: :following_friends has_many :follower_friends, foreign_key: "following_id", class_name: "Friend", dependent: :destroy has_many :followers, through: :follower_friends has_many :user_groups has_many :groups, through: :user_groups validates :password, length: {minimum: 4}, on: :create validates :password, length: {minimum: 4}, on: :update, allow_blank: true VALID_PHONE_NUMBER_REGEX = /\A0(\d{1}[-(]?\d{4}|\d{2}[-(]?\d{3}|\d{3}[-(]?\d{2}|\d{4}[-(]?\d{1})[-)]?\d{4}\z|\A0[5789]0[-]?\d{4}[-]?\d{4}\z/ validates :call, presence: true, format: { with: VALID_PHONE_NUMBER_REGEX } # def following?(other_user) # following_friends.find_by(following_id: other_user.id) # end # def follow!(other_user) # following_friends.create!(following_id: other_user.id) # end # def unfollow!(other_user) # following_friendss.find_by(following_id: other_user.id).destroy # end end
#!/usr/bin/env ruby require 'optparse' require 'fileutils' multistage = true stages = ["dev", "prod"] OptionParser.new do |opts| opts.banner = "Usage: #{File.basename($0)} [path]" opts.on("-h", "--help", "Displays this help info") do puts opts exit 0 end opts.on("-n", "--no-multistage", "Disabling multistages") do multistage = false stages = [] end opts.on("-s", "--stages RAW_STAGES", "Specify stages you would like to create --stages dev,prod (first stage is default one)") do |raw_stages| stages = raw_stages.to_s.split(/,/) end begin opts.parse!(ARGV) rescue OptionParser::ParseError => e warn e.message puts opts exit 1 end end if ARGV.empty? abort "Please specify the directory, e.g. `#{File.basename($0)} .'" elsif !File.exists?(ARGV.first) abort "`#{ARGV.first}' does not exist." elsif !File.directory?(ARGV.first) abort "`#{ARGV.first}' is not a directory." elsif ARGV.length > 1 abort "Too many arguments; please specify only one directory." end def unindent(string) indentation = string[/\A\s*/] string.strip.gsub(/^#{indentation}/, "") end base = ARGV.shift is_magento = File.exists? File.join(base,'app/Mage.php') files = {} head = unindent(<<-FILE) set :application, "application" set :domain, "hatimeria.com" set :deploy_to, "/home/www/\#{application}" set :user, "deployment" set :use_sudo, false ssh_options[:forward_agent] = true set :repository, "git@github.com:hatimeria/\#{application}.git" set :scm, :git # Or: `accurev`, `bzr`, `cvs`, `darcs`, `subversion`, `mercurial`, `perforce`, `subversion` or `none` set :deploy_via, :remote_cache set :copy_exclude, [".git"] role :web, domain # Your HTTP server, Apache/etc role :app, domain # This may be the same as your `Web` server role :db, domain, :primary => true # This is where Rails migrations will run set :keep_releases, 3 FILE if is_magento config_path = 'app/etc' files["Capfile"] = unindent(<<-FILE) load 'deploy' if respond_to?(:namespace) # cap2 differentiator load Gem.find_files('magento.rb').last.to_s load Gem.find_files('capimeria_magento.rb').last.to_s load '#{config_path}/deploy' FILE files["#{config_path}/deploy.rb"] = '' else symfony_version = nil symfony_version = symfony_version || ((File.directory? File.join(base, 'config')) ? 1 : 2) symfony_app_path = 'app' if symfony_version == 2 config_path = "#{symfony_app_path}/config" files["Capfile"] = unindent(<<-FILE) load 'deploy' if respond_to?(:namespace) # cap2 differentiator Dir['vendor/bundles/*/*/recipes/*.rb'].each { |bundle| load(bundle) } load Gem.find_files('symfony2.rb').last.to_s load Gem.find_files('capimeria_symfony2.rb').last.to_s load '#{symfony_app_path}/config/deploy' FILE files["#{config_path}/deploy.rb"] = unindent(<<-FILE) set :app_path, "#{symfony_app_path}" set :model_manager, "doctrine" set :update_vendors, true set :vendors_mode, "hatimeria" set :hatimeria_extjs, false set :shared_files, ["app/config/custom.yml"] set :shared_children, [app_path + "/logs", web_path + "/media", "vendor", web_path + "/system"] FILE else config_path = "config" files["Capfile"] = unindent(<<-FILE) load 'deploy' if respond_to?(:namespace) # cap2 differentiator Dir['plugins/*/lib/recipes/*.rb'].each { |plugin| load(plugin) } load Gem.find_files('symfony1.rb').last.to_s load Gem.find_files('capimeria_symfony1.rb').last.to_s load 'config/deploy' FILE files["#{config_path}/deploy.rb"] = '' end end if multistage stages.each do |stage| files["#{config_path}/deploy/#{stage}.rb"] = unindent(<<-FILE) set :deploy_to, "/home/www/\#{application}/#{stage}" FILE end multi = unindent(<<-FILE) set :stages, %w(#{stages.join(' ')}) set :default_stage, "#{stages.first}" set :stage_dir, "#{config_path}/deploy" require 'capistrano/ext/multistage' FILE else multi = '' end files["#{config_path}/deploy.rb"] = multi + "\n\n" + head + "\n\n" + files["#{config_path}/deploy.rb"] files.each do |file, content| file = File.join(base, file) if File.exists?(file) warn "[skip] '#{file}' already exists" elsif File.exists?(file.downcase) warn "[skip] '#{file.downcase}' exists, which could conflict with `#{file}'" else unless File.exists?(File.dirname(file)) puts "[add] making directory '#{File.dirname(file)}'" FileUtils.mkdir(File.dirname(file)) end puts "[add] writing '#{file}'" File.open(file, "w") { |f| f.write(content) } end end puts "[done] Project was capimariand!"
require 'rails_helper' RSpec.describe 'mechanics show page' do before do @mechanic1 = Mechanic.create(name: 'Kara Smith', years_experience: 11) @mechanic2 = Mechanic.create(name: 'Sam Jones', years_experience: 7) @ride1 = Ride.create(name: 'Ferris Wheel', thrill_rating: 3, open: true) visit "/mechanics/#{@mechanic1.id}" end it 'i see the mechanic attributes' do expect(page).to have_content("Mechanic: #{@mechanic1.name}") expect(page).to have_content("Years of Experience: #{@mechanic1.years_experience}") end it 'only shows the rides that are open' do # expect(page).to have_content("Current rides they're working on: #{@mechanic1.working_on}") end it 'shows rides in order by thrill rating' do end describe 'add a ride to a mechanic' do it 'i see a form to add a ride to workload' do end it 'when submitted, i see the newly added ride to mechanic show page' do require "pry"; binding.pry end end end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Typhoid::RequestBuilder do context "a request builder object" do it "should provide an http method by default" do req = Typhoid::RequestBuilder.new(Game, 'http://localhost/') req.http_method.should eql :get end it "should set http method from options" do req = Typhoid::RequestBuilder.new(Game, 'http://localhost', :method => :post) req.http_method.should eql :post end end end
module Shipindo module Helpers module RupiahToFloat # convert rupiah string to float # @param [Hash] options conversion options # @option options [String] :prefix ("Rp.") prefix to remove # @option options [String] :thousand_separator (".") separator for thousands # @option options [String] :cent_separator (",") separator for cents def rupiah_to_float(options={}) options[:prefix] ||= "Rp." options[:thousand_separator] ||= "." options[:cent_separator] ||= "," text = self.gsub(options[:prefix],"").gsub(options[:thousand_separator],"") if text.include?(options[:cent_separator]) && options[:cent_separator] != "." text = text.gsub(options[:cent_separator], ".") end text.to_f end alias :rp_to_f :rupiah_to_float end end end class String include Shipindo::Helpers::RupiahToFloat end
# Models class Bird include Mongoid::Document field :name, type: String field :family, type: String field :continents, type: Array field :added, type: String, default: -> { Date.today } field :visible, type: Boolean, default: -> { false } validates :name, presence: true validates :family, presence: true validates :continents, presence: true validate :verified_continents_type validate :verified_continents_size validate :verified_continents_uniqueness #index :name scope :family, ->(family) { where(family: family) } scope :name, ->(name) { where(name: name) } scope :only_visible, -> { where(visible: true) } def verified_continents_type return if continents.all? { |i| i.is_a?(String) } errors.add(:continents, 'Continent should be string only') end def verified_continents_size return unless continents.size.zero? errors.add(:continents, 'Continent should be contain atleast one item') end def verified_continents_uniqueness return unless continents.size != continents.uniq.size errors.add(:continents, 'Continent should have uniq items') end end
require 'spec_helper' feature 'invitation' do background do clear_email end after { clear_email } scenario 'user sends out an invitation and has it fulfilled', {js: true, vcr: true} do charge = double(charge, successful?: true) StripeWrapper::Charge.stub(:create).and_return(charge) bob = Fabricate(:user, email: 'joe@joe.com', password: "password") user_signs_in(bob) invite_friend open_mail expect(current_email).to have_content "Hi Joe Bloggs" expect(page).to have_content('Your invitation has been sent') sign_out current_email.click_link('click here to join') visit invitation_path(Invitation.first) clear_email expect(find('#user_email').value).to eq('joe@example.com') fill_in_sign_up_form sleep 2 open_mail expect(current_email).to have_content "Hi Joe Bloggs" click_people expect(page).to have_content("#{bob.full_name}") sign_out user_signs_in(bob) click_people expect(page).to have_content("Joe Bloggs") clear_email end def invite_friend click_link 'People' click_link 'Invite a Friend' fill_in(:invitation_name, with: 'Joe Bloggs') fill_in(:invitation_email, with: 'joe@example.com') click_button('Send Invitation') end def sign_out find('a.dropdown-toggle').click click_link('Sign Out') end def open_mail open_email('joe@example.com') end def fill_in_sign_up_form fill_in(:user_password, with: 'password') fill_in(:user_full_name, with: 'Joe Bloggs') within_frame(find('iframe')) do find('input[name="cardnumber"]').set('4000000000000002') find('input[name="exp-date"]').set('0122') find('input[name="cvc"]').set('123') find('input[name="postal"]').set('12345') end click_button('Sign Up') end def click_people click_link('People') end end
Gem::Specification.new do |s| s.name = 'aqueductron' s.version = '0.0.2' s.date = '2013-03-05' s.summary = 'Dataflow in a functional, self-modifying pipeline style' s.description = 'Aqueductron lets you create a path for data, then flow data through it, then find the results at the end. It encourages a functional style, avoiding mutable values. It uses iteratees to let the path change itself as the data passes.' s.authors = ['Jessica Kerr'] s.email = 'jessitron@gmail.com' s.files = Dir['lib/**/*.rb'] s.license = 'MIT' s.homepage = 'http://github.com/jessitron/aqueductron' end
require "spec_helper" describe Api::HabitDescriptionsController, type: :controller do before do coach = create(:coach) login(coach) @habit_description = create_list(:habit_description, 2, user: coach).first end describe "GET #index" do before do another_coach = create(:coach) create_list(:habit_description, 2, user: another_coach) end it "should query 2 HabitDescriptions" do get(:index) expect(json.count).to eq 2 end end describe "GET #show" do it "should read 1 HabitDescription" do get( :show, id: @habit_description.id) expect(json["name"]).to eq(@habit_description.name) end end describe "POST #create" do context "with valid attributes" do it "should create HabitDescription" do habit_description_attributes = attributes_for(:habit_description, tag_list: "") expect do post( :create, habit_description: habit_description_attributes) end.to change(HabitDescription, :count).by(1) end end context "with invalid attributes" do it "should not create HabitDescription" do habit_description_attributes = attributes_for(:habit_description, name: nil) expect do post( :create, habit_description: habit_description_attributes) end.to change(HabitDescription, :count).by(0) end end end describe "PATCH #update" do context "with valid attributes" do it "should update HabitDescription" do name = "NAME#{rand(1000)}" tag_list = "" patch( :update, id: @habit_description.id, habit_description: { name: name, tag_list: tag_list }) expect(HabitDescription.find(@habit_description.id).name).to eq(name) end end context "with invalid attributes" do it "should not update HabitDescription" do name = "EXCEEDS MAX LENGTH" * 10 patch( :update, id: @habit_description.id, habit_description: { name: name }) expect(HabitDescription.find(@habit_description.id).name).to eq(@habit_description.name) end end end describe "DELETE #destroy" do it "should delete HabitDescription when not in use" do expect do delete( :destroy, id: @habit_description.id) end.to change(HabitDescription, :count).by(-1) end it "should not delete HabitDescription when in use" do create(:habit_log, habit_description: @habit_description) expect do delete( :destroy, id: @habit_description.id) end.to change(HabitDescription, :count).by(-1) expect(HabitDescription.where(id: @habit_description.id).unscope(where: :id)).to exist end end end
# Generate a gallery from an image gallery subreddit. Requires imagemagick to be installed in your # path. Assumes the billboards are rendered at 512x512. require 'open-uri' require 'json' require 'uri' # For the vector class # (note: install gmath3D gem if not already installed) require 'gmath3D' SUBREDDIT = "aww".downcase DOWNLOAD = true puts "Fetching /r/#{SUBREDDIT} as json..." json = JSON.parse(open("http://www.reddit.com/r/#{SUBREDDIT}.json").readlines.join) puts "Downloading and resizing images..." `rm scenes/images/r-#{SUBREDDIT}-* 2>/dev/null` if DOWNLOAD xml = "<scene>\n" xml += <<-EOF <spawn position="0 0 0" /> EOF i = 0 json["data"]["children"].each do |child| story = child["data"] title = story["title"].slice(0,70) # to do.. # why check title is sliced exactly 70 chars? # eg. no sub needed for shorter length titles. # why is title not space or dot padded first? if title.length == 70 title = title.sub(/\.+$/, '') + "..." end uri = URI.parse(story["url"]) extension = File.extname(uri.path).downcase # jpg, jpeg, png... next unless extension == ".jpg" || extension == ".jpeg" || extension == ".png" puts " * #{uri.to_s}" if DOWNLOAD `curl #{uri.to_s} -s -o scenes/images/r-#{SUBREDDIT}-#{i}#{extension}` || next `mogrify -resize 500x450 scenes/images/r-#{SUBREDDIT}-#{i}#{extension}` || next end x = i % 5 z = (i / 5).floor v = GMath3D::Vector3.new(x, 0, -z) * 5 v += GMath3D::Vector3.new(5, 1.5, -5) height = `identify scenes/images/r-#{SUBREDDIT}-#{i}#{extension}`.match(/x(\d+)/)[1].to_i margin = (512 - 40 - height) / 2 xml += <<-EOF <billboard position="#{v.x} #{v.y} #{v.z}" rotation="0 0 0" scale="3 3 0.3"> <![CDATA[ <center style="margin-top: #{margin}px; font-size: 2em"> <img src="/images/r-#{SUBREDDIT}-#{i}#{extension}" style="max-width: 100%" /><br /> #{title} </center> ]]> </billboard> EOF i += 1 end xml += "</scene>" File.open("./scenes/r-#{SUBREDDIT}.xml", "w") { |f| f.write xml } puts "Visit /r-#{SUBREDDIT}.xml to see the gallery."
require 'open3' module Girth class Repo def self.open(dir = nil) repo = new(dir) if block_given? && block.arity == 1 yield repo elsif block_given? repo.instance_eval(&block) else repo end end attr_reader :git_dir def self.init(dir = nil, bare = false, &block) command = %w(git) command << "--bare" if bare command << "init" command << "-q" begin old_dir = ENV["GIT_DIR"] ENV["GIT_DIR"] = nil dir ||= old_dir || "." Dir.chdir(dir) do Open3.popen3(*command) do |i,o,e| errors = e.read raise Executor::Error, errors, caller unless errors.empty? end end ensure ENV["GIT_DIR"] = old_dir end open(dir, &block) end def initialize(dir = nil) old_dir = ENV["GIT_DIR"] ENV["GIT_DIR"] = nil @argument = dir || old_dir || "." Dir.chdir(@argument) do @git_dir = Open3.popen3("git","rev-parse","--git-dir") do |i,o,e| o.read.chomp end raise Error, "fatal: Not a git repository" if @git_dir.to_s.empty? if @git_dir == "." # Inside the git dir failed = 16.times do if File.directory?(@git_dir+"/objects") && File.directory?(@git_dir+"/refs") && File.exists?(@git_dir+"/HEAD") break false end @git_dir = File.join("..", @git_dir) end if failed raise Error, "fatal: Not a git repository" end end @git_dir = ::File.join(".",@git_dir) if @git_dir[0] == ?~ @git_dir = ::File.expand_path(@git_dir) end ensure ENV["GIT_DIR"] = old_dir end # +self+ def repo self end alias repository repo # The working tree, or +nil+ in a bare repository. def work_tree if ::File.basename(@git_dir) == ".git" ::File.dirname(@git_dir) end end def bare? !work_tree end # Call the block while chdired to the working tree. In a bare repo, the # git dir is used instead. def in_work_tree(&block) Dir.chdir(work_tree || @git_dir,&block) end def ref(path) ref = Girth::Ref.new(self, path) if path =~ /^[[:xdigit:]]{40}(\^\{\w+\})?$/ ref.object else ref end end def [](path) if path =~ /^[[:xdigit:]]{40}$/ instantiate_object(path) elsif path =~ /^([[:xdigit:]]{4,40})(?:\^\{(\w+)\})?$/ instantiate_object(git.rev_parse(path)) else Girth::Ref.new(self, path) end end def fetch(path) ref(path).object end alias object fetch def instantiate_object(sha1, type = nil) #:nodoc: raise Error, "Full SHA1 required" unless sha1 =~ /^[[:xdigit:]]{40}$/ type ||= git.exec("cat-file","-t",sha1).chomp case type when "tag" then Girth::Tag.new(self,sha1) when "commit" then Girth::Commit.new(self,sha1) when "tree" then Girth::Tree.new(self,sha1) when "blob" then Girth::Blob.new(self,sha1) else raise "unknown type #{type}" end end # Find an object. def rev_parse(rev) instantiate_object(git.rev_parse(rev)) end alias ` rev_parse # HEAD ref def head ref("HEAD") end # ORIG_HEAD ref def orig_head ref("ORIG_HEAD") end def refs @refs ||= Girth::Ref::Collection.new(self,"refs") end def heads refs.heads(:collection) end def remotes refs.remotes(:collection) end def tags refs.tags(:collection) end def inspect "#{Girth.inspect}[#{@argument.inspect}]" end def each_ref(*args) pattern = args.empty? ? "refs" : args.join("/") git.exec("for-each-ref", "--format=%(objectname) %(refname)", pattern) do |line| yield(*line.chomp.split(" ",2)) end end def rev_list(*args) RevList.new(self,args) end # Runs Girth::Executor::x in the work tree or git dir. def x(*args) in_work_tree do Executor.x(*args) end end def author Identity.parse(git.exec("var","GIT_AUTHOR_IDENT")) end def committer Identity.parse(git.exec("var","GIT_COMMITTER_IDENT")) end def method_missing(method,*args,&block) if args.empty? [refs,tags,heads,remotes].each do |group| ref = group[method] and return ref end end super(method,*args,&block) end def create(content) if content.kind_of?(Hash) git.popen3("hash-object","-t","tree","-w","--stdin") do |i,o,e| content.sort.each do |filename, object| if filename.to_s =~ /[\0\/]/ raise ArgumentError, "tree filenames can't contain nulls or slashes", caller end if object.respond_to?(:tree) i.write "040000 #{filename}\0#{object.tree.binary_sha1}" elsif object.respond_to?(:blob) i.write "100644 #{filename}\0#{object.blob.binary_sha1}" else raise ArgumentError, "trees can only contain trees and blobs", caller end end i.close Tree.new(self,o.read.chomp) end else git.popen3("hash-object","-w","--stdin") do |i,o,e| if content.respond_to?(:read) while hunk = content.read(1024) i.write hunk end else i.write(content.to_str) end i.close Blob.new(self,o.read.chomp) end end end # Returns a Girth::Config object. def config(include_global = true) Girth::Config.new(self, include_global) end # Returns a Girth::Executor object for running commands. # # repo.git.exec("status") #=> "...output of git status..." def git @git ||= Executor.new(self) end end Repository = Repo end
require "./player" # This class provides the basic functionality # for making guesses toward the code. class Codebreaker < Player # Initializes instance variables that # are useful only when the computer is # playing as codebreaker def initialize @previous_black_pins = -1 # -1 to distinguish between first round # of feedback and every other round. @previous_guesses = [] @known_pins = 0 end # This method is used when the user of the # game chooses to be the codemaker instead. # This method takes in an array of strings # representing the last row of the game board # and return a new guess array. def computer_guess(row) code = [] if row.nil? # if first guess code = generate_code @previous_guesses << code[0] else current_black_pins = row[2][-1] last_guess = row[1].split if (@previous_black_pins != -1) && (current_black_pins > @previous_black_pins) @known_pins += 1 @previous_black_pins = current_black_pins # Update record of black pins for future turns @previous_guesses = [last_guess[@known_pins]] # Start off with next color to the right # and record it as your previous guess since # we are about to guess a new color in its # place. elsif (@previous_black_pins != -1) && (current_black_pins < @previous_black_pins) last_guess[@known_pins] = @previous_guesses[-2] # Since black pins went down after our last guess, # we should go back to our guess before the last one. @known_pins += 1 @previous_guesses = [last_guess[@known_pins]] # Start off with next color to the right # and record it as your previous guess since # we are about to guess a new color in its # place. elsif @previous_black_pins == -1 # If it's the first round. @previous_black_pins = current_black_pins # Update record of black pins for future turns. end guess = (@@accepted_colors - @previous_guesses).sample @previous_guesses << guess last_guess[@known_pins] = guess # Keep everything the same as your last guess except for the # current color that we're guessing. code = last_guess end code end end
class AddDeletedToWesellItems < ActiveRecord::Migration def change add_column :wesell_items, :deleted, :boolean, default: false, null: false WesellItem.where('status = 11').update_all deleted: true, status: 10 end end
class BoardsController < ApplicationController include ActionView::Helpers::AssetTagHelper def controller;self;end;private(:controller) before_filter :signed_in_user_board, only: [:new, :create] def new @board = Board.new end def create @board = current_user.boards.create(params[:board]) if @board.save #create the fake ad with the controller @advertisement = @board.advertisements.build() @advertisement.x_location = 0 @advertisement.y_location = 0 @advertisement.height = @board.height @advertisement.width = @board.width path = Rails.root.to_s + image_path("bg.jpg") @advertisement.image = File.open(path,"rb") { |io| io.read } @advertisement.user = current_user @advertisement.save flash[:success] = "Board created" redirect_to @board else flash.now[:error] = 'Invalid board information' render 'new' end end def index @boards = Board.all end def show @board = Board.find(params[:id]) @ads = @board.advertisements end end
####### # NOTE! # - Can take hours # - Need to create ports & fronts in Redis Datamapper via script/rserve_dm.rb first ####### task data_mapper: ["data_mapper:create_database_records"] namespace :data_mapper do # To create records in DataMapper/redis: `script/rserve_dm.rb` desc "Loads up efficient frontiers to database from previously created Redis DataMapper models" task create_database_records: :environment do previous_level_AR = ActiveRecord::Base.logger.level begin # Make sure not to generate the long log outputs when updating these # attributes. Slows stuff down ActiveRecord::Base.logger.level = Logger::ERROR require 'digest' require 'data_mapper' require 'dm-redis-adapter' require 'script/objects/dm_port.rb' require 'script/objects/dm_frontier.rb' ################### DataMapper.setup(:default, { adapter: "redis", db: 15 }); DataMapper::Model.raise_on_save_failure = true $redis = Redis.new(db: 15) DataMapper.finalize #################### ## # Clear state Portfolio.delete_all EfficientFrontier.delete_all $redis.del "created-dm-portfolios" ### require 'java' @count = java.util.concurrent.atomic.AtomicInteger.new(0) approximate_total_ports = 4789900 # For 18 assets #################### tickers = Security.all.map(&:ticker) (1..tickers.length).each do |number_of_assets| tickers.combination(number_of_assets).to_a.each do |combo| dm_efficient_frontier = DmEfficientFrontier.with_allowable_securities combo dm_portfolios = dm_efficient_frontier.dm_portfolios efficient_frontier = EfficientFrontier.new dm_portfolios.each do |dm_portfolio| allocation = dm_portfolio.weights portfolio_created = $redis.sismember("created-dm-portfolios", dm_portfolio.id) if portfolio_created portfolio = Portfolio.with_weights(allocation) else portfolio = Portfolio.create!(weights: allocation) $redis.sadd "created-dm-portfolios", dm_portfolio.id current_count = @count.incrementAndGet if current_count%100 == 0 pct_complete = (current_count.to_f / approximate_total_ports) * 100 puts "Created #{current_count} portfolios. Approximate % complete: #{pct_complete}." end end efficient_frontier.portfolios << portfolio end efficient_frontier.save! end # combo end # number_of_assets ensure ActiveRecord::Base.logger.level = previous_level_AR end puts "********\nFINISHED\n********" puts "If it worked, you probably want to: $redis = Redis.new(db: 15); $redis.flushdb" end # task create_database_records_from_datamapper end # datamapper namespace