text
stringlengths
10
2.61M
require 'ansi/progressbar' module StormFury::CLI class ProgressReport attr_reader :bar, :server def self.run(server) progress_report = new(server) progress_report.run end def initialize(server) @bar = ANSI::Progressbar.new(server.name, 100) @server = server end def increment!(value = nil) if value value.times { bar.inc } else bar.inc end end def run progress = server.progress.to_i until server.ready? sleep(2) server.reload progress = server.progress - progress increment! progress end bar.finish end end end
#!/usr/bin/env ruby # has to be fed in reverse order, from least to most # 37396 is a magic number, if you spot it, the number of lines in the dump require 'pry' CUTOFF=3 def nuke(msg, idx, term) STDERR.print ARGF.filename, ': ', msg, ': ', idx, '; ', "#{term}\n" end STOPWORDS=['edition', 'book', 'chapter', 'adelaide', 'texas'] # 'I' as a roman numeral was probably mis-parsed by Saffron NUMERALS=['ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix', 'x', 'xi', 'xii', 'xiii', 'xiv', 'xv', 'xvi', 'ch'] # 'thou art' :( ARCHAISMS=['thy', 'thou', 'thine', 'thee', 'mine', 'hath', 'ye', 'nay', 'showeth'] # don't downcase PROPER=['God'] # proabable hyphenated words OK_HYPHENS=['pre-Darwinian', 'ante-Christian', 'Christian-Teutonic', 'Graeco-Roman', 'Ural-Altaic', 'Psycho-Analytic', 'Greatest-Happiness', 'post-Kantian', 'Anglo-North', 'Gnostic-Theosophic', 'Dalai-Lama', 'Father-in-Law', 'Vice-President', 'Free-as-a-Bird', 'Teutonico-Christian', 'anti-Christian', 'World-Cause', 'Victoriously-Perfect', 'Port-Royal', 'pre-Aryan', 'Anglo-American', 'pre-Christian', 'Kant-Fichteian', 'States-General', 'East-Indies', 'Non-Contradiction', 'Self-Surpassing', 'Ass-Festival', 'Non-Ego', 'not-Self', 'non-Ego'] # fi → fi # eventually must have _only_ text, or very light markup that topic modeller/inferer understands master = [] ARGF.each_with_index do |line, idx| #STDERR.print ARGF.filename, ': ', idx, '; ', line begin totes, term, pattern = line.split(', ') the_sub_terms = term.split(' ') pattern.strip! the_sub_patterns = pattern.split(' ') # raise "pattern: #{pattern} doesn't match" if NUMERALS.any? {|num| the_sub_terms.map(&:downcase).include?(num) ? true : false} nuke "NUMERAL", idx, term elsif ARCHAISMS.any? {|arch| the_sub_terms.map(&:downcase).include?(arch) ? true : false} nuke "ARCHAISM", idx, term elsif !(term =~ /^[[:alpha:] -]+[[:alpha:]]+--[[:alpha:]][[:alpha:] -]+$/).nil? nuke "DOUBLE --", idx, term elsif STOPWORDS.any? {|stop| !(term.downcase =~ /.*#{stop}.*/).nil? ? true : false} nuke "STOPWORD", idx, term elsif !(term =~ /\b[[:upper:]]+\b/).nil? nuke "ALL CAPS", idx, term elsif (the_sub_terms.length != the_sub_patterns.length) and !OK_HYPHENS.any? {|hype| the_sub_terms.include?(hype) ? true : false} nuke "BAD HYPHEN", idx, term else last = the_sub_patterns.last common = (last == 'NN' or last == 'NNS') upcase = term.scan(/[[:upper:]]/).length down = (PROPER.include?(term) ? term : term.downcase) master[idx] = {totes: totes.to_i, term: term, down: down, pattern: pattern, common: common, upcase: upcase, processed: false} end rescue => e # STDERR.puts e.message # STDERR.puts e.backtrace nuke "OOF! #{e}", idx, term # binding.pry end end def output(totes, term, pattern) STDOUT.puts "#{totes}, #{term}, #{pattern}" end max = master.length bump = [] new_totes = 0 old_bump_length = 0 master.each_with_index do |line, idx| # skip over holes created by STOPWORDS, ARCHAISMS, and NUMERALS if not line.nil? if bump.length != old_bump_length # binding.pry # STDERR.puts "#{line[:totes]}; index - #{idx}; bump length - #{bump.length}" old_bump_length = bump.length end # make sure new_totes tracks current totes if line[:totes] > new_totes new_totes = line[:totes] end del = 0 bump.each do |b| if b[:totes] < new_totes output(b[:totes], b[:term], b[:pattern]) del += 1 else break end end bump.slice!(0,del) # ignore lines that have been processed if not line[:processed] line[:processed] = true j = idx+1 matched = [] while j < max if not master[j].nil? and (line[:down] == master[j][:down]) master[j][:processed] = true matched << j end j += 1 end if matched.length > 0 matched << idx common = -1 acc = 0 matched.each do |i| acc += master[i][:totes] if master[i][:common] if 0 <= common # choose the one with the most lowercase if master[i][:upcase] < master[common][:upcase] common = i end else # first one common = i end end end # ignore the rest for the moment if acc >= CUTOFF if 0 > common matched.each do |i| nuke "UNCOMMON", i, "#{master[i][:totes]}, #{master[i][:term]}, #{master[i][:pattern]}" end else ins = 0 bump.each_with_index do |b, i| if b[:totes] < acc ins = i+1 else break end end # insert accumulated match in sequential order bump.insert(ins,master[common].dup) bump[ins][:totes] = acc end end else output(line[:totes], line[:term], line[:pattern]) if line[:totes] >= CUTOFF end end end end del = 0 bump.each_with_index do |b| output(b[:totes], b[:term], b[:pattern]) del += 1 end bump.slice!(0,del)
# 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) require 'active_record/fixtures' #Load defaults from db/seed/fixtures Dir.glob(File.join(Rails.root, 'db', 'seed', 'fixtures', '**', '*.{yml,csv}')).each do |fixture_file, something| ActiveRecord::Fixtures.create_fixtures(File.dirname(fixture_file), File.basename(fixture_file, '.*')) end #Load bike brands and models from sql if BikeBrand.all.empty? and BikeModel.all.empty? # Need to use DEFAULT instead of explicit IDs that are used in the sql file, # so that the PG table ID sequence is incremented # # Note the drop(1) which assumes we have a junk PRAGMA line at the top ['common_wheel_sizes.sql', 'bike_brands_and_models.sql'].each do |sql| load_statements = File.readlines(File.join(Rails.root, 'db', 'seed', 'sql', sql)).drop(1).map do |statement| statement.sub(/VALUES\(\d+,/, 'VALUES(DEFAULT,') end ActiveRecord::Base.connection.execute(load_statements.join) end end if Rails.env.development? #create default users if User.all.empty? u = FactoryGirl.create(:user) FactoryGirl.create(:user_profile, user_id: u.id) u = FactoryGirl.create(:staff) FactoryGirl.create(:user_profile, user_id: u.id) u = FactoryGirl.create(:bike_admin) FactoryGirl.create(:user_profile, user_id: u.id) u = FactoryGirl.create(:admin) FactoryGirl.create(:user_profile, user_id: u.id) end #create fake bikes if Bike.all.empty? 42.times do |n| FactoryGirl.create(:seed_bike) end end elsif Rails.env.production? unless User.find_by_username('admin') #create an admin admin = User.create!( :username => 'admin', :first_name => 'admin', :last_name => 'admin', :email=>'admin@example.com', :password=>'password') admin.roles << Role.find_by_role('admin') end end
require 'spotify_web/resource' require 'spotify_web/album' require 'spotify_web/artist' require 'spotify_web/schema/bartender.pb' require 'spotify_web/schema/metadata.pb' module SpotifyWeb # Represents a song on Spotify class Song < Resource self.metadata_schema = Schema::Metadata::Track self.resource_name = 'track' def self.from_search_result(client, attributes) #:nodoc: attributes = attributes.merge( 'name' => attributes['title'], 'artist' => [{ :id => attributes['artist_id'], :name => attributes['artist'] }], 'album' => { :id => attributes['album_id'], :name => attributes['album'], :artist => [{ :id => attributes['album_artist_id'], :name => attributes['album_artist'] }] }, 'number' => attributes['track_number'], 'restriction' => [attributes['restrictions']['restriction']].flatten.map do |restriction| { :countries_allowed => restriction['allowed'] && restriction['allowed'].split(',').join, :countries_forbidden => restriction['forbidden'] && restriction['forbidden'].split(',').join } end ) super end # The title of the song # @return [String] attribute :title, :name # Info about the artist # @return [SpotifyWeb::Artist] attribute :artist do |artist| Artist.new(client, artist[0].to_hash) end # Info about the album # @return [SpotifyWeb::Album] attribute :album do |album| Album.new(client, album.to_hash) end # The disc the song is located on within the album # @return [Fixnum] attribute :disc_number # The track number on the disc # @return [Fixnum] attribute :number do |value| value.to_i end # Number of seconds the song lasts # @return [Fixnum] attribute :length, :duration do |length| length / 1000 end # The relative popularity of this song on Spotify # @return [Fixnum] attribute :popularity do |value| value.to_f end # The countries for which this song is permitted to be played # @return [Array<SpotifyWeb::Restriction>] attribute :restrictions, :restriction do |restrictions| restrictions.map {|restriction| Restriction.new(client, restriction.to_hash)} end # Whether this song is available to the user # @return [Boolean] def available? restrictions.all? {|restriction| restriction.permitted?(:country)} end # Looks up songs that are similar to the current one # @return [Array<SpotifyWeb::Song>] def similar response = api('request', :uri => "hm://similarity/suggest/#{uri_id}", :payload => Schema::Bartender::StoryRequest.new( :country => client.user.country, :language => client.user.language, :device => 'web' ), :response_schema => Schema::Bartender::StoryList ) # Build songs based on recommendations songs = response['result'].stories.map do |story| song = story.recommended_item album = song.parent artist = album.parent Song.new(client, :uri => song.uri, :name => song.display_name, :album => { :uri => album.uri, :name => album.display_name, :artist => [{ :uri => artist.uri, :name => artist.display_name }] }, :artist => [{ :uri => artist.uri, :name => artist.display_name }] ) end ResourceCollection.new(client, songs) end end end
#encoding: utf-8 class User < ActiveRecord::Base belongs_to :person has_secure_password attr_accessible :password, :username, :password_confirmation, :person, :person_id validates :username, :presence => true, :uniqueness => true validates :utype, :presence => true, :numericality => { :only_integer => true, :less_than => 2, :greater_than_or_equal_to => 0 } validates_presence_of :password, :on => :create validate :person, :presence => true, :uniqueness => true before_save :normalizeAttributes def normalizeAttributes self.username = self.username.downcase end end
class BoatingTest attr_reader :student, :instructor, :test_name attr_accessor :status @@all = [] ###### Instance methods ###### #Works! def initialize(student, instructor, test_name, status) @student = student @instructor = instructor @test_name = test_name @status = status @@all << self end ###### Class methods ###### #Works! def self.all() @@all end end
# Define a method meal_choice that returns the meal_choice that was # passed into it and defaults to meat. def meal_choice(meal=nil) if meal "#{meal}" else "meat" end end
json.array!(@documentos) do |documento| json.extract! documento, :id, :tipo_documento, :fecha_ingreso, :observacion, :estudiante_id json.url documento_url(documento, format: :json) end
class DepositionsController < ApplicationController def index end def new session[:deposition_params] ||= {} @deposition = Deposition.new end def create session[:deposition_params].deep_merge!(deposition_params) @deposition = Deposition.new(session[:deposition_params]) @deposition.current_step = session[:deposition_step] if @deposition.valid? if params[:back_button] @deposition.previous_step elsif params[:next_button] @deposition.next_step elsif @deposition.last_step? @deposition.save if @deposition.all_valid? end session[:deposition_step] = @deposition.current_step end if @deposition.new_record? render :new else session[:deposition_step] = session[:deposition_params] = nil redirect_to deposition_path(@deposition) end end def show @deposition = Deposition.find(params[:id]) end def deposition_params params.require(:deposition).permit(:dep_city, :arr_city, :reason, :excuse, :departure, :arrival, :forward, :forward_dep, :forward_arr, :alert_date, :delay) end end
class AddFaviconUrlAndDescriptionToBookmark < ActiveRecord::Migration def self.up add_column :bookmarks, :favicon_url, :string add_column :bookmarks, :description, :text end def self.down remove_column :bookmarks, :description remove_column :bookmarks, :favicon_url end end
# == Schema Information # # Table name: release_order_results # # id :integer not null, primary key # release_order_id :integer indexed, indexed => [env_id, application_id] # env_id :integer indexed, indexed => [release_order_id, application_id] # status :integer default("unknown") # created_at :datetime not null # updated_at :datetime not null # application_id :integer indexed => [release_order_id, env_id] # application_with_version_id :integer # log :text default("") # # Indexes # # index_release_order_results_on_env_id (env_id) # index_release_order_results_on_release_order_id (release_order_id) # uniq_result (release_order_id,env_id,application_id) UNIQUE # describe ReleaseOrderResult, type: :model do it { is_expected.to define_enum_for(:status) .with_values(%i[unknown success failure]) } it { is_expected.to belong_to(:release_order) } it { is_expected.to belong_to(:env) } it { is_expected.to belong_to(:application) } it { is_expected.to belong_to(:application_with_version) } end
class WorkExperienceLookedHistory < ApplicationRecord belongs_to :user belongs_to :work_experience scope :created_at_paging, -> { order(created_at: :desc) } end
module HttpFetcher class << self def fetch(url) response = HTTParty.get(url) unless response.code == 200 raise Exceptions::HttpException.new("Requested resource returned HTTP status: #{response.code}", response.code) end response rescue SocketError => e raise Exceptions::HttpException.new('Unable to reach specified URL') end end end
module XMLNBI require 'net/http' require 'open-uri' require 'nokogiri' class XmlSessionError < StandardError; end class InvalidSessionId < XmlSessionError; end class InvalidParameter < XmlSessionError; end class InvalidXMLRequest < XmlSessionError; end class XMLServer @@port = "18080" @@xml4login = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" \ + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">" \ + "<soapenv:Body>" \ + "<auth message-id=\"1\">" \ + "<login>" \ + "<UserName>%s</UserName>" \ + "<Password>%s</Password>" \ + "</login>" \ + "</auth>" \ + "</soapenv:Body>" \ + "</soapenv:Envelope>" def initialize host, user, password @host = host @http = Net::HTTP.new(@host, @@port) @http.open_timeout = 60 @http.read_timeout = 600 @http.start() rsp = send_request(@@xml4login%[user, password]) @sessionId = rsp.scan(/<SessionId>(\d+)<\/SessionId>/i)[0][0] end def execute xml raise InvalidParameter unless xml.instance_of?(String) xml.gsub!(/ sessionid="\d+"/i) {|m| m.split("=")[0] + "=" + "\"#{@sessionId}\""} rst = send_request(xml) rst end def exit @http.finish() end private def send_request xml uri = "http://#{@host}:#{@@port}/" xmls = xml.to_s if xmls.include?("Msap") uri << "cmsweb/nc" elsif xmls.include?("E5100") uri << "cmsweb/nc" elsif xmls.include?("AeCMSNetwork") uri << "cmsae/ae/netconf" elsif xmls.include?("nodename") and not xmls.include?("AeCMSNetwork") uri << "cmsexc/ex/netconf" else uri << "cmsweb/nc" # raise InvalidXMLRequest, xml end req = Net::HTTP::Post.new(uri) req['content-type'] = "text/plain;charset=UTF-8" req.body = xmls rsp = @http.request(req) rst = Nokogiri::XML(rsp.body,&:noblanks).to_xml rst.gsub!("<?xml version=\"1.0\"?>", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") rst end end end if __FILE__ == $0 xmler = XMLNBI::XMLServer.new("10.245.252.104", "rootgod", "root") s = "" File.open('C:\MyWork\XMLNBI\E72\xmlreq\create-data_svc.xml', 'r+') do |f| s << f.read end puts xmler.execute(s) end
require "rails_helper" RSpec.describe EmailAuthentication, type: :model do let(:weak_password_error) { "Please choose a stronger password with at least 8 characters. Try a mix of letters, numbers, and symbols." } describe "Associations" do it { should have_one(:user_authentication) } it { should have_one(:user).through(:user_authentication) } end it "requires a non blank password" do auth = build(:email_authentication, password: "") expect(auth).to_not be_valid expect(auth.errors.messages[:password]).to eq [weak_password_error] end it "requires a strong password" do auth = build(:email_authentication) ["password", "passw0rd", "12345678", "1234abcd", "aaaaaaaa", "catsdogs", "foobar", "cats dogs"].each do |password| auth.password = password expect(auth).to_not be_valid, "password #{password} should not be valid" expect(auth.errors.messages[:password]).to eq [weak_password_error] end end it "allows strong passwords" do auth = build(:email_authentication) ["three word passphrase", "stubborn kosher rehire", "brown batter horse pumpkin", "speaker imac coverage flower", "@zadlfj4809574zk.vd", "long-pass-phrase-verklempt-basketball"].each do |password| auth.password = password expect(auth).to be_valid, "password #{password.inspect} should not be valid" end end it "allows email to be updated even if the EmailAuthentication has a weak password" do auth = build(:email_authentication, password: "1234567890") auth.save(validate: false) auth = EmailAuthentication.find(auth.id) auth.email = "newemail@example.com" expect(auth).to be_valid auth.save! # make sure a weak password change is prevented auth.password = "passw0rd" expect(auth).to_not be_valid expect(auth.errors.messages[:password]).to eq [weak_password_error] end end
module Sudoku::Solver class SudokuGrid attr_reader :matrix def initialize(matrix) @matrix = matrix end def set_value_at(value, index_y, index_x) @matrix[index_y][index_x] = value end def dup dup = [] (0...9).each do |y| (0...9).each do |x| dup[y] ||= [] dup[y][x] = @matrix[y][x] end end SudokuGrid.new(dup) end def is_placement_ok?(value, index_y, index_x) is_nil_at?(index_y, index_x) && is_row_ok?(value, index_y) && is_col_ok?(value, index_x) && is_square_ok_at?(value, index_y, index_x) end def is_nil_at?(index_y, index_x) @matrix[index_y][index_x].nil? end def is_col_ok?(value, index_x) (0...9).each do |y| return false if @matrix[y][index_x] == value end true end def is_row_ok?(value, index_y) (0...9).each do |x| return false if @matrix[index_y][x] == value end true end def is_square_ok_at?(value, index_y, index_x) start_y = start_index(index_y) start_x = start_index(index_x) (start_y...(start_y + 3)).each do |y| (start_x...(start_x + 3)).each do |x| return false if @matrix[y][x] == value end end true end def to_s output = [] @matrix (0...9).each do |y| output << @matrix[y].map { |value| value.nil? ? " " : value }.join(" | ") end output.join("\n") end def eql?(other) result = true (0...9).each do |y| (0...9).each do |x| result = result && other.matrix[y][x] == @matrix[y][x] end end result end private def start_index(index) if index < 3 0 elsif index < 6 3 else 6 end end end end
# encoding: UTF-8 class Film class Statistiques def nombre_personnages @nombre_personnages ||= personnages.count end # Retourne un Array de personnages en fonction de # leur présence, du plus présent au moins présent. def personnages_par_temps_presence @personnages_par_temps_presence ||= begin calcule_temps_par_personnage personnages.sort_by { |p| - p.presence } end end def calcule_temps_par_personnage personnages.each do |perso| perso.presence(scenes) # force simplement son calcul end end end #/Statistiques end #/Film class Film class Personnage # Texte écrit dans le fichier statistique pour la # présence du personnage def info_presence_stats presence.s2h + div("(#{pourcentage_presence})", class: 'small') end # Retourne le temps de présence dans les scènes # spécifiées # Noter qu'il s'agit d'une variable définie une seule fois, # en considérant qu'elle est utile pour une collecte en # particulier. def presence in_scenes = nil @presence ||= calcule_temps_presence_in_scenes(in_scenes) end def pourcentage_presence @pourcentage_presence ||= film.pourcentage_duree_for(presence) end def calcule_temps_presence_in_scenes in_scenes in_scenes ||= film.scenes p = 0 in_scenes.each do |scene| scene.personnages_ids || next scene.personnages_ids.include?(id) || next p += scene.duree end return p end end #/Personnage end #/Film
require 'test_helper' describe 'PlayerLoader' do describe '#load' do it 'will generate identifier if none is passed' do PlayerLoader.new(first_name: 'Bob', last_name: 'Ross', birth_year: 1942, identifier: nil).load Player.count.must_equal 1 player = Player.first player.identifier.must_equal 'rossbo01' player.imported.must_equal true end it 'will stub other data if none is passed' do PlayerLoader.new(first_name: nil, last_name: nil, birth_year: nil, identifier: 'identifier').load Player.count.must_equal 1 player = Player.find_by(identifier: 'identifier') player.first_name.must_equal 'unknown' player.last_name.must_equal 'unknown' player.birth_year.must_equal 0 player.imported.must_equal true end describe 'when the player exists' do it 'will update the existing player' do player = create :player Player.count.must_equal 1 PlayerLoader.new(first_name: 'Bob', last_name: 'Ross', birth_year: player.birth_year, identifier: player.identifier).load Player.count.must_equal 1 results = Player.first results.first_name.must_equal 'Bob' results.last_name.must_equal 'Ross' results.imported.must_equal true end end describe 'when the player does not exist' do it 'will create a new player' do Player.count.must_equal 0 PlayerLoader.new(first_name: 'Bob', last_name: 'Ross', birth_year: 1942, identifier: 'Bob').load Player.count.must_equal 1 Player.first.imported.must_equal true end end it 'is idempotent' do Player.count.must_equal 0 loader = PlayerLoader.new(first_name: 'Bob', last_name: 'Ross', birth_year: 1942, identifier: 'Bob') loader.load loader.load Player.count.must_equal 1 Player.first.imported.must_equal true end it 'will not recreate record with a generated identifier when the birthdays are the same' do player = create :player, :imported loader = PlayerLoader.new(first_name: player.first_name, last_name: player.last_name, birth_year: player.birth_year, identifier: nil) loader.load Player.count.must_equal 1 end it 'will create record different generated identifier when the birthdays are not the same' do player = create :player, :imported loader = PlayerLoader.new(first_name: player.first_name, last_name: player.last_name, birth_year: 2018, identifier: nil) loader.load Player.count.must_equal 2 identifiers = Player.all.map(&:identifier) identifiers.must_include 'willite01' identifiers.must_include 'willite02' loader.load Player.count.must_equal 2 end end end
module Types class ProviderType < Types::BaseEnum value "heroku" end end
class Setlist < ActiveRecord::Base belongs_to :gig belongs_to :song end
class AlbumImage < ActiveRecord::Base attr_accessible :album_id, :image, :caption, :cover validates :image_file_name, :presence => true belongs_to :album has_attached_file :image, :url => "/assets/album_images/:id/:style/:basename.:extension", :path => ":rails_root/public/assets/album_images/:id/:style/:basename.:extension" end
module KMP3D class GOBJ < GroupType def initialize @name = "Objects" @external_settings = [ Settings.new(:text, :obj, "Object ID", "itembox"), Settings.new(:path, :path, "Object Path", Data.load_obj("itembox")) ] @settings = [ Settings.new(:text, :uint16, "Ref ID", "0x0"), Settings.new(:text, :uint16, "Route ID", "-1"), Settings.new(:text, :uint16, "S1", "0"), Settings.new(:text, :uint16, "S2", "0"), Settings.new(:text, :uint16, "S3", "0"), Settings.new(:text, :uint16, "S4", "0"), Settings.new(:text, :uint16, "S5", "0"), Settings.new(:text, :uint16, "S6", "0"), Settings.new(:text, :uint16, "S7", "0"), Settings.new(:text, :uint16, "S8", "0"), Settings.new(:text, :uint16, "Flag", "0x3F") ] @obj_list = Objects::LIST.keys.join("|") super end def sequential_id? false end def settings_name "" end def add_group(init=false) return super if init object = UI.inputbox(["Enter Object Name"], ["itembox"], [@obj_list], "Add Object").first @table << [object, Data.load_obj(object)] end def model @table[@group + 1][1] end def transform(comp, pos) comp.transform!(Geom::Transformation.translation(pos)) end def advance_steps(_pos) 0 end def helper_text "Click to add a new object." end def import(pos, rot, scale, group, settings) comp = Data.entities.add_instance(Data.load_obj(group), pos) comp.transform!(Geom::Transformation.scaling(pos, *scale)) comp.transform!(Geom::Transformation.rotation(pos, [1, 0, 0], rot[0])) comp.transform!(Geom::Transformation.rotation(pos, [0, 0, 1], rot[1])) comp.transform!(Geom::Transformation.rotation(pos, [0, 1, 0], -rot[2])) comp.name = "KMP3D #{type_name}(#{group}|#{settings * '|'})" comp.layer = name return comp end def inputs # settings added due to next point using previous settings inputs = [[-1, false] + @settings.map { |s| s.default }] Data.entities.each do |ent| next unless ent.type?("GOBJ") && ent.kmp3d_group == group_id(@group) id = ent.kmp3d_id(type_name) selected = Data.selection.include?(ent) inputs << [id, selected] + ent.kmp3d_settings[1..-1] end return inputs end def group_id(i) @table[i.to_i + 1][0] end def update_group(value, row, col) Data.model.start_operation("Update object group") Data.entities.each do |ent| next unless ent.type?("GOBJ") && ent.kmp3d_group == group_id(row) case col.to_i # change the definition to the default if the object name is changed when 0 definition = Data.load_obj(value) @table[row.to_i + 1][1] = definition ent.edit_setting(0, value) ent.definition = definition # change the definition to the path if the object path is changed when 1 then ent.definition = value end end super Data.model.commit_operation end end end
module Forms class Builder < ActionView::Helpers::FormBuilder delegate :content_tag, to: :@template def error_for(method, options = {}) return '' if @object.nil? || @object.errors[method].blank? field_errors = @object.errors[method].join(', ') field_errors = field_errors.humanize if field_errors =~ /_/ error_options = { class: 'field_errors' } content_tag(:div, field_errors, error_options).html_safe end end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception include SessionsHelper private def require_user_logged_in unless logged_in? redirect_to homepages_url end end def counts(user) @count_reviews = user.reviews.count @count_contents = user.res_reviews.count @count_refs = user.ref_reviews.count @count_evas = user.eva_reviews.count @count_goods = user.good_spots.count @count_likes = user.like_spots.count @count_nices = user.nice_restaurants.count @count_cons = user.con_restaurants.count end def read(result) place_id = result['place_id'] formatted_address = result['formatted_address'] name = result['name'] photo_reference = result['photos'][0]['photo_reference'] return{ place_id: place_id, formatted_address: formatted_address, name: name, photo_reference: photo_reference, } end def detail(result) place_id = result['place_id'] formatted_address = result['formatted_address'] name = result['name'] photo_reference = result['photos'][0]['photo_reference'] weekday_text = result['opening_hours']['weekday_text'] return{ place_id: place_id, formatted_address: formatted_address, name: name, photo_reference: photo_reference, weekday_text: weekday_text, } end def photo(result) photo_url = result.at('//a').[]('href') return{ photo_url: photo_url, } end end
# Assumptions: # This method assumes the input array is comprised of elements of the same data type, which are already sorted # Restrictions: # This method cannot use any fancy built-in Ruby array methods, only 'Array#[]' and 'Array#length' def binary_search(array, target, midpoint_index = array.length / 2) return nil if array.length <= 1 && array[0] != target left = array[0...midpoint_index] right = array[midpoint_index..-1] if array[midpoint_index] == target midpoint_index elsif array[midpoint_index] > target binary_search(left, target) elsif array[midpoint_index] < target if binary_search(right, target) == nil nil else midpoint_index + binary_search(right, target) end end end def linear_search(array, target) idx = 0 while idx < array.length if array[idx] == target return idx else idx += 1 end end nil end require 'benchmark' Benchmark.bm do |x| test_array = ("a".."eeeee").to_a target = "dbc" x.report("binary search:") { binary_search(test_array, target) } puts "-" * 70 x.report("linear search:") { linear_search(test_array, target) } puts "-" * 70 x.report("Array#index:") { test_array.index(target) } end # Benchmark output: # user system total real # binary search: 0.000000 0.000000 0.000000 ( 0.007298) # ---------------------------------------------------------------------- # linear search: 0.000000 0.000000 0.000000 ( 0.000901) # ---------------------------------------------------------------------- # Array#index: 0.000000 0.000000 0.000000 ( 0.000109)
class AddCompanySettings < ActiveRecord::Migration def self.up add_column :companies, :show_wiki, :boolean, :default => true add_column :companies, :show_forum, :boolean, :default => true add_column :companies, :show_chat, :boolean, :default => true end def self.down remove_column :companies, :show_chat remove_column :companies, :show_forum remove_column :companies, :show_wiki end end
require 'test_helper' class Buyers::ApplicationsTest < ActionDispatch::IntegrationTest class MasterLoggedInTest < Buyers::ApplicationsTest setup do login! master_account FactoryBot.create(:cinstance, service: master_account.default_service) end attr_reader :service test 'index retrieves all master\'s provided cinstances except those whose buyer is master' do get admin_buyers_applications_path assert_response :ok expected_cinstances_ids = master_account.provided_cinstances.not_bought_by(master_account).pluck(:id) assert_same_elements expected_cinstances_ids, assigns(:cinstances).map(&:id) end end class ProviderLoggedInTest < Buyers::ApplicationsTest def setup @provider = FactoryBot.create(:provider_account) login! provider #TODO: dry with @ignore-backend tag on cucumber stub_backend_get_keys stub_backend_referrer_filters stub_backend_utilization end attr_reader :provider test 'index shows the services column when the provider is multiservice' do provider.services.create!(name: '2nd-service') assert provider.reload.multiservice? get admin_buyers_applications_path page = Nokogiri::HTML::Document.parse(response.body) assert page.xpath("//tr").text.match /Service/ end test 'index does not show the services column when the provider is not multiservice' do refute provider.reload.multiservice? get admin_buyers_applications_path page = Nokogiri::HTML::Document.parse(response.body) refute page.xpath("//tr").text.match /Service/ end test 'index shows an application of a custom plan' do service = provider.default_service buyer = FactoryBot.create(:buyer_account, provider_account: provider) app_plan = FactoryBot.create(:application_plan, issuer: service) custom_plan = app_plan.customize cinstance = FactoryBot.create(:cinstance, user_account: buyer, plan: custom_plan, name: 'my custom cinstance') get admin_buyers_applications_path assert_response :success page = Nokogiri::HTML::Document.parse(response.body) assert page.xpath("//td").text.match /my custom cinstance/ end test 'member cannot create an application when lacking access to a service' do forbidden_service = FactoryBot.create(:service, account: provider) forbidden_plan = FactoryBot.create(:application_plan, issuer: forbidden_service) forbidden_service_plan = FactoryBot.create(:service_plan, issuer: forbidden_service) authorized_service = FactoryBot.create(:service, account: provider) authorized_plan = FactoryBot.create(:application_plan, issuer: authorized_service) authorized_service_plan = FactoryBot.create(:service_plan, issuer: authorized_service) buyer = FactoryBot.create(:buyer_account, provider_account: provider) member = FactoryBot.create(:member, account: provider, member_permission_ids: [:partners]) member.activate! FactoryBot.create(:member_permission, user: member, admin_section: :services, service_ids: [authorized_service.id]) login_provider provider, user: member post admin_buyers_account_applications_path(account_id: buyer.id), cinstance: { plan_id: forbidden_plan.id, name: 'Not Allowed!', service_plan_id: forbidden_service_plan.id } assert_response :not_found post admin_buyers_account_applications_path(account_id: buyer.id), cinstance: { plan_id: authorized_plan.id, name: 'Allowed', service_plan_id: authorized_service_plan.id } assert_response :found end test 'buying a stock plan is allowed but buying a custom plan is not' do service = provider.default_service initial_plan = FactoryBot.create(:application_plan, issuer: service) buyer = FactoryBot.create(:buyer_account, provider_account: provider) cinstance = FactoryBot.create(:cinstance, user_account: buyer, plan: initial_plan) app_plan = FactoryBot.create(:application_plan, issuer: service) custom_plan = app_plan.customize put change_plan_admin_buyers_application_path(account_id: buyer.id, id: cinstance.id), cinstance: {plan_id: custom_plan.id} assert_response :not_found assert_equal initial_plan.id, cinstance.reload.plan_id put change_plan_admin_buyers_application_path(account_id: buyer.id, id: cinstance.id), cinstance: {plan_id: app_plan.id} assert_redirected_to admin_service_application_path(service, cinstance) assert_equal app_plan.id, cinstance.reload.plan_id end end end
module Mautic # Represent received web hook class WebHook attr_reader :connection # @param [Mautic::Connection] connection # @param [ActionController::Parameters] params def initialize(connection, params) @connection = connection @params = params end def form_submissions @forms ||= Array.wrap(@params.require('mautic.form_on_submit')) .collect do |data| ::Mautic::Submissions::Form.new(@connection, data['submission']) if data['submission'] end.compact end end end
class ProductsController < ApplicationController before_action :require_login, only: [:new, :create, :edit, :update] before_action :require_product_ownership, only: [:edit, :update] def index @products = Product.where(status: "Available") @products_by_merchant = Product.by_merchant(params[:merchant_id]) end def show product_id = params[:id] @product = Product.find_by(id: product_id) if @product.nil? flash[:error] = "Sorry! That products doesn't exist." redirect_to root_path return end @merchant = Merchant.find(@product.merchant_id ) end def new @product = Product.new end def create @status = "Available" @product = Product.new(product_params) @product.merchant_id = session[:merchant_id] if @product.save flash[:success] = "#{@product.name} added successfully" redirect_to product_path(@product.id) return else @error = @product.errors.full_messages flash.now[:error] = "Error: #{@error}" render action: "new" return end end def edit @product = Product.find_by(id: params[:id]) render_404 unless @product end def update @status = params[:product][:status] if @product.update(product_params) flash[:success] = "You successfully updated #{@product.name}" redirect_to merchant_path(@merchant) else flash[:error] = "Unable to update #{@product.name}" flash[:error_msgs] = @product.errors.full_messages render action: "edit" return end end private def require_login @merchant = Merchant.find_by(id: session[:merchant_id]) if @merchant.nil? flash[:error] = "Please log-in first" return redirect_to root_path end end def require_product_ownership @product = Product.find_by(id: params[:id]) # this confirms that the product belongs to its merchant if @product.nil? || @product.merchant.id != @merchant.id flash[:error] = "You are not authorized to edit this product!" redirect_to root_path return end end def product_params return params.require(:product).permit(:name, :price, :stock, :img_url, :description, category_ids: []).merge(status: @status) end end
require "test_helper" class WeekendTest < ActiveSupport::TestCase def test_fixture_is_valid assert FactoryBot.create(:weekend).valid? end def test_validations weekend = FactoryBot.build(:weekend) assert(weekend.valid?) weekend = FactoryBot.build(:weekend, body: nil) refute(weekend.valid?) weekend = FactoryBot.build(:weekend, body: "") refute(weekend.valid?) weekend = FactoryBot.build(:weekend, body: "A" * 6) refute(weekend.valid?) weekend = FactoryBot.build(:weekend, body: "A" * 65_536) refute(weekend.valid?) weekend = FactoryBot.build(:weekend, body: "A" * 30) assert(weekend.valid?) weekend = FactoryBot.build(:weekend, front_user: nil) assert(weekend.valid?) end def test_scope_published _weekend_1 = FactoryBot.create(:weekend, status: "draft") _weekend_2 = FactoryBot.create(:weekend, status: "moderation_pending") weekend_3 = FactoryBot.create(:weekend, status: "published") weekend_4 = FactoryBot.create(:weekend, status: "published") assert_primary_keys([weekend_3, weekend_4].sort, Weekend.published.sort) end def test_uuid_on_create weekend = FactoryBot.build(:weekend) assert_nil(weekend.uuid) weekend.save! assert_not_nil(weekend.uuid) end def test_primary_key weekend = FactoryBot.create(:weekend) assert_equal(weekend, Weekend.find(weekend.uuid)) end def test_relations front_user = FactoryBot.create(:front_user) weekend = FactoryBot.create(:weekend, front_user: front_user) assert_equal(front_user, weekend.front_user) end def test_on_create_init_status weekend = FactoryBot.build(:weekend, status: nil) assert_nil weekend.status weekend.save! assert_equal("draft", weekend.status) end end
module Ecology module Test def set_up_ecology(file_contents, filename = "some.ecology", options = {}) match = filename.match(/^(.*)\.erb$/) if match ENV["ECOLOGY_SPEC"] = match[1] File.stubs(:exist?).with(match[1]).returns(false) else ENV["ECOLOGY_SPEC"] = filename end File.stubs(:exist?).with(filename + ".erb").returns(false) File.stubs(:exist?).with(filename).returns(true) unless options[:no_read] File.expects(:read).with(filename).returns(file_contents).at_least_once end end end end
class Order < ActiveRecord::Base alias_attribute :parent_id, :state mount_uploader :details_file, FileUploader enum state: [:new_one, :handled] has_many :order_items, -> { ordered }, dependent: :destroy validates :name, :phone, :email, presence: true, if: -> x { x.real? } def sum order_items .lazy .map { |x| x.price * x.count } .reduce(:+) end end
Rails.application.routes.draw do devise_for :admin_users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) root :to => "routes#index" # Routes for the City resource: # CREATE get "/cities/new", :controller => "cities", :action => "new" post "/create_city", :controller => "cities", :action => "create" # READ get "/cities", :controller => "cities", :action => "index" get "/cities/:id", :controller => "cities", :action => "show" # UPDATE get "/cities/:id/edit", :controller => "cities", :action => "edit" post "/update_city/:id", :controller => "cities", :action => "update" # DELETE get "/delete_city/:id", :controller => "cities", :action => "destroy" #------------------------------ # Routes for the Restaurant resource: # CREATE get "/restaurants/new", :controller => "restaurants", :action => "new" post "/create_restaurant", :controller => "restaurants", :action => "create" # READ get "/restaurants", :controller => "restaurants", :action => "index" get "/restaurants/:id", :controller => "restaurants", :action => "show" # UPDATE get "/restaurants/:id/edit", :controller => "restaurants", :action => "edit" post "/update_restaurant/:id", :controller => "restaurants", :action => "update" # DELETE get "/delete_restaurant/:id", :controller => "restaurants", :action => "destroy" #------------------------------ # Routes for the Shop resource: # CREATE get "/shops/new", :controller => "shops", :action => "new" post "/create_shop", :controller => "shops", :action => "create" # READ get "/shops", :controller => "shops", :action => "index" get "/shops/:id", :controller => "shops", :action => "show" # UPDATE get "/shops/:id/edit", :controller => "shops", :action => "edit" post "/update_shop/:id", :controller => "shops", :action => "update" # DELETE get "/delete_shop/:id", :controller => "shops", :action => "destroy" #------------------------------ # Routes for the Preference resource: # CREATE get "/preferences/new", :controller => "preferences", :action => "new" post "/create_preference", :controller => "preferences", :action => "create" # READ get "/preferences", :controller => "preferences", :action => "index" get "/preferences/:id", :controller => "preferences", :action => "show" # UPDATE get "/preferences/:id/edit", :controller => "preferences", :action => "edit" post "/update_preference/:id", :controller => "preferences", :action => "update" # DELETE get "/delete_preference/:id", :controller => "preferences", :action => "destroy" #------------------------------ # Routes for the Route resource: # CREATE get "/routes/new", :controller => "routes", :action => "new" post "/create_route", :controller => "routes", :action => "create" # READ get "/routes", :controller => "routes", :action => "index" get "/routes/:id", :controller => "routes", :action => "show" # UPDATE get "/routes/:id/edit", :controller => "routes", :action => "edit" post "/update_route/:id", :controller => "routes", :action => "update" # DELETE get "/delete_route/:id", :controller => "routes", :action => "destroy" #------------------------------ devise_for :users # Routes for the User resource: # READ get "/users", :controller => "users", :action => "index" get "/users/:id", :controller => "users", :action => "show" # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
# frozen_string_literal: true RSpec.feature "Single Item Pagination", type: :system, clean: true, js: true do before do stub_request(:get, 'https://yul-dc-development-samples.s3.amazonaws.com/manifests/11/11/111.json') .to_return(status: 200, body: File.open(File.join('spec', 'fixtures', '2041002.json')).read) stub_request(:get, 'https://yul-dc-development-samples.s3.amazonaws.com/manifests/22/22/222.json') .to_return(status: 200, body: File.open(File.join('spec', 'fixtures', '2041002.json')).read) stub_request(:get, 'https://yul-dc-development-samples.s3.amazonaws.com/manifests/33/33/333.json') .to_return(status: 200, body: File.open(File.join('spec', 'fixtures', '2041002.json')).read) solr = Blacklight.default_index.connection solr.add([test_record, same_call_record, diff_call_record]) solr.commit visit search_catalog_path visit '/catalog?search_field=all_fields&q=' end let(:same_call_record) do { id: '222', visibility_ssi: 'Public', callNumber_ssim: 'this is the call number' } end let(:diff_call_record) do { id: '333', visibility_ssi: 'Public', callNumber_ssim: 'this is the call number, but different' } end let(:test_record) do { id: '111', visibility_ssi: "Public", callNumber_ssim: 'this is the call number, but moderately different' } end it 'has expected css' do click_link '111' expect(page).to have_css '.page-links-show' expect(page).to have_css '.page-items-show' expect(page).to have_css '.page-info-show' end context "in the first item" do it 'does not have "Previous" and should have "Next"' do click_link '111' expect(page).not_to have_link("< Previous") expect(page).to have_link("Next >", href: '/catalog/222') expect(page).to have_content("1 of 3") end end context "in the second item" do it 'has "Previous" and "Next"' do click_link '222' expect(page).to have_link("< Previous", href: '/catalog/111') expect(page).to have_link("Next >", href: '/catalog/333') expect(page).to have_content("2 of 3") end end context "in the third item" do it 'has "Previous", but not "Next"' do click_link '333' expect(page).to have_link("< Previous", href: '/catalog/222') expect(page).not_to have_link("Next >") expect(page).to have_content("3 of 3") end end end
RSpec.feature "Users can view an activity" do context "when the user belongs to BEIS" do let(:user) { create(:beis_user) } before { authenticate!(user: user) } after { logout } context "and the activity is a fund" do scenario "the child programme activities can be viewed" do fund = create(:fund_activity) programme = create(:programme_activity, parent: fund) visit organisation_activity_children_path(fund.organisation, fund) expect(page).to have_content programme.title expect(page).to have_content programme.roda_identifier end scenario "the child programme activities are ordered by created_at (oldest first)" do fund = create(:fund_activity) programme_1 = create(:programme_activity, created_at: Date.yesterday, parent: fund) programme_2 = create(:programme_activity, created_at: Date.today, parent: fund) visit organisation_activity_children_path(fund.organisation, fund) expect(page.find("table.programmes tbody tr:first-child")[:id]).to have_content(programme_1.id) expect(page.find("table.programmes tbody tr:last-child")[:id]).to have_content(programme_2.id) end scenario "they do not see a Publish to Iati column & status against programmes" do fund = create(:fund_activity) programme = create(:programme_activity, parent: fund) visit organisation_activity_children_path(fund.organisation, fund) within(".programmes") do expect(page).to_not have_content t("summary.label.activity.publish_to_iati.label") end within("##{programme.id}") do expect(page).to_not have_content t("summary.label.activity.publish_to_iati.true") end end end context "and the activity is a programme" do scenario "they view a list of all child projects" do fund = create(:fund_activity) programme = create(:programme_activity, parent: fund) project = create(:project_activity, parent: programme) another_project = create(:project_activity, parent: programme) visit organisation_activity_children_path(programme.organisation, programme) within("##{project.id}") do expect(page).to have_link project.title, href: organisation_activity_path(project.organisation, project) expect(page).to have_content project.roda_identifier expect(page).to have_content project.parent.title end within("##{another_project.id}") do expect(page).to have_link another_project.title, href: organisation_activity_path(another_project.organisation, another_project) expect(page).to have_content another_project.roda_identifier expect(page).to have_content another_project.parent.title end end scenario "they see a Publish to Iati column & status against projects" do fund = create(:fund_activity) programme = create(:programme_activity, parent: fund) project = create(:project_activity, parent: programme) visit organisation_activity_children_path(programme.organisation, programme) within(".projects") do expect(page).to have_content t("summary.label.activity.publish_to_iati.label") end within("##{project.id}") do expect(page).to have_content "Yes" end end end context "whent the activity is a project" do scenario "they see a list of all their third-party projects" do project = create(:project_activity) third_party_project = create(:third_party_project_activity, parent: project) visit organisation_activity_children_path(project.organisation, project) within("##{third_party_project.id}") do expect(page).to have_link third_party_project.title, href: organisation_activity_path(third_party_project.organisation, third_party_project) expect(page).to have_content third_party_project.roda_identifier expect(page).to have_content third_party_project.parent.title end end scenario "they see a Publish to Iati column & status against third-party projects" do project = create(:project_activity) third_party_project = create(:third_party_project_activity, parent: project) visit organisation_activity_children_path(project.organisation, project) expect(page).to have_content t("summary.label.activity.publish_to_iati.label") within("##{third_party_project.id}") do expect(page).to have_content "Yes" end end end scenario "the financial summary and activity financials can be viewed" do travel_to Time.zone.local(2021, 12, 15) do activity = create(:programme_activity, organisation: user.organisation) q3_21_report = create( :report, :active, financial_quarter: 3, financial_year: 2021, organisation: user.organisation, fund: activity.associated_fund ) actual = create( :actual, parent_activity: activity, value: 10, report: q3_21_report, financial_quarter: 3, financial_year: 2021 ) create( :actual, parent_activity: activity, value: 50, report: q3_21_report, financial_quarter: 3, financial_year: 2021 ) budget = create(:budget, parent_activity: activity, value: 10) create(:budget, parent_activity: activity, value: 55) ForecastHistory.new(activity, financial_year: 2021, financial_quarter: 3).set_value(40) ForecastHistory.new(activity, financial_year: 2021, financial_quarter: 4).set_value(30) visit organisation_activity_financials_path(activity.organisation, activity) within ".govuk-tabs__list-item--selected" do expect(page).to have_content "Financials" end within ".financial-summary" do expect(page).to have_content "Total spend to date £60.00" expect(page).to have_content "Total budget to date £65.00" expect(page).to have_content "Total forecasted spend £30.00" # only upcoming periods end expect(page).to have_content actual.value expect(page).to have_content budget.value end end scenario "the activity child activities can be viewed in a tab" do activity = create(:project_activity) visit organisation_activity_children_path(activity.organisation, activity) within ".govuk-tabs__list-item--selected" do expect(page).to have_content "Child activities" end expect(page).to have_content activity.title end scenario "the activity details tab can be viewed" do activity = create(:project_activity) visit organisation_activity_details_path(activity.organisation, activity) within ".govuk-tabs__list-item--selected" do expect(page).to have_content "Details" end activity_presenter = ActivityPresenter.new(activity) expect(page).to have_content activity_presenter.roda_identifier expect(page).to have_content activity_presenter.sector expect(page).to have_content activity_presenter.title expect(page).to have_content activity_presenter.description expect(page).to have_content activity_presenter.planned_start_date expect(page).to have_content activity_presenter.planned_end_date expect(page).to have_content activity_presenter.recipient_region end scenario "the activity links to the parent activity" do activity = create(:programme_activity, organisation: user.organisation) parent_activity = activity.parent visit organisation_activity_details_path(activity.organisation, activity) expect(page).to have_link parent_activity.title, href: organisation_activity_path(parent_activity.organisation, parent_activity) end scenario "a fund activity has human readable date format" do travel_to Time.zone.local(2020, 1, 29) do activity = create(:project_activity, planned_start_date: Date.new(2020, 2, 3), planned_end_date: Date.new(2024, 6, 22), actual_start_date: Date.new(2020, 1, 2), actual_end_date: Date.new(2020, 1, 29)) visit organisation_activity_path(user.organisation, activity) click_on t("tabs.activity.details") within(".planned_start_date") do expect(page).to have_content("3 Feb 2020") end within(".planned_end_date") do expect(page).to have_content("22 Jun 2024") end within(".actual_start_date") do expect(page).to have_content("2 Jan 2020") end within(".actual_end_date") do expect(page).to have_content("29 Jan 2020") end end end end context "when the user is signed in as a partner organisation user" do let(:user) { create(:partner_organisation_user) } before { authenticate!(user: user) } after { logout } scenario "a programme activity does not link to its parent activity" do activity = create(:programme_activity, extending_organisation: user.organisation) parent_activity = activity.parent visit organisation_activity_details_path(activity.organisation, activity) expect(page).not_to have_link parent_activity.title, href: organisation_activity_path(parent_activity.organisation, parent_activity) expect(page).to have_content parent_activity.title end scenario "they do not see a Publish to Iati column & status against third-party projects" do project = create(:project_activity, organisation: user.organisation) third_party_project = create(:third_party_project_activity, parent: project) visit organisation_activity_children_path(project.organisation, project) expect(page).to_not have_content t("summary.label.activity.publish_to_iati.label") within("##{third_party_project.id}") do expect(page).to_not have_content t("summary.label.activity.publish_to_iati.true") end end end end
class Favorite < ActiveRecord::Base belongs_to :user belongs_to :hitorigochi validates :user, presence: true validates :user_id, uniqueness: { scope: :hitorigochi_id } validates :hitorigochi, presence: true end
class Agenda < ActiveRecord::Base has_many :items, :class_name => "Item", :foreign_key => "id_item"; has_many :users, :class_name => "User", :foreign_key => "id_user"; end
class Block < ApplicationRecord belongs_to :floor has_many :parking_slots, dependent: :destroy accepts_nested_attributes_for :parking_slots, allow_destroy: true, reject_if: :all_blank before_save :build_parking_slots attr_accessor :slots private def build_parking_slots if self.slots.present? && self.parking_slots.count == 0 self.slots.to_i.times do |n| if n < 9 self.parking_slots.build(name: "0#{n+1}") else self.parking_slots.build(name: "#{n+1}") end end end end end
require 'vanagon/engine/always_be_scheduling' require 'vanagon/driver' require 'vanagon/platform' require 'logger' require 'spec_helper' class Vanagon class Driver @@logger = Logger.new('/dev/null') end end describe 'Vanagon::Engine::AlwaysBeScheduling' do let (:platform) { plat = Vanagon::Platform::DSL.new('aix-6.1-ppc') plat.instance_eval("platform 'aix-6.1-ppc' do |plat| plat.build_host 'abcd' end") plat._platform } let (:platform_with_vmpooler_template) { plat = Vanagon::Platform::DSL.new('ubuntu-10.04-amd64 ') plat.instance_eval("platform 'aix-6.1-ppc' do |plat| plat.build_host 'abcd' plat.vmpooler_template 'ubuntu-1004-amd64' end") plat._platform } let (:platform_with_abs_resource_name) { plat = Vanagon::Platform::DSL.new('aix-6.1-ppc') plat.instance_eval("platform 'aix-6.1-ppc' do |plat| plat.build_host 'abcd' plat.abs_resource_name 'aix-61-ppc' end") plat._platform } let (:platform_with_both) { plat = Vanagon::Platform::DSL.new('aix-6.1-ppc') plat.instance_eval("platform 'aix-6.1-ppc' do |plat| plat.build_host 'abcd' plat.vmpooler_template 'aix-six-one-ppc' plat.abs_resource_name 'aix-61-ppc' end") plat._platform } let(:pooler_token_file) { File.expand_path('~/.vanagon-token') } let(:floaty_config) { File.expand_path('~/.vmfloaty.yml') } describe '#validate_platform' do it 'returns true if the platform has the required attributes' do expect(Vanagon::Engine::AlwaysBeScheduling.new(platform, nil).validate_platform) .to be(true) end end describe '#build_host_name' do it 'by default returns the platform name with no translation' do expect(Vanagon::Engine::AlwaysBeScheduling.new(platform, nil).build_host_name) .to eq("aix-6.1-ppc") end it 'returns vmpooler_template if vmpooler_template is specified' do expect(Vanagon::Engine::AlwaysBeScheduling.new(platform_with_vmpooler_template, nil).build_host_name) .to eq("ubuntu-1004-amd64") end it 'returns abs_resource_name if abs_resource_name is specified' do expect(Vanagon::Engine::AlwaysBeScheduling.new(platform_with_abs_resource_name, nil).build_host_name) .to eq("aix-61-ppc") end it 'prefers abs_resource_name to vmpooler_template if both are specified' do expect(Vanagon::Engine::AlwaysBeScheduling.new(platform_with_both, nil).build_host_name) .to eq("aix-61-ppc") end end describe '#name' do it 'returns "always_be_scheduling" engine name' do expect(Vanagon::Engine::AlwaysBeScheduling.new(platform, nil).name) .to eq('always_be_scheduling') end end describe '#read_vanagon_token' do it 'takes the first line for abs token, second line is optional' do token_value = 'decade' allow(File).to receive(:exist?) .with(pooler_token_file) .and_return(true) allow(File).to receive(:read) .with(pooler_token_file) .and_return(token_value) abs_service = Vanagon::Engine::AlwaysBeScheduling.new(platform, nil) expect(abs_service.token).to eq('decade') expect(abs_service.token_vmpooler).to eq(nil) end it 'takes the second line as vmpooler token' do token_value = "decade\nanddaycade" allow(File).to receive(:exist?) .with(pooler_token_file) .and_return(true) allow(File).to receive(:read) .with(pooler_token_file) .and_return(token_value) abs_service = Vanagon::Engine::AlwaysBeScheduling.new(platform, nil) expect(abs_service.token).to eq('decade') expect(abs_service.token_vmpooler).to eq('anddaycade') end end describe '#read_vmfloaty_token' do before :each do allow(File).to receive(:exist?) .with(pooler_token_file) .and_return(false) allow(File).to receive(:exist?) .with(floaty_config) .and_return(true) end token_value = 'decade' it 'reads a token from "~/.vmfloaty.yml" at the top level' do allow(YAML).to receive(:load_file) .with(floaty_config) .and_return({ 'token' => token_value }) allow(ENV).to receive(:[]) allow(ENV).to receive(:[]).with('VMPOOLER_TOKEN').and_return(nil) abs_service = Vanagon::Engine::AlwaysBeScheduling.new(platform, nil) expect(abs_service.token).to eq(token_value) end it 'reads a token from "~/.vmfloaty.yml" in the abs service' do vmp_token_value = 'deecade' allow(YAML).to receive(:load_file) .with(floaty_config) .and_return( { 'services' => { 'MYabs' => { 'type' => 'abs', 'token' => token_value, 'url' => 'foo', 'vmpooler_fallback' => 'myvmp' }, 'myvmp' => { 'token' => vmp_token_value, 'url' => 'bar' } } } ) abs_service = Vanagon::Engine::AlwaysBeScheduling.new(platform, nil) expect(abs_service.token).to eq(token_value) end it 'reads a token from "~/.vmfloaty.yml" and includes the vmpooler token' do vmp_token_value = 'deecade' allow(YAML).to receive(:load_file) .with(floaty_config) .and_return( { 'services' => { 'MYabs' => { 'type' => 'abs', 'token' => token_value, 'url' => 'foo', 'vmpooler_fallback' => 'myvmp' }, 'myvmp' => { 'token' => vmp_token_value, 'url' => 'bar' } } } ) abs_service = Vanagon::Engine::AlwaysBeScheduling.new(platform, nil) expect(abs_service.token_vmpooler).to eq(vmp_token_value) end end describe '#select_target_from' do it 'runs successfully' do hostname = 'faint-whirlwind.puppet.com' stub_request(:post, 'https://foobar/request') .to_return( { status: 202, body: "", headers: {} }, { status: 200, body: [{ 'hostname' => hostname, 'type' => 'aix-6.1-ppc', 'engine' => 'nspooler' }] .to_json, headers: {} } ) abs_service = Vanagon::Engine::AlwaysBeScheduling.new(platform, nil) abs_service.select_target_from("https://foobar") expect(abs_service.target).to eq(hostname) end it 'returns a warning if the first request is not a 202' do hostname = 'fainter-whirlwind.puppet.com' stub_request(:post, "https://foobar/request") .to_return( { status: 404, body: "", headers: {} }, { status: 200, body: [{ 'hostname' => hostname, 'type' => 'aix-6.1-ppc', 'engine' => 'nspooler' }].to_json, headers: {} } ) allow(VanagonLogger).to receive(:info) expect(VanagonLogger).to receive(:info).with('failed to request ABS with code 404') abs_service = Vanagon::Engine::AlwaysBeScheduling.new(platform, nil) abs_service.select_target_from('https://foobar') end it 'retries until request is a 200' do hostname = 'faintest-whirlwind.puppet.com' stub_request(:post, 'https://foobar/request') .to_return( { status: 202, body: "", headers: {} }, { status: 503, body: "", headers: {} }, { status: 200, body: [{ 'hostname' => hostname, 'type' => 'aix-6.1-ppc', 'engine' => "nspooler" }].to_json, headers: {} } ) allow(VanagonLogger).to receive(:info) expect(VanagonLogger).to receive(:info).with(/^Waiting 1 second.*to fill/) abs_service = Vanagon::Engine::AlwaysBeScheduling.new(platform, nil) abs_service.select_target_from("https://foobar") end it 'sets a service target when request is a 200' do hostname = 'faintest-whirlwind.puppet.com' stub_request(:post, 'https://foobar/request') .to_return( { status: 202, body: "", headers: {} }, { status: 503, body: "", headers: {} }, { status: 200, body: [{ 'hostname' => hostname, 'type' => 'aix-6.1-ppc', 'engine' => "nspooler" }].to_json, headers: {} } ) allow(VanagonLogger).to receive(:info) abs_service = Vanagon::Engine::AlwaysBeScheduling.new(platform, nil) abs_service.select_target_from("https://foobar") expect(abs_service.target).to eq(hostname) end end end
require 'spec_helper' describe 'dns::zone' do let(:pre_condition) { 'include dns::server::params' } let(:title) { 'test.com' } let(:facts) {{ :osfamily => 'Debian', :concat_basedir => '/mock_dir' }} describe 'passing something other than an array to $allow_query ' do let(:params) {{ :allow_query => '127.0.0.1' }} it { should raise_error(Puppet::Error, /is not an Array/) } end describe 'passing an array to $allow_query' do let(:params) {{ :allow_query => ['192.0.2.0', '2001:db8::/32'] }} it { should_not raise_error } it { should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/allow-query/) } it { should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/192\.0\.2\.0;/) } it { should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/2001:db8::\/32/) } end describe 'passing something other than an array to $allow_transfer' do let(:params) {{ :allow_transfer => '127.0.0.1' }} it { should raise_error(Puppet::Error, /is not an Array/) } end describe 'passing something other than an array to $allow_forwarder' do let(:params) {{ :allow_forwarder => '127.0.0.1' }} it { should raise_error(Puppet::Error, /is not an Array/) } end describe 'passing an array to $allow_transfer and $allow_forwarder' do let(:params) do { :allow_transfer => ['192.0.2.0', '2001:db8::/32'], :allow_forwarder => ['8.8.8.8', '208.67.222.222'] } end it { should_not raise_error } it { should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/allow-transfer/) } it { should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/192\.0\.2\.0/) } it { should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/forwarders/) } it { should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/forward first;/) } it { should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/8.8.8.8/) } it { should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/2001:db8::\/32/) } it { should contain_concat('/etc/bind/zones/db.test.com.stage') } it { should contain_concat__fragment('db.test.com.soa'). with_content(/_SERIAL_/) } it { should contain_exec('bump-test.com-serial'). with_refreshonly('true') } end context 'when ask to have a only forward policy' do let :params do { :allow_transfer => [], :allow_forwarder => ['8.8.8.8', '208.67.222.222'], :forward_policy => 'only' } end it 'should have a forward only policy' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/forward only;/) end end context 'with no explicit forward policy or forwarder' do let(:params) {{ :allow_transfer => ['192.0.2.0', '2001:db8::/32'] }} it 'should not have any forwarder configuration' do should_not contain_concat__fragment('named.conf.local.test.com.include'). with_content(/forward/) end end context 'with a delegation-only zone' do let :params do { :zone_type => 'delegation-only' } end it 'should only have a type delegation-only entry' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/zone \"test.com\" \{\s*type delegation-only;\s*\}/) end end context 'with a forward zone' do let :params do { :allow_transfer => ['123.123.123.123'], :allow_forwarder => ['8.8.8.8', '208.67.222.222'], :forward_policy => 'only', :zone_type => 'forward' } end it 'should have a type forward entry' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/type forward/) end it 'should not have allow_tranfer entry' do should_not contain_concat__fragment('named.conf.local.test.com.include'). with_content(/allow-transfer/) end it 'should not have file entry' do should_not contain_concat__fragment('named.conf.local.test.com.include'). with_content(/file/) end it 'should have a forward-policy entry' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/forward only/) end it 'should have a forwarders entry' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/forwarders/) end it 'should have an "absent" zone file concat' do should contain_concat('/etc/bind/zones/db.test.com.stage').with({ :ensure => "absent" }) end end context 'with a slave zone' do let :params do { :slave_masters => ['123.123.123.123'], :zone_type => 'slave' } end it 'should have a type slave entry' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/type slave/) end it 'should have file entry' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/file/) end it 'should have masters entry' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/masters.*123.123.123.123 *;/) end it 'should not have allow_tranfer entry' do should_not contain_concat__fragment('named.conf.local.test.com.include'). with_content(/allow-transfer/) end it 'should not have any forward information' do should_not contain_concat__fragment('named.conf.local.test.com.include'). with_content(/forward/) end it 'should have an "absent" zone file concat' do should contain_concat('/etc/bind/zones/db.test.com.stage').with({ :ensure => "absent" }) end end context 'with a slave zone with multiple masters' do let :params do { :slave_masters => ['123.123.123.123', '234.234.234.234'], :zone_type => 'slave' } end it 'should have masters entry with all masters joined by ;' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/masters.*123.123.123.123 *;[ \n]*234.234.234.234 *;/) end end context 'with a master zone' do let :params do { :allow_transfer => ['8.8.8.8','8.8.4.4'], :allow_forwarder => ['8.8.8.8', '208.67.222.222'], :forward_policy => 'only', :zone_type => 'master' } end it 'should have a type master entry' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/type master/) end it 'should have file entry' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/file/) end it 'should not have masters entry' do should_not contain_concat__fragment('named.conf.local.test.com.include'). with_content(/masters/) end it 'should have allow_tranfer entry' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/allow-transfer/) end it 'should have a forward-policy entry' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/forward /) end it 'should have a forwarders entry' do should contain_concat__fragment('named.conf.local.test.com.include'). with_content(/forwarders/) end it 'should have a zone file concat' do should contain_concat('/etc/bind/zones/db.test.com.stage').with({ :ensure => "present" }) end end context 'passing no zone_notify setting' do let :params do {} end it { should contain_concat__fragment('named.conf.local.test.com.include').without_content(/ notify /) } end context 'passing a wrong zone_notify setting' do let :params do { :zone_notify => 'maybe' } end it { should raise_error(Puppet::Error, /The zone_notify/) } end context 'passing yes to zone_notify' do let :params do { :zone_notify => 'yes' } end it { should contain_concat__fragment('named.conf.local.test.com.include').with_content(/ notify yes;/) } end context 'passing no to zone_notify' do let :params do { :zone_notify => 'no' } end it { should contain_concat__fragment('named.conf.local.test.com.include').with_content(/ notify no;/) } end context 'passing master-only to zone_notify' do let :params do { :zone_notify => 'master-only' } end it { should contain_concat__fragment('named.conf.local.test.com.include').with_content(/ notify master-only;/) } end context 'passing explicit to zone_notify' do let :params do { :zone_notify => 'explicit' } end it { should contain_concat__fragment('named.conf.local.test.com.include').with_content(/ notify explicit;/) } end context 'passing no also_notify setting' do let :params do {} end it { should contain_concat__fragment('named.conf.local.test.com.include').without_content(/ also-notify /) } end context 'passing a string to also_notify' do let :params do { :also_notify => '8.8.8.8' } end it { should raise_error(Puppet::Error, /is not an Array/) } end context 'passing a valid array to also_notify' do let :params do { :also_notify => [ '8.8.8.8' ] } end it { should contain_concat__fragment('named.conf.local.test.com.include').with_content(/ also-notify \{/) } it { should contain_concat__fragment('named.conf.local.test.com.include').with_content(/8\.8\.8\.8;/) } end end
require 'rails_helper' # As a visitor, # When I visit an amusement park’s show page # I see the name and price of admissions for that amusement park # And I see the names of all the rides that are at that theme park listed in alphabetical order # And I see the average thrill rating of this amusement park’s rides describe 'parks show page' do it 'shows the parks name and admission price, along with all the rides, listed alphabetically, and the average thrill rating' do park = Park.create(name:'Cedar Point', price: 50.00) ride1 = Ride.create(name:'death trap', thrill_rating: 7, open: false, park_id: park.id) ride2 = Ride.create(name:'slow, boring ride', thrill_rating: 1, open: true, park_id: park.id) ride3 = Ride.create(name:'flying death trap', thrill_rating: 10, open: true, park_id: park.id) visit "/parks/#{park.id}" expect(page).to have_content('Cedar Point') expect(page).to have_content(50) expect(page).to have_content(6.0) expect(page).to have_content('death trap') expect(page).to have_content('slow, boring ride') expect(page).to have_content('flying death trap') expect(page.text.index(ride3.name)).to be < page.text.index(ride2.name) expect(page.text.index(ride1.name)).to be < page.text.index(ride3.name) end end
Gem::Specification.new do |s| s.name = 'square.rb' s.version = '31.0.0.20230816' s.summary = 'square' s.description = '' s.authors = ['Square Developer Platform'] s.email = ['developers@squareup.com'] s.homepage = '' s.licenses = ['Apache-2.0'] s.add_dependency('apimatic_core_interfaces', '~> 0.2.0') s.add_dependency('apimatic_core', '~> 0.3.0') s.add_dependency('apimatic_faraday_client_adapter', '~> 0.1.0') s.add_development_dependency('minitest', '~> 5.14', '>= 5.14.1') s.add_development_dependency('minitest-proveit', '~> 1.0') s.required_ruby_version = ['>= 2.6'] s.files = Dir['{bin,lib,man,test,spec}/**/*', 'README*', 'LICENSE*'] s.require_paths = ['lib'] end
require 'spec_helper' describe Task do before(:each) do @user = User.create(:login => 'username', :password => '123456', :password_confirmation => '123456') @todo_tasks = [ Task.create(:title => 'Test', :description => 'Desc'), Task.create(:title => 'Test', :description => 'Desc'), ] @done_tasks = [ Task.create(:title => 'Test', :description => 'Desc', :done => true), Task.create(:title => 'Test', :description => 'Desc', :done => true), ] end describe '#todo' do before(:each) do @tasks = Task.todo end it 'should return not done tasks' do @tasks.should == @todo_tasks end it 'should not return done tasks' do @tasks.should_not include(@done_tasks) end end describe '#done' do before(:each) do @tasks = Task.done end it 'should return done tasks' do @tasks.should == @done_tasks end it 'should not return not done tasks' do @tasks.should_not include(@todo_tasks) end end describe 'when created' do it 'should not be done' do task = Task.create(:title => 'Test', :description => 'Desc') task.should_not be_done end end describe 'done' do it 'should mark a task as done' do task = Task.create(:title => 'Test', :description => 'Desc') task.done! task.should be_done end end end
class AddSalaryToPostings < ActiveRecord::Migration[5.0] def change add_column :postings, :employer, :string add_column :postings, :salary, :string add_column :postings, :schedule, :string add_column :postings, :date_to_remove, :datetime add_column :postings, :date_posted, :datetime add_column :postings, :jobbank_id, :string, index: true end end
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::BsonObjectId do it_behaves_like 'a generic field type', :string_field, :bson_object_id describe '#parse_value' do let(:bson) { RailsAdmin::Adapters::Mongoid::Bson::OBJECT_ID.new } let(:field) do RailsAdmin.config(FieldTest).fields.detect do |f| f.name == :bson_object_id_field end end before :each do RailsAdmin.config do |config| config.model FieldTest do field :bson_object_id_field, :bson_object_id end end end it 'parse valid bson_object_id', mongoid: true do expect(field.parse_value(bson.to_s)).to eq bson end end end
class Pub attr_reader :name, :till, :stock def initialize(name, till) @name = name @till = till @stock = Hash.new(0) end def stock_level(drink) return @stock[drink] end def add_drink(drink) if @stock.include?(drink) @stock[drink] += 1 else @stock[drink] = 1 end end def stock_value() total = 0 for drink in @stock.keys total += (drink.price * @stock[drink]) end return total end def serve(customer, drink) return if customer_too_young?(customer) return if customer_too_drunk?(customer) return if customer_cannot_afford_drink?(customer, drink) if @stock[drink] > 0 customer.buy_drink(drink) @stock[drink] -= 1 @till += drink.price() end end def customer_cannot_afford_drink?(customer, drink) return !customer.sufficient_funds?(drink) end def customer_too_young?(customer) return customer.age < 18 end def customer_too_drunk?(customer) return customer.drunkenness >= 50 end end
class Pub < ApplicationRecord DISTRICTS = [ "Brunswick", "Carlton", "Central Business District", "Collingwood", "Docklands", "East Melbourne", "Elwood", "Fitzroy", "Footscray", "Northcote", "Port Melbourne", "Prahran", "Richmond", "South Melbourne", "South Yarra", "Southbank", "St Kilda", "Windsor", "Yarraville/Seddon" ] validates :name, presence: true, uniqueness: true validates :address, :description, :photo, presence: true validates :district, presence: true, inclusion: { in: DISTRICTS } geocoded_by :address after_validation :geocode, if: :will_save_change_to_address? end
class Dispositivo < ActiveRecord::Base has_many :puertos, :include => :endpoint, :dependent => :destroy has_many :device_connections, :through => :puertos, :include => :dispositivo has_and_belongs_to_many :practicas scope :for_users, where('tipo <> ?','vlan') scope :ok, where('estado = ?', 'ok') #has_many :endpoints, :through => :device_connections #has_many :endpoints, :through => :device_connections, :class_name => 'Puerto', :source => :endpoint ## Constants # User - modifiable , VLAN - VLAN Switch TYPES = %w[user vlan] CATEGORIAS = %w[switch router otro] ESTADOS = %w[ok bad stock] validates :tipo, :presence => true, :inclusion => TYPES validates :categoria, :presence => true, :inclusion => CATEGORIAS validates :cluster_id, :presence => true, :numericality => true accepts_nested_attributes_for :puertos, :allow_destroy => true # Returns only physically connected ports # @return [Array] def puertos_utiles puertos.select do |puerto| puerto.conectado_fisicamente? end end def number_of_puertos_utiles puertos_utiles.size end def irc_channel "#device_#{self.id}" end def recalculate_port_numbers self.puertos.each_with_index do |puerto, number| puerto.numero = number + 1 puerto.save end end # TODO: Change the appropiate inital state, for now is ready state_machine :status, :initial => :ready do state :initializing state :reseting state :ready event :reset do transition all - :reseting => :reseting end event :do_boot do transition all - :initializing => :initializing end event :set_ready do transition all - :ready => :ready end end # Retrieves the current practica this device is on, if is not in a practica, returns nil def current_practica Practica.abiertas.search({:dispositivos_id_equals => self.id}, :join_type => :inner).first end end
class DropAddRandomTable < ActiveRecord::Migration def change # drop_table(:randoms) create_table(:random_events) do |t| t.column(:change_happiness, :integer) t.column(:change_energy, :integer) t.column(:change_money, :float) t.column(:description, :string) end end end
require 'data_magic' namespace :es do desc "delete elasticsearch index (_all for all)" task :delete, [:index_name] => :environment do |t, args| DataMagic.client.indices.delete(index: args[:index_name]) end desc "list elasticsearch indices" task :list => :environment do |t, args| result = DataMagic.client.indices.get(index: '_all').keys puts result.join("\n") end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe StoreComment, "StoreCommentモデルのテスト", type: :model do describe 'バリデーションのテスト' do let!(:store_comment) { create(:store_comment) } context '登録ができるか' do it "全ての情報があれば登録できる" do expect(store_comment).to be_valid end end context 'titleカラム' do it '空白だと登録できない' do store_comment = build(:store_comment, title: '') expect(store_comment).not_to be_valid expect(store_comment.errors[:title]).to include("を入力してください") end it '50字以下であること(50字は◯)' do title = Faker::Lorem.characters(number: 50) store_comment = build(:store_comment, title: title) expect(store_comment).to be_valid end it '50字以下であること(51字は☓)' do title = Faker::Lorem.characters(number: 51) store_comment = build(:store_comment, title: title) expect(store_comment).not_to be_valid expect(store_comment.errors[:title]).to include("は50文字以内で入力してください") end end context 'introductionカラム' do it '空白だと登録できない' do store_comment = build(:store_comment, introduction: '') expect(store_comment).not_to be_valid expect(store_comment.errors[:introduction]).to include("を入力してください") end it '50字以下であること(2000字は◯)' do introduction = Faker::Lorem.characters(number: 2000) store_comment = build(:store_comment, introduction: introduction) expect(store_comment).to be_valid end it '50字以下であること(2001字は☓)' do introduction = Faker::Lorem.characters(number: 2001) store_comment = build(:store_comment, introduction: introduction) expect(store_comment).not_to be_valid expect(store_comment.errors[:introduction]).to include("は2000文字以内で入力してください") end end context 'rateカラム' do it 'rateの値がないと登録できない' do store_comment = build(:store_comment, rate: '') expect(store_comment).not_to be_valid expect(store_comment.errors[:rate]).to include("を入力してください") end end context 'genreカラム' do it 'genreの値がないと登録できない' do store_comment = build(:store_comment, genre: '') expect(store_comment).not_to be_valid expect(store_comment.errors[:genre]).to include("を入力してください") end end end describe 'アソシエーションのテスト' do context 'userモデルとの関係' do it 'N:1となっている' do expect(StoreComment.reflect_on_association(:user)).to be_present end end context 'storeモデルとの関係' do it 'N:1となっている' do expect(StoreComment.reflect_on_association(:store)).to be_present end end context 'favoritesモデルとの関係' do it '1:Nとなっている' do expect(StoreComment.reflect_on_association(:favorites)).to be_present end end end describe 'メソッドのテスト' do context 'favorited_by?メソッド' do let!(:current_user) { create(:user) } let!(:current_comment) { create(:store_comment, user_id: current_user.id) } let!(:current_favorite) do create(:favorite, user_id: current_user.id, store_comment_id: current_comment.id) end let!(:other_user) { create(:user) } let!(:other_comment) { create(:store_comment, user_id: other_user.id) } let!(:other_favorite) do create(:favorite, user_id: other_user.id, store_comment_id: other_comment.id) end it 'コメントに紐付いたのfavoritesモデルに自分のuser_idが入っている場合はtrueを返す' do expect(current_comment.favorited_by?(current_user)).to be_truthy end it 'コメントに紐付いたのfavoritesモデルに自分のuser_idが入っていない場合はfalseを返す' do expect(other_comment.favorited_by?(current_user)).to be_falsey end end end end
class UsersController < ApplicationController PER_PAGE = 8 # GET users def index unless current_user.can_manage_users? return render_404 end @site = if params[:site] Site.find_by_name(params[:site]) else unless current_user.is_admin current_user.site else nil end end unless current_user.can_manage_site?(@site) return render_404 end @users = User.filter_by_user(current_user).listing.page(params[:page]).per(PER_PAGE) respond_to do |format| format.html # index.html.erb end end # GET users/edit/:id def edit @user = User.find_by_id(params[:id]) if @user.nil? return render_404 end load_sites_for_edit! unless current_user.can_manage_site?(@site) return render_404 end unless current_user.can_manage_user?(@user) return render_404 end respond_to do |format| format.html # index.html.erb end end # GET users/new def new @user = User.new load_sites_for_edit! unless current_user.can_manage_site?(@site) return render_404 end respond_to do |format| format.html # index.html.erb end end # PUT users/update/:id def update @user = User.find_by_id(params[:id]) if @user.nil? return render_404 end unless current_user.can_manage_user?(@user) return render_404 end @user.attributes = params[:user].permit(User.accessible_attributes_by_admin) begin @user.save!(:validate => true) flash[:notice] = message(:users, :updated) return redirect_to users_path rescue ActiveRecord::RecordInvalid => ex load_sites_for_edit! render :action => :new rescue => ex p ex.message raise ex end end # POST users/create def create @user = User.new(params[:user].permit(User.accessible_attributes_by_admin)) begin @user.save!(:validate => true) flash[:notice] = message(:users, :created) return redirect_to users_path rescue ActiveRecord::RecordInvalid => ex load_sites_for_edit! render :action => :new end end # DELETE users/destroy def destroy @user = User.find_by_id(params[:id]) if @user.nil? return render_404 end unless current_user.can_manage_user?(@user) return render_404 end begin @user.destroy flash[:notice] = message(:users, :destroyed) return redirect_to users_path rescue ActiveRecord::RecordInvalid => ex render :action => :new end end private def load_sites_for_edit! @site = if params[:site] Site.find_by_name(params[:site]) else unless current_user.is_admin current_user.site else nil end end @sites = if @site.nil? @sites = Site.listing end @folders = if @site @site.folders.opened.listing else nil end end end
class SecretsController < ApplicationController before_action :require_login, only: [:index, :create, :destroy] def index @secrets = Secret.all end def create flash[:messages] = [] @secret = current_user.secrets.new(secret_params) if @secret.save flash[:messages].push({ 'status' => 'success', 'text' => "Succcesfully added secret" }) else errors = @secret.errors.full_messages errors.each do |error| flash[:messages].push({ 'status' => 'error', 'text' => error }) end end redirect_to "/users/#{current_user.id}" end def destroy flash[:messages] = [] secret = Secret.find(params[:id]) if secret.user == current_user secret.destroy flash[:messages].push({ 'status' => 'success', 'text' => "Succcesfully deleted secret" }) end redirect_to "/users/#{current_user.id}" end private def secret_params params.require(:secret).permit(:content) end def set_user @user = User.find(params[:id]) end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception include SessionHelper before_action :fetch_user private def fetch_user @current_user = User.find_by :id => session[:user_id] if session[:user_id].present? session[:user_id] = nil unless @current_user.present? # This prevents horrors when reseeding end def check_for_login redirect_to login_path unless @current_user.present? end def check_for_access @admin = Admin.find_by :user_id => @current_user.id, :business_id => (params[:id]||params[:business_id]) if @current_user.present? @watch = @current_user.businesses.exists?(params[:id]||params[:business_id]) redirect_to root_path unless @admin.present? || @watch.present? end def check_for_admin redirect_to root_path unless @admin.present? end end
class ApplicationController < ActionController::Base delegate :current_user, :user_signed_in?, to: :user_session protect_from_forgery with: :exception helper_method :current_user, :user_signed_in? def user_session UserSession.new(session) end def require_authentication unless user_signed_in? redirect_to new_user_sessions_path, alert: 'Para realizar esta ação é preciso fazer login' end end def require_no_authentication if user_signed_in? redirect_to root_path, notice: 'Já está logado' end end end
require "formula" class Dtc < Formula homepage "http://www.devicetree.org/" url "http://ftp.debian.org/debian/pool/main/d/device-tree-compiler/device-tree-compiler_1.4.0+dfsg.orig.tar.gz" sha1 "2f9697aa7dbc3036f43524a454bdf28bf7e0f701" def install system "make" system "make", "DESTDIR=#{prefix}", "PREFIX=", "install" mv lib/"libfdt.dylib.1", lib/"libfdt.1.dylib" end test do (testpath/'test.dts').write <<-EOS.undent /dts-v1/; / { }; EOS system "#{bin}/dtc", "test.dts" end end
require 'rails_helper' describe ContactForm do it { should validate_presence_of :email } it { should validate_presence_of :name } it { should validate_presence_of :message } it { should allow_value("person@example.com").for(:email) } it { should_not allow_value("person_email").for(:email) } end
# The Fibonacci sequence is defined by the recurrence relation: # # Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1. # Hence the first 12 terms will be: # # F1 = 1 # F2 = 1 # F3 = 2 # F4 = 3 # F5 = 5 # F6 = 8 # F7 = 13 # F8 = 21 # F9 = 34 # F10 = 55 # F11 = 89 # F12 = 144 # The 12th term, F12, is the first term to contain three digits. # # What is the first term in the Fibonacci sequence to contain 1000 digits? beginning_time = Time.now first = 0 second = 1 fibostance = first + second term = 1 until fibostance.to_s.length == 1000 fibostance = first + second term +=1 first = second second = fibostance end puts term puts fibostance end_time = Time.now puts "Time elapsed #{(end_time - beginning_time)} seconds" # fibs = [1, 1] # fibs << fibs.last(2).inject(:+) until fibs.last.to_s.length >= 1000 # puts fibs.count - 1
Rails.application.routes.draw do resources :questions, only: [:index, :show] root "questions#index" end
require 'rails_helper' RSpec.describe MediaType, type: :model do before { @model = FactoryGirl.build(:media_type) } subject { @model } it { should respond_to(:name) } it { should respond_to(:description) } it { should be_valid } it { should validate_uniqueness_of(:name) } it { should validate_presence_of(:name) } it { should have_many(:media_items) } end
class RewardPoint < ActiveRecord::Base # if we have a program other than Sears, this will need to be a config MAX_POINTS_PER_MONTH = 25_000 belongs_to :user belongs_to :badging, :class_name => 'Reputable::Badging' belongs_to :badge, :class_name => 'Reputable::Badge' named_scope :for, lambda {|user| { :conditions => { :user_id => user.id } }} named_scope :since, lambda {|time| { :conditions => ["created_at > ?", time ] }} named_scope :last_redeemable_for, lambda {|user| { :conditions => { :user_id => user.id }, :order => "redeem_on DESC", :limit => 1 }} # == Callbacks before_create :check_monthly_cap after_create :create_remaining def self.total_for user, since=Time.now.beginning_of_year return 0 unless user RewardPoint.for(user).since(since).collect{|r| r.amount}.sum end protected # before_create def check_monthly_cap last_redeem_on = self.redeem_on || RewardPoint.last_redeemable_for(self.user).first.try(:redeem_on) || Time.now total_points = points_for_user_during last_redeem_on remaining = MAX_POINTS_PER_MONTH - total_points unless remaining >= self.amount @leftover = self.amount - remaining self.amount = remaining end self.redeem_on = last_redeem_on @leftover ||= 0 end # after_create def create_remaining return if @leftover == 0 last_redeem_on = self.redeem_on + 31.days reward_to_alloc = @leftover while reward_to_alloc > 0 current_reward = MAX_POINTS_PER_MONTH >= reward_to_alloc ? reward_to_alloc : MAX_POINTS_PER_MONTH RewardPoint.create :user => user, :amount => current_reward, :redeem_on => last_redeem_on, :badge => badge, :description => "#{self.description} rollover", :badging => badging unless current_reward == 0 last_redeem_on = (last_redeem_on + 31.days) reward_to_alloc -= current_reward end end def points_for_user_during time RewardPoint.sum(:amount, :conditions => { :user_id => self.user.id, :redeem_on => time..(time + 31.days) } ) end end
require 'rubygems' require 'logger' require "yaml" require 'ftools' require 'open3' require 'thread' module Castly module Transcoding class << self attr_accessor :log, :config, :transfer_queue def start(file_path, output, config = nil) configure Thread.new { start_indexer(output) }.run process_ffmpeg(file_path, output) stop_indexer end def configure @config = YAML::load(IO.read("config.yml")) @log = Logger.new("debug.log") @transfer_queue = Queue.new end def process_ffmpeg(path, output_dir) encoding_profile = @config['encoding_profile'] #TODO Transcoding.log.debug("Base ffmpeg_command: #{@config[encoding_profile]['ffmpeg_command']}") command = @config[encoding_profile]['ffmpeg_command'] % [path, @config['segmenter_binary'], @config['segment_length'], output_dir, @config['segment_prefix'] + '_' + encoding_profile, encoding_profile] Transcoding.log.debug("Executing: #{command}") Open3.popen3(command) do |stdin, stdout, stderr| @stop_stdin = stdin stderr.each("\r") do |line| if line =~ /segmenter: (.*)/i Transcoding.log.debug("Segment command #{encoding_profile}: *#{$1}*") @transfer_queue << $1 end if line =~ /ffmpeg/i Transcoding.log.debug("Encoder #{encoding_profile}: #{line}") end if line =~ /error/i Transcoding.log.error("Encoder #{encoding_profile}: #{line}") end end end Transcoding.log.debug("Return code from #{encoding_profile}: #{$?}") raise "WTF OLALA" if $?.exitstatus != 0 end def stop_indexer $exit = true end SLEEP = 3 def start_indexer(output_dir) @log.info('Transfer thread started') loop do value = @transfer_queue.pop unless value sleep(SLEEP) else @log.info("Transfer initiated with value = *#{value}*"); create_index_and_run_transfer(value,output_dir) end break if $exit end ensure @log.info('Transfer thread finished') end def create_index_and_run_transfer(value,output_dir) @log.debug('Creating index') (first_segment, last_segment, stream_end, encoding_profile) = value.strip.split(%r{,\s*}) index_segment_count = @config['index_segment_count'] segment_duration = @config['segment_length'] output_prefix = @config['segment_prefix'] encoding_profile = encoding_profile http_prefix = @config['url_prefix'] first_segment = first_segment.to_i last_segment = last_segment.to_i stream_end = stream_end.to_i == 1 index_file_path = "#{output_dir}/index.m3u8" File.open(index_file_path, 'a') do |index_file| if last_segment == first_segment index_file.write("#EXTM3U\n") index_file.write("#EXT-X-TARGETDURATION:#{segment_duration}\n") end result_file_name = "#{output_prefix}_#{encoding_profile}-%05u.ts\n" % last_segment index_file.write("#EXT-X-MEDIA-SEQUENCE:#{last_segment}\n") index_file.write("#EXTINF:#{segment_duration}, no desc\n") index_file.write("#{http_prefix}#{result_file_name}\n") index_file.write("#EXT-X-ENDLIST\n") if stream_end end @log.debug('Done creating index') end end end end Castly::Transcoding.start( "/root/1.avi", "/srv/apps/castly/video")
class ChangeShortUrl < ActiveRecord::Migration[5.1] def change add_index :short_urls, [:user_id,:short_url], unique: true # add_index :short_urls end end
class Contest < ActiveRecord::Base belongs_to :order belongs_to :account validates_presence_of :name def criteria results = [] results << "Product Name: #{product_name}" if product_name.present? results << "Start Date: #{I18n.l start_date.to_date, format: :short}" if start_date.present? results << "End Date: #{I18n.l end_date.to_date, format: :short}" if end_date.present? results << "Max #: #{max_results}" if max_results.present? return results.join(', ') end end
require 'rails_helper' RSpec.describe User, type: :model do describe 'user登録機能' do context '全て入力してある場合' do it "is valid with a name, email, password, rating" do user = User.new( name: 'rspec', email: "rspec@test.com", password: "password" ) expect(user).to be_valid end end context '入力にからがある場合' do it "is invalid without a name" do user = User.new(name: nil) user.valid? expect(user.errors[:name]).to include("を入力してください") end it "is invalid without a email" do user = User.new(email: nil) user.valid? expect(user.errors[:email]).to include("を入力してください") end it "is invalid without a password" do user = User.new(password: nil) user.valid? expect(user.errors[:password]).to include("を入力してください") end end context 'ユニーク設定' do it "is invalid with a duplicate email" do User.create( name: 'rspec', email: "rspec@test.com", password: "password" ) user = User.new( name: 'rspec', email: "rspec@test.com", password: "password" ) user.valid? expect(user.errors[:email]).to include("はすでに存在します") end end context '文字数制限がある場合' do it "is invalid with password is 6 or less characters" do user = User.new(password: 'a' * 5) user.valid? expect(user.errors[:password]).to include("は6文字以上で入力してください") end end end end
#!/usr/bin/env ruby #encoding: utf-8 require 'json' require 'mechanize' require 'highline/import' backloggery_url = "http://backloggery.com" if ARGV.length < 1 || ARGV.length > 2 puts "Usage: ./backloggery_steam.rb backloggery_username [steam_username]" exit -1 end backloggery_username = ARGV[0].downcase if ARGV.length == 1 steam_username = ARGV[0] else steam_username = ARGV[1] end def ugly_hack_mechanize_is_retarded(str) str.force_encoding('utf-8').chars.select{|i| i.valid_encoding?}.join end puts "Steam user: #{steam_username}" puts puts "=== Backloggery ===" puts "Username: #{backloggery_username}" backloggery_password = ask("Backloggery password: ") { |q| q.echo = "" } backloggery = Mechanize.new { |agent| agent.follow_meta_refresh = true } backloggery.get(backloggery_url) do |login| page = login.form do |form| form['username'] = backloggery_username form['password'] = backloggery_password end.submit if page.uri.to_s.end_with? "login.php" puts "Login failed!" exit 1 else puts "Login successful!" end end puts "Fetching already added games..." existing_games = [] backloggery.get("http://backloggery.com/ajax_moregames.php?user=#{backloggery_username}&console=Steam&rating=&status=&unplayed=&own=&search=&comments=&region=&region_u=0&wish=&alpha=&temp_sys=ZZZ&total=2&aid=1&ajid=0") do |page| page.search("section.gamebox").each do |game| header = game.css("h2") name = header.css("b").text if name.length > 0 existing_games << name.chomp end end end puts "Fetching backloggery new game form..." backloggery.get("http://backloggery.com/newgame.php?user=#{backloggery_username}") do |page| page.encoding = 'utf-8' @new_game_form = page.form; end puts "Fetching steam game list..." steam = Mechanize.new { |agent| agent.follow_meta_refresh = true } steam.get("http://steamcommunity.com/id/#{steam_username}/games?tab=all") do |page| page.encoding = 'utf-8' @gameraw = ugly_hack_mechanize_is_retarded(page.body.match(/rgGames = .*?;/m).to_s.gsub("rgGames = ","").gsub(";","").gsub("\\/","/")) end puts "Uploading steam games..." games = JSON.parse(@gameraw) c = 0 games.each do |game| game_name = ugly_hack_mechanize_is_retarded(game["name"].chomp) game_name = game_name.gsub("\u2122", "") # remove (tm) if existing_games.include? game_name next end appid = game["appid"] @new_game_form['name'] = game_name @new_game_form['console'] = "Steam" @new_game_form['note'] = "Playtime: #{game['hours_forever']}h" @new_game_form['submit2'] = "Stealth Add" if game["availStatLinks"]["achievements"] url = game["friendlyURL"] steam.get("http://steamcommunity.com/id/#{steam_username}/stats/#{url}/?tab=achievments") do |page| block = page.search(".//div[@id='topSummaryAchievements']") achievment_count = block.children()[0].to_s.match(/(\d+) of (\d+)/) if achievment_count @new_game_form['achieve1'] = achievment_count[1] @new_game_form['achieve2'] = achievment_count[2] else puts "Error for #{game_name} achievments" end end end # Check if DLC: steam.get("http://store.steampowered.com/app/#{appid}") do |page| page.encoding = 'utf-8' dlc = page.body.match("Requires the base game.*?<a .*?>(.*?)</a>") if dlc @new_game_form['comp'] = dlc[1].chomp.force_encoding("utf-8").gsub("\u2122", "") # steam have a tendency of adding (tm) to the end of game names here, but not otherwise else @new_game_form['comp'] = game_name end end @new_game_form.submit c+= 1 puts "#{game_name} uploaded (#{c}/#{games.length - existing_games.length})" end
###################################################################### # Copyright (c) 2008-2014, Alliance for Sustainable Energy. # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ###################################################################### module BCL module_function # tarball multiple paths recursively to destination def tarball(destination, paths) # check for filepath length limit full_destination = File.expand_path(destination) if full_destination.length > 259 # 256 chars max; "C:\" doesn't count puts "[TarBall] ERROR cannot generate #{destination} because path exceeds 256 char limit. shorten component name by at least by #{full_destination.length - 259} chars" return end Zlib::GzipWriter.open(destination) do |gzip| out = Archive::Tar::Minitar::Output.new(gzip) paths.each do |fi| if File.exist?(fi) Archive::Tar::Minitar.pack_file(fi, out) else puts "[TarBall] ERROR Could not file file: #{fi}" end end out.close end end def extract_tarball(filename, destination) Zlib::GzipReader.open(filename) do |gz| Archive::Tar::Minitar.unpack(gz, destination) end end def create_zip(_destination, paths) Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile| paths.each do |fi| # Two arguments: # - The name of the file as it will appear in the archive # - The original file, including the path to find it zipfile.add(fi.basename, fi) end end end def extract_zip(filename, destination, delete_zip = false) Zip::File.open(filename) do |zip_file| zip_file.each do |f| f_path = File.join(destination, f.name) FileUtils.mkdir_p(File.dirname(f_path)) zip_file.extract(f, f_path) unless File.exist? f_path end end if delete_zip file_list = [] file_list << filename FileUtils.rm(file_list) end end end
class Idea < ActiveRecord::Base # == Vendor acts_as_markup :description, :active_domains => Cobrand.active_domains validates_markup :description, :minimum => 1 acts_as_fulltextable :title, :description acts_as_profanity_filter :title, :description include ActsAsHasPermalink acts_as_has_permalink { |idea| idea.title.to_s[0..128] } # == Class-level # # === Constants VOTE_POINT_VALUE = 10 SUMMARY_SIZE = 500 # === Scopes named_scope :top, :conditions => "status NOT IN ('deactivated', 'duplicate')", :order => "points DESC, created_at DESC", :limit => 5 named_scope :recent, :conditions => ["created_at >= ?", 7.days.ago], :order => "created_at DESC", :limit => 3 named_scope :by, lambda { |user| { :conditions => { :user_id => user.id } } } named_scope :not, lambda { |*states| { :conditions => ["status NOT IN (?)", states] } } named_scope :filter_category, lambda { |c| c.blank? ? {} : { :conditions => { :idea_category_id => c } } } named_scope :filter_status, lambda { |s| s.blank? ? {} : { :conditions => { :status => s.to_sym } } } named_scope :filter_notes, lambda { |n| return {} if n.blank? { :conditions => n == "true" ? "notes_count > 0" : "notes_count = 0" } } named_scope :filter_dates, lambda { |start_date, end_date| k, v = [], [] [["created_at >= ?", start_date], ["created_at <= ?", end_date]].each do |pair| unless pair[1].blank? then k << pair[0]; v << pair[1] end end k.length > 0 ? {:conditions => [k.join(" AND "), *v] } : {} } named_scope :for_all_rss, lambda { |*args| options = {} options[:limit] = (args[0] || 20) options[:order] = "created_at DESC" options[:include] = [:user, :idea_category] options } # === Associations belongs_to :user belongs_to :idea_category belongs_to :idea_instance has_many :notes, :class_name => "IdeaNote" has_many :idea_votes has_many :messages, :as => :about has_many :local_photos, :as => :owner has_many :photos, :as => :owner, :class_name => "LocalPhoto" # === Methods class << self def find_by_param(param, options = {}) return if param.nil? find_by_permalink param, options end def find_by_param!(param, options = {}) find_by_param(param, options) || raise(ActiveRecord::RecordNotFound, "ideas.param=#{param}") end def new_with_defaults(params = nil) returning new(:status => "new") do |idea| idea.attributes = params if params end end def positive_vote VOTE_POINT_VALUE end def negative_vote -VOTE_POINT_VALUE end def for_feed(instance) ideas = [] ideas << filter_status("launched").first(:conditions => { :idea_instance_id => instance.id }, :order => "points DESC") ideas.concat all(:conditions => { :status => %w(development review), :idea_instance_id => instance.id }, :order => "points DESC", :limit => 2) ideas.compact! ideas.concat filter_status("new").all(:conditions => { :idea_instance_id => instance.id }, :order => "points DESC", :limit => (5 - ideas.size)) ideas.compact! ideas.sort! { |x, y| y.points <=> x.points } ideas end # In case the counter caches ever get out of line, this maintenance # method will recalculate them. # # script/runner 'Idea.fix_counter_caches\!' def fix_counter_caches! ActiveRecord::Base.connection.execute <<SQL UPDATE `ideas`, (\ SELECT idea_id, count(*) AS each_count FROM `idea_notes` GROUP BY idea_id\ ) AS notes \ SET ideas.notes_count = notes.each_count WHERE ideas.id = notes.idea_id; SQL end end # == Instance-level # # === Attributes alias_attribute :category_id, :idea_category_id # === Callbacks # # ==== Validations validates_presence_of :title, :description, :category_id, :status, :idea_instance_id, :user validates_each :idea_category, :if => :idea_category_id do |record, attr, v| unless record.idea_category && record.idea_category.leaf? record.errors.add attr, "must be a leaf" end end validates_length_of :title, :in => 2..128 #validates_numericality_of :points, :greater_than_or_equal_to => 0, :if => Proc.new{|i| i.points >= 0 } # ==== Lifecycle before_create :build_vote after_create :log_user_activity after_save :remove_from_user_activity_if_deactivated # === Methods def to_param permalink end def last_comment messages.active.last end def search_for_similar_ideas Idea.search(title, description) - [self] end def vote_for!(user = nil, anonymous_token = nil) return unless voting_allowed? vote(VOTE_POINT_VALUE, user, anonymous_token) end def vote_against!(user = nil, anonymous_token = nil) return unless voting_allowed? vote(-VOTE_POINT_VALUE, user, anonymous_token) end def vote_cast_by(user = nil, anonymous_token = nil) return unless voting_allowed? if user && vote = idea_votes.find_by_user_id(user.id) return vote.points end if anonymous_token && vote = \ idea_votes.find_by_anonymous_token_id(anonymous_token.id) return vote.points end end def can_vote(value) update_attribute :voting_enabled, value end def update_message_count update_attribute :messages_count, messages.active.count end def summary prepare_description_for_display(SUMMARY_SIZE).first end def commentable? idea_instance.messages_enabled && messages_enabled end def votable? idea_instance.voting_enabled && voting_enabled && (idea_instance.active_statuses - %w(launched)).include?(status) end alias voting_allowed? votable? def project_status? idea_instance.project_statuses.include? status end def new_status? idea_instance.new_statuses.include?(status) && created_at > 3.days.ago end private def vote(points, user = nil, anonymous_token = nil) return unless voting_allowed? disable_profanity_filter vote = if user idea_votes.find_or_initialize_by_user_id(user.id) else idea_votes.find_or_initialize_by_anonymous_token_id(anonymous_token.id) end vote.points = points # doubles the points if updating an existing idea vote vote.save end def log_user_activity UserActivity.posted_idea self end def remove_from_user_activity_if_deactivated UserActivity.destroy_activity_for_subject(self) if (status == :deactivated and status_was != :deactivated) end def build_vote self.last_voted_at = Time.now idea_votes.build :points => VOTE_POINT_VALUE, :user => user end end
class ListingsController < ApplicationController before_action :require_login, only: [:edit, :update] def index if params[:query].present? @listings = Listing.search(params[:query], page:params[:page]) else # @listings = Listing.all.page params[:page] @listings = current_user.listings.all end end def new @user = current_user @listing = Listing.new end def create @listing = current_user.listings.build(listing_params) if @listing.save redirect_to @listing else render 'new' end end def show @listing = Listing.find(params[:id]) @reservation = Reservation.new end def edit @listing = Listing.find(params[:id]) end def update @listing = Listing.find(params[:id]) if @listing.update_attributes(listing_params) flash[:success] = "Listing updated" redirect_to @listing else render 'edit' end end def destroy @listing.destroy flash[:sucess]="Listing deleted" redirect_to '/' end private def listing_params params.require(:listing).permit(:property_type, :room_type, :accommodates, :bedrooms, :beds, :bathrooms, :name, :description, :country, :address, :city, :state, :zip_code, {photos: []}) end end
class EasyPageUserTab < ActiveRecord::Base belongs_to :page_definition, :class_name => "EasyPage", :foreign_key => 'page_id' belongs_to :user acts_as_list scope :page_tabs, lambda { |page, user_id, entity_id| { :conditions => EasyPageUserTab.tab_condition(page.id, user_id, entity_id), :order => "#{EasyPageUserTab.table_name}.position"}} def self.tab_condition(page_id, user_id, entity_id) cond = "#{EasyPageUserTab.table_name}.page_id = #{page_id}" cond << (user_id.blank? ? " AND #{EasyPageUserTab.table_name}.user_id IS NULL" : " AND #{EasyPageUserTab.table_name}.user_id = #{user_id}") cond << (entity_id.blank? ? " AND #{EasyPageUserTab.table_name}.entity_id IS NULL" : " AND #{EasyPageUserTab.table_name}.entity_id = #{entity_id}") cond end private # Overrides acts_as_list - scope_condition def scope_condition EasyPageUserTab.tab_condition(self.page_id, self.user_id, self.entity_id) end end
require 'net/http' require "csv" class StooqApi DATA_SOURCE_URL = 'https://stooq.pl/q/d/l/' attr_reader :url def initialize @url = URI.parse(DATA_SOURCE_URL) end def get_data(stock_symbol:, period: 'd') params = { s: stock_symbol, i: period } url.query = URI.encode_www_form(params) response = Net::HTTP.get_response(url) CSV.parse(response.body, headers: true).map do |row| row.to_hash end end end
require 'spec_helper' feature "Signing in" do background do @user = FactoryGirl.create(:user) end scenario "Signing in with correct credentials" do visit '/sessions/create' within(".new_user") do fill_in 'user[email]', :with => @user.email fill_in 'user[password]', :with => @user.password end click_button 'Login' expect(page).to have_content "Welcome to the Wound Management System!" end given(:other_user) { User.create!(:email => 'other@example.com', :password => '1234rous') } scenario "Signing in with wrong information" do visit '/sessions/create' within(".new_user") do fill_in 'user[email]', :with => other_user.email fill_in 'user[password]', :with => "were" end click_button 'Login' expect(page).to have_content 'Staff Login' end scenario "Signing Out a user" do visit '/sessions/create' within(".new_user") do fill_in 'user[email]', :with => @user.email fill_in 'user[password]', :with => @user.password end click_button 'Login' click_link 'Logout' expect(page).to have_content 'Staff Login' end end
require 'test_helper' class ActivationsControllerTest < ActionController::TestCase setup :activate_authlogic setup do @user = FactoryGirl.create :user @active_user = FactoryGirl.create :active_user end test "Activating User" do @user.reset_perishable_token! get :create, :activation_code=>@user.perishable_token assert_equal "Your account has been activated!", flash[:notice], "Check Flash Notice" assert_not_nil UserSession.find(@user), "Check Session is Created" assert_redirected_to root_url assert !ActionMailer::Base.deliveries.empty?, "Check Email is sent" end test "Active Users Gets Redirected" do UserSession.create(@active_user) get :create, :activation_code=>@active_user.perishable_token assert_redirected_to root_url assert_equal "You've already activated your account!", flash[:notice] end test "Incorrect Token Doesn't work" do @user.reset_perishable_token get :create, :activation_code=>@user.perishable_token assert_equal "Couldn't find that activation code", flash[:error], "Check Flash Error" assert_nil UserSession.find(@user), "Check Session isn't Created" assert_redirected_to root_url end test "Already Active User Doesn't Work" do @active_user.reset_perishable_token! get :create, :activation_code=>@active_user.perishable_token assert_equal "You're already activated", flash[:error], "Check Flash Error" assert_nil UserSession.find(@user), "Check Session isn't Created" assert_redirected_to root_url end end
class NullifyInvalidMeasurements < ActiveRecord::Migration def self.up Measurement.find_each do |measurement| unless measurement.valid? measurement.attribute_names.each do |attribute| unless measurement.errors[attribute].blank? measurement.send("#{attribute}=",nil) end end end measurement.save! end end def self.down end end
class IndianMusicEvaluationService < ExperimentService class << self SONG_SIZE = 10 def create(options) DB.transaction do exp = Experiment.create( username: options['username'], model: 'IndianMusicEvaluationEntry', ) SONG_SIZE.times.to_a.shuffle.each do |i| IndianMusicEvaluationEntry.create( experiment: exp, song_id: i, ) end return IndianMusicEvaluationService.new(exp) end end def find(options) exp = Experiment.where( username: options['username'], model: 'IndianMusicEvaluationEntry', )&.first raise NotFoundError.new('Experiment', 'No such experiment exists') if exp.nil? IndianMusicEvaluationService.new(exp) end def export Experiment.where( model: 'IndianMusicEvaluationEntry', ).map do |exp| res = exp.entries.order(:song_id).map do |pair| { id: pair.song_id, ornamentation: pair.ornamentation, grooviness: pair.grooviness, familiarity: pair.familiarity, liking: pair.liking, consonance: pair.consonance, valence: pair.valence, excitement: pair.excitement, sound_quality: pair.sound_quality, tempo: pair.tempo, rhythmic_regularity: pair.rhythmic_regularity, vocal_range: pair.vocal_range, vocal_tension: pair.vocal_tension, vocal_texture: pair.vocal_texture, instrument_vocal_overlap: pair.instrument_vocal_overlap, instrument_overlap: pair.instrument_overlap, instrument_tone_blend: pair.instrument_tone_blend, instrument_rhythm_blend: pair.instrument_rhythm_blend, edited: pair.edited, } end { username: exp.username, matrix: res, } end end end def initialize(entity) @entity = entity end def offset cat = @entity.username[-1].to_i raise NotFoundError.new('Entity', 'No Such Category') unless (0..5).include?(cat) # 6 Groups @entity.username[-1].to_i * 4 + 6 # Each group has 4 songs to be tested, skip the first 6 songs end def next entity = @entity.entries.where(edited: false).order(:id).first raise NotFoundError.new('Entity', 'Experiment Finished') if entity.nil? res = { id: entity.id, progress: @entity.entries.where(edited: true).count.to_f / @entity.entries.count, wavs: [] } if (0..5).include?(entity.id) res[:wavs] << { label: 'Sample', entity: "/static/indian_music/sample#{entity.song_id}.mp3", } else res[:wavs] << { label: 'Sample', entity: "/static/indian_music/#{entity.song_id + offset}.mp3", } end res end def update(options) entry = @entity.entries.where(id: options['id'])&.first raise NotFoundError.new('Entry does not exist') if entry.nil? entry.ornamentation = options['ornamentation'] entry.grooviness = options['grooviness'] entry.familiarity = options['familiarity'] entry.liking = options['liking'] entry.consonance = options['consonance'] entry.valence = options['valence'] entry.excitement = options['excitement'] entry.sound_quality = options['sound_quality'] entry.tempo = options['tempo'] entry.rhythmic_regularity = options['rhythmic_regularity'] entry.vocal_range = options['vocal_range'] entry.vocal_tension = options['vocal_tension'] entry.vocal_texture = options['vocal_texture'] entry.instrument_vocal_overlap = options['instrument_vocal_overlap'] entry.instrument_overlap = options['instrument_overlap'] entry.instrument_tone_blend = options['instrument_tone_blend'] entry.instrument_rhythm_blend = options['instrument_rhythm_blend'] entry.edited = true entry.save nil end def destroy @entity.entries.delete @entity.delete end end
# == Schema Information # # Table name: shop_types # # id :integer not null, primary key # created_at :datetime not null # updated_at :datetime not null # i18n_name_id :integer # i18n_description_id :integer # shop_id :integer # class ShopType < ActiveRecord::Base belongs_to :i18n_name, class_name: 'I18nKey' belongs_to :i18n_description, class_name: 'I18nKey' belongs_to :shop end
class Locations attr_reader :locations def initialize @locations = [] end def add(location) @locations.push(location) end end
class PatchArtistNames < Patch def call # Prevent slug conflicts each_printing do |card| unless card["artist"] unless card["name"] == "Look at Me, I'm R&D" warn "No artist for #{card["name"]} #{card["set_code"]} #{card["number"]}" end card["artist"] = "unknown" end end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'play_store_info/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |spec| spec.name = 'play_store_info' spec.version = PlayStoreInfo::VERSION spec.authors = ['Hugo Sequeira'] spec.email = ['hugoandresequeira@gmail.com'] spec.homepage = 'https://github.com/hugocore/play_store_info' spec.summary = 'Simple Google Play store parser' spec.description = 'Simple Google Play store parser' spec.license = 'MIT' spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(spec)/}) } spec.add_dependency 'metainspector', '~> 5.1.1' spec.add_dependency 'sanitize', '~> 4.0.1' spec.add_development_dependency 'bundler', '~> 1.10' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.3' spec.add_development_dependency 'rubocop', '~> 0.35' spec.add_development_dependency 'rubocop-rspec', '~> 1.3' spec.add_development_dependency 'pry', '~> 0.10' spec.add_development_dependency 'vcr', '~> 3.0' spec.add_development_dependency 'webmock', '~> 1.22' end
# == Schema Information # # Table name: courses # # id :integer not null, primary key # title :string(255) # author :string(255) # image :string(255) # desc :text # created_at :datetime not null # updated_at :datetime not null # user_id :integer # ispublished :integer default(0) # releasemonth :string(255) default("December") # class Course < ActiveRecord::Base self.per_page = 6 acts_as_commentable attr_accessible :lms_id,:attachment,:author, :desc, :image, :title, :topic_id, :user_id, :ispublished, :releasemonth, :ispopular,:filename,:content_type,:data, :short_desc scope :teachers, joins(:teaching_staff_courses).where('teaching_staff_courses.teaching_staff_type = ?', "teacher") scope :teacher_assistants, joins(:teaching_staff_courses).where('teaching_staff_courses.teaching_staff_type = ?', "teacher_assitant") #has_many :relationships scope :enrolled_students, joins(:student_courses).where('student_courses.status = ?', "enroll") scope :completed_students, joins(:student_courses).where('student_courses.status = ?', "completed") scope :shortlisted_students, joins(:student_courses).where('student_courses.status = ?', "shortlisted") belongs_to :topic has_many :student_courses has_many :students, :through => :student_courses has_many :teaching_staff_courses has_many :teaching_staffs, :through => :teaching_staff_courses has_many :course_coupons has_many :coupons, :through => :course_coupons has_one :rating_cache belongs_to :user letsrate_rateable "rate" has_many :course_pricings #before_save { |course| course.category = category.downcase } validates :title, presence: true, length: { maximum: 100 } has_one :course_status has_many :course_payments has_many :previews #before_save { |course| course.category = category.downcase } validates :desc, presence: true, length: { maximum: 1000 } default_scope order: 'courses.created_at DESC' def self.enrollcourse(studentid,courseid) @enroll=Course.connection.select_all("select count(*) as co from student_courses where student_id=#{studentid} and course_id= #{courseid}") end def attachment=(incoming_file) self.image = incoming_file.original_filename self.content_type = incoming_file.content_type self.data = incoming_file.read end def image=(new_filename) write_attribute("image", sanitize_filename(new_filename)) end private def sanitize_filename(filename) #get only the filename, not the whole path (from IE) just_filename = File.basename(filename) #replace all non-alphanumeric, underscore or periods with underscores just_filename.gsub(/[^\w\.\-]/, '_') end end
class UserSkill < ApplicationRecord belongs_to :user belongs_to :skill validates :user_id, presence: true validates :skill_id, presence: true mount_uploader :multimedia, SkillUploader end
# frozen_string_literal: true require "forwardable" module IdNumberLatam class Base extend Forwardable def_delegators :@dni_class, :format, :unformat, :valid? attr_accessor :id_number, :unformatted_id_number, :country def initialize(id_number, opts = {}) @id_number = id_number @country = opts.delete(:country)&.to_sym @dni_class = get_dni_class.new(@id_number) if @country end def get_dni_class return unless @country country_dni_class = IdNumberLatam.constants.map(&:to_s).detect { |c| c == "#{@country.capitalize}Dni" } unless country_dni_class raise "class IdNumberLatam::#{@country.capitalize}Dni not implemented for #{@country} country code" end IdNumberLatam.const_get country_dni_class end end end
module LanguageHelpers def check_language (var) return current_lang.to_s.eql? var end def full_lang_name(lang) case lang.to_s when "pl" "Polski" when "en" "English" when "es" "Español" end end def current_lang I18n.locale end def other_langs langs - [I18n.locale] end end
class Review < ApplicationRecord belongs_to :user_country has_one :country, through: :user_country has_one :user, through: :user_country end
json.brand do json.partial! "item", brand: @brand end
class Admin::Cms::GroupsController < Admin::Cms::BaseController before_action :build_group, :only => [:new, :create] before_action :load_group, :only => [:edit, :update, :destroy] def files mirrored_site_ids @items = Cms::File.includes(:categories).for_category(params[:category]).where(['site_id IN (?)', @site_ids]).order('cms_files.position').group_by(&:group_id) groups_by_parent('Cms::File') render :action => :index, :layout => false end def snippets @site_ids = [@site.id] @items = @site.snippets.includes(:categories).for_category(params[:category]).order('cms_snippets.position').group_by(&:group_id) groups_by_parent('Cms::Snippet') logger.info("@@@ SNIPPET GROUPS: #{@groups.inspect}") render :action => :snippets, :layout => false end def images mirrored_site_ids @items = Cms::File.includes(:categories).for_category(params[:category]).where(["file_content_type LIKE 'image%' AND site_id IN (?)", @site_ids]).order('cms_files.position').group_by(&:group_id) groups_by_parent('Cms::File') # avoid multiple retrieval due to several web editors response.headers['Cache-Control'] = 'max-age=60, must-revalidate' render :template => '/admin/cms/groups/images', :layout => false end def new render end def edit render end def create @group.save! flash[:success] = I18n.t('cms.groups.created') redirect_to :action => :edit, :id => @group.id rescue ActiveRecord::RecordInvalid flash.now[:error] = I18n.t('cms.groups.creation_failure') render :action => :new end def update @group.update_attributes!(group_params) flash[:success] = I18n.t('cms.groups.updated') redirect_to :action => :edit, :id => @group.id rescue ActiveRecord::RecordInvalid flash.now[:error] = I18n.t('cms.groups.update_failure') render :action => :edit end def destroy @group.destroy flash[:success] = I18n.t('cms.groups.deleted') redirect_to eval("admin_cms_site_#{@group.grouped_type.underscore.split('/').pluralize}_url") end protected def mirrored_site_ids @site_ids = (@site.mirrors).uniq.map(&:id) end def groups_by_parent(type) @groups = Cms::Group.where(['grouped_type = ? AND site_id IN (?)', type, @site_ids]).group_by(&:parent_id) end def build_group type = params[:grouped_type] case type when 'Cms::Snippet' # create to this site default = @site.groups.where(grouped_type: type).first @group = @site.groups.build({grouped_type: type, parent_id: default.nil? ? nil : default.id }) else # create on the original mirror default = @site.original_mirror.groups.where(grouped_type: type).first @group = @site.original_mirror.groups.build({grouped_type: type, parent_id: default.nil? ? nil : default.id }) end @group.attributes = group_params end def load_group @group = Cms::Group.where(['id = ? AND site_id IN (?)', params[:id], @site.mirrors.map(&:id)]).first end def group_params params.fetch(:group, {}).permit! end end
class RenameColumnt < ActiveRecord::Migration def change rename_column :program_sizes, :planed_added, :planned_added end end
class Contract < ActiveRecord::Base has_many :stations, dependent: :destroy has_many :weather_data_points, dependent: :destroy end
class ExportJob < Struct.new(:export, :filename, :type, :base_uri) def enqueue(job) job.delayed_reference_id = export.id job.delayed_reference_type = export.class.to_s job.delayed_global_reference_id = export.to_global_id job.save! end def perform strio = StringIO.new exporter = SkosExporter.new(filename, type, base_uri, Logger.new(strio)) exporter.run @messages = strio.string end def success(job) export.finish!(@messages) end def error(job, exception) export.fail!(exception) end end
class BIDCustomPickerViewController < UIViewController attr_accessor :picker, :winLabel, :column0, :column1, :column2, :column3, :column4, :column5, :button def showButton button.hidden = false end def playWinSound path = NSBundle.mainBundle.pathForResource('win', ofType: 'wav') soundID = Pointer.new('I') AudioServicesCreateSystemSoundID(NSURL.fileURLWithPath(path), soundID) winLabel.text = 'WIN!' performSelector('showButton', withObject: nil, afterDelay: 1.5) end def spin win = false; num_in_row = 1 last_val = -1 for index in 1...5 do new_value = Random.new.rand % column1.count if new_value === last_val num_in_row += 1 else num_in_row = 1 end last_val = new_value picker.selectRow(new_value, inComponent: index, animated: true) picker.reloadComponent(index) win = true if num_in_row >= 3 end button.hidden = true path = NSBundle.mainBundle.pathForResource('crunch', ofType: 'wav') soundID = Pointer.new('I') AudioServicesCreateSystemSoundID(NSURL.fileURLWithPath(path), soundID) AudioServicesPlaySystemSound(soundID.cast!('I')) if win performSelector('playWinSound', withObject: nil, afterDelay: 0.5) else performSelector('showButton', withObject: nil, afterDelay: 0.5) end winLabel.text = '' Random.srand end def viewDidLoad super for index in 0..5 do image_names = ['seven', 'bar', 'crown', 'cherry', 'lemon', 'apple'] images = image_names.map { |name| UIImage.imageNamed(name) } image_views = images.map { |image| UIImageView.alloc.initWithImage(image) } setValue(image_views, forKey: "column#{index}") end end def viewDidUnload super [picker, winLabel, column0, column1, column2, column3, column4, column5].each do |outlet| self.outlet = nil end end def shouldAutorotateToInterfaceOrientation(interface_orientation) interfaceOrientation === UIInterfaceOrientationPortrait end def numberOfComponentsInPickerView(picker_view) 5 end def pickerView(picker_view, numberOfRowsInComponent: component) column1.count end def pickerView(picker_view, viewForRow: row, forComponent: component, reusingView: view) array_name = "column#{component + 1}" array = valueForKey(array_name) array.objectAtIndex(row) end end
require 'rails_helper' describe "When an order has been placed" do before :each do @user = User.create(name: 'Christopher', email: 'christopher@email.com', password: 'p@ssw0rd', role: 0) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(@user) @address = @user.addresses.create(address_nickname: 'Home', address: '123 Oak Ave', city: 'Denver', state: 'CO', zip: 80021) @bike_shop = Merchant.create(name: "Meg's Bike Shop", address: '123 Bike Rd.', city: 'Denver', state: 'CO', zip: 80_203, enabled?: false) @tire = @bike_shop.items.create(name: 'Tire', description: 'Great tire!', price: 100, image: 'http://lovencaretoys.com/image/cache/dog/tug-toy-dog-pull-9010_2-800x800.jpg', inventory: 32) @order = @user.orders.create(address_id: @address.id, status: 2) ItemOrder.create(order_id: @order.id, item_id: @tire.id, quantity: 2, price: 20) end it 'can be edited if not shipped' do visit "/user/orders/#{@order.id}/edit" choose "order[address_id]" click_button "Update Order" expect(page).to have_content("#{@address.address_nickname}") end end
require 'spec_helper' describe Prediction do it { should belong_to(:forecast) } describe "attributes" do it { should respond_to(:game_id) } it { should respond_to(:winning_team_id) } it { should respond_to(:losing_team_id) } it { should respond_to(:winning_team_score) } it { should respond_to(:losing_team_score) } it { should respond_to(:forecast_id) } it { should allow_mass_assignment_of(:game_id) } it { should allow_mass_assignment_of(:winning_team_id) } it { should allow_mass_assignment_of(:losing_team_id) } it { should allow_mass_assignment_of(:winning_team_score) } it { should allow_mass_assignment_of(:losing_team_score) } it { should allow_mass_assignment_of(:forecast_id) } end end
name 'managed_directory' maintainer 'Zachary Stevens' maintainer_email 'zts@cryptocracy.com' license 'Apache 2.0' description 'Provides the managed_directory resource' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) source_url 'https://github.com/zts/chef-cookbook-managed_directory' issues_url 'https://github.com/zts/chef-cookbook-managed_directory/issues' supports 'centos' supports 'redhat' supports 'mac_os_x' chef_version '>= 12.5' version '0.3.2'
class Monsters attr_accessor :name, :size, :type ,:alignment ,:armor_class ,:hit_points @@all = [] def initialize @@all << self end def self.all @@all end end
# frozen_string_literal: true class City < ApplicationRecord has_many :users, dependent: :nullify validates :zip_code, presence: true, format: { with: /\A(?:[0-8]\d|9[0-8])\d{3}\Z/ } end
# Purty colours require 'highline/import' begin require 'Win32/Console/ANSI' if RUBY_PLATFORM =~ /win32/ rescue LoadError raise 'You must `gem install win32console` to use color on Windows' end def command_echoing_output(cmd) escaped = cmd.gsub("'", "\\\\'") say "<%=color('#{escaped}', RED)%>" IO::popen(cmd) do |o| o.each { |output| print output } end end def update_subtree(subtree_dir, git_remote, git_branch = 'master', repo_root = '.') say "<%=color('Running git from #{repo_root}', WHITE, ON_BLUE)%>" Dir.chdir repo_root do |path| command_echoing_output "git subtree pull --squash -P #{subtree_dir} #{git_remote} #{git_branch}" end end desc "Update GLM subtree" task :update_subtree_glm do update_subtree 'external/glm', 'git://github.com/g-truc/glm.git' end desc "Update GLM subtree" task :update_subtree_gmgridview do update_subtree 'hosts/ios/external/GMGridView', 'git://github.com/gmoledina/GMGridView.git' end
require "overridden_helpers" require "utilities" module ApplicationHelper include OverriddenHelpers include Utilities def relative_time_tag(to_time, start_caps = false) format = relative_time(to_time) format = format[0].upcase + format[1...format.size] if start_caps time_tag to_time, to_time.strftime(format) end def relative_event_time_tag(event) start_str = event.date.past? ? "Started" : "Starting" end_str = event.end_date.past? ? "ended" : "ends" start_time = relative_time_tag event.date end_time = relative_time_tag event.end_date "#{start_str} #{start_time}, #{end_str} #{end_time}".html_safe end def link_to_block(name = nil, options = nil, html_options = nil) link_to options, html_options do content_tag :span, name end end # Adds :size parameter to html_options. This is the size of the image # being requested. def link_avatar(options, html_options = {}) html_options.merge!(class: " avatar") { |_, old, new| old + new } url = options.avatar_url(html_options[:size] || 256) link_to options, html_options do image_tag url end end def validation_error_messages!(resource) return "" if resource.errors.empty? messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join sentence = I18n.t("errors.messages.not_saved", count: resource.errors.count, resource: resource.class.model_name.name) <<-HTML.html_safe <div id="error-explanation"> <h2>#{sentence}</h2> <ul>#{messages}</ul> </div> HTML end end
# frozen_string_literal: true require 'grpcs/grpcapi-go-server/article_pb' class ArticleApi::Article::CreateService < ArticleApi::Article def call(title) req = Grpcs::GrpcapiGoServer::Article::CreateArticleRequest.new(title: title) @service.create_article(req) end end
require 'rails_helper' feature 'Editing audit details', :omniauth, :js do let!(:user) { create(:user) } let!(:audit) { create(:audit, name: 'My audit', user: user) } let!(:audit_structure_type) { audit.audit_structure.audit_strc_type } before do signin_as user visit audits_path end scenario 'for attributes on the audit structure record' do click_audit audit.name click_section_tab 'Details' expect(page).to have_grouping 'Structure' expect(page).to have_field('Name', with: 'My audit') fill_in 'Name', with: 'My new audit' click_section_tab 'Substructures' # Changes should persist when navigating back to the same page click_crumb_link 'All audits' click_audit 'My new audit' click_section_tab 'Details' expect(page).to have_field('Name', with: 'My new audit') end scenario 'for structure fields' do grouping = create(:grouping, name: 'Auditor', audit_strc_type: audit.audit_structure.audit_strc_type) create(:audit_field, :string, display_order: 1, grouping: grouping, name: 'Auditor name') create(:audit_field, :email, display_order: 2, grouping: grouping, name: 'Email') click_audit audit.name click_section_tab 'Details' expect(page).to have_grouping 'Auditor' expect(page).to have_field('Auditor name') expect(page).to have_field('Email') fill_in 'Auditor name', with: 'Marty McFly' fill_in 'Email', with: 'mmcfly@wegowise.com' click_section_tab 'Substructures' click_crumb_link 'All audits' click_audit audit.name click_section_tab 'Details' expect(page).to have_field('Auditor name', with: 'Marty McFly') expect(page).to have_field('Email', with: 'mmcfly@wegowise.com') end end
class Fluentd module Setting class FormatterLtsv include Fluentd::Setting::Plugin register_plugin("formatter", "ltsv") def self.initial_params {} end def common_options [ :delimiter, :label_delimiter, :add_newline ] end end end end