text
stringlengths
10
2.61M
# == Schema Information # # Table name: self_evaluations # # id :integer not null, primary key # duties :text # self_evaluation_totality :string # middle_manager_id :integer # created_at :datetime not null # updated_at :datetime not null # created_year :integer # activity_id :integer # user_info :string # evaluated_user_info :text # user_info_id :integer # activity_year :string # department_and_duty :string # job :string # require 'rails_helper' RSpec.describe SelfEvaluation, type: :model do it { should belong_to(:activity)} it { should belong_to(:middle_manager)} it { should have_many(:evaluations)} it { should have_one(:result)} end
class CreateObjectivesMainQuestionsJoinTable < ActiveRecord::Migration def change create_table :main_questions_objectives, id: false do |t| t.integer :main_question_id t.integer :objective_id end add_index :main_questions_objectives, :main_question_id add_index :main_questions_objectives, :objective_id end end
require "rails_helper" describe "Global Templates Search Query API", :graphql do describe "globalTemplatesSearch" do let(:query) do <<-'GRAPHQL' query($tag: String!) { globalTemplatesSearch(tag: $tag) { body tags } } GRAPHQL end it "gets global templates" do create(:global_template, tags: ["testing"]) result = execute query, as: build(:user), variables: { tag: "test", } templates = result[:data][:globalTemplatesSearch] expect(templates.count).to eq(1) end it "does not get user templates" do user = create(:user) create(:template, user: user, tags: ["testing"]) result = execute query, as: build(:user), variables: { tag: "test", } templates = result[:data][:globalTemplatesSearch] expect(templates.count).to eq(0) end end end
Gem::Specification.new do |spec| spec.name = 'bluzelle' spec.version = '0.1.1' spec.date = '2020-04-20' spec.summary = "Ruby gem client library for the Bluzelle Service" spec.description = "Ruby gem client library for the Bluzelle Service" spec.authors = ["bluzelle"] spec.email = 'hello@bluzelle.com' spec.files = ["lib/bluzelle.rb"] spec.homepage = 'https://rubygemspec.org/gems/bluzelle' spec.license = 'MIT' # spec.add_dependency "money-tree" # spec.add_dependency "secp256k1" spec.add_dependency "ecdsa", "~> 1.2.0" spec.add_dependency "bip_mnemonic", "~> 0.0.4" spec.add_development_dependency "dotenv" end
module SqlMigrations class SqlScript attr_reader :date, :time, :name def initialize(path, opts) @date = opts[:date] @time = opts[:time] @name = opts[:name] @path = opts[:path] @db_name = opts[:db_name] @content = IO.read(path) @type = self.class.name.downcase.split('::').last @datetime = (@date + @time).to_i end def execute(db) @database = db return unless is_new? begin @database.db.transaction do @benchmark = Benchmark.measure do @database.db.run @content end end rescue puts "[-] Error while executing #{@type} #{@name} !" raise else on_success end end def self.find(db_name, type) scripts = [] Find.find(Dir.pwd) do |path| if !db_name.is_a? Array then db_name = [ db_name ] end file_date, file_time, file_name, file_db = self.file_options(db_name, type, path) next unless file_name scripts << self.new(path, date: file_date, time: file_time, name: file_name, db_name: file_db) end scripts.sort_by { |file| (file.date + file.time).to_i } end private def self.file_options(db_names, type, path) up_dir, dir, filename = path.split(File::SEPARATOR)[-3, 3] # Only files that match agains this regexp file_opts = File.basename(path).match(/(\d{8})_(\d{6})_(.*)?\.sql/) return nil unless file_opts file_in_type_dir = (dir == type.to_s) file_in_type_updir = (up_dir == type.to_s) file_in_db_dir = db_names.include?(dir.to_sym) # There is exception when we are looking for files for more than one database # or we are checking default database only if db_names == [ :default ] || db_names.count > 1 return nil unless (file_in_type_dir || (file_in_db_dir && file_in_type_updir)) else # Only files for specific type (migration/fixture/seed) # Only files for specific database return nil unless (file_in_db_dir && file_in_type_updir) end file_database = db_names.include?(dir.to_sym) ? dir : :default return file_opts[1], file_opts[2], file_opts[3], file_database end def is_new? schema = @database.schema_dataset last = schema.order(Sequel.asc(:time)).where(type: @type).last is_new = schema.where(time: @datetime, type: @type).count == 0 if is_new && !last.nil? if last[:time] > @datetime raise "#{@type.capitalize} #{@name} has time BEFORE last one recorded !" end end is_new end def on_success puts "[+] Successfully executed #{@type}, name: #{@name}" puts " Benchmark: #{@benchmark}" schema = @database.schema_dataset schema.insert(time: @datetime, name: @name, type: @type, executed: DateTime.now) end end end
class Event < ActiveRecord::Base attr_accessor :date, :time attr_accessible :name, :datetime, :message, :description, :assets, :assets_attributes, :location, :location_attributes, :date, :time validates_presence_of :name, :datetime belongs_to :user has_many :assets, as: :assetable accepts_nested_attributes_for :assets has_one :location, :dependent => :destroy accepts_nested_attributes_for :location end
json.categories @categories do |c| json.partial! 'category/show', category: c end
class User < ApplicationRecord before_save { self.email.downcase! } validates :name, presence: true, length: { maximum:50 } validates :email, presence: true, length: { maximum:255 }, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }, uniqueness: { case_sensitive: false } has_secure_password # Rails標準のパスワード付きモデル has_many :microposts has_many :relationships #foreign_key: 'user_id'は命名規則により省略 has_many :followings, through: :relationships, source: :follow #relationshipという中間テーブルを通じて、そのfollow_id列を参照する。 has_many :reverses_of_relationship, class_name: 'Relationship', foreign_key: 'follow_id' has_many :followers, through: :reverses_of_relationship, source: :user #reverses_of_relationshipという中間テーブルを通じ、user_id列を参照 #ここから課題↓ has_many :favorites # foreign_key: 'user_id'省略 自分がお気に入りのMicropostへの参照 has_many :likes, through: :favorites, source: :micropost #favoritesという中間テーブルを通じて、micropost_id列を参照 #has_many :famous_for_user, class_name: 'Favorite', foreign_key: 'Micropost_id' #そのMicropostをお気に入りに登録しているUserへの参 class_nameはFavorite?? #has_many :famousfor,through: :famous_for_user, source: :user #user.famousforでそのMicropostをお気に入りにしているUser達を取得 def follow(other_user) #他のユーザーをフォローするメソッド unless self == other_user #自分自身ではない事を確認 #selfはUserのインスタンス(user.follow(other)を実行したときuserが代入される) self.relationships.find_or_create_by(follow_id: other_user.id)#Relationshipsテーブルのfollow_idカラムから other_user.idに一致するレコード取得 #見つかればRelationshipモデルのインスタンスを返す #見つからなければフォロー関係を作成保存(create = build + save) end end def unfollow(other_user) #アンフォローするメソッド relationship = self.relationships.find_by(follow_id: other_user.id)#Relationshipsテーブルのfollwo_idカラムから other_user.idに一致するレコード取得 relationship.destroy if relationship #上で取得したレコードを削除 #if Relationshipが存在すれば、relationshipをdestroyする end def following?(other_user) #既にフォローしているかどうかを確認するメソッド self.followings.include?(other_user) #self.followingsによりフォローしているUser達を取得 #include?(other_user)でother_userが含まれていないかを確認し、含まれているときはtrue end def feed_microposts Micropost.where(user_id: self.following_ids + [self.id]) #following_idsはUserモデルのhas_many :followings,...によって自動生成されるメソッド。UserがフォローしているUserのidの配列を取得 #self.idもデータ型を合わせるために[self.id]と配列に変換して追加 end def add2favorite(target_post) self.favorites.find_or_create_by(micropost_id: target_post.id) #binding.pry #favoritesテーブルのmicropost_id列からtarget_post_idに一致するレコードを取得。見つかればインスタンスを返す #見つからなければ、お気に入り関係を作成保存 end def rm_favorite(target_post) favorite = self.favorites.find_by(micropost_id: target_post.id) favorite.destroy if favorite #favoriteに登録されていれば、削除する end def myfavorite?(target_post) self.likes.include?(target_post) #自分のお気に入りを確認し、target_postが含まれていればtrueを返す end end
class Map < Sequel::Model plugin :schema set_schema do primary_key :id Integer :from_value_set_id Integer :to_value_set_id DateTime :created_at DateTime :updated_at end create_table unless table_exists? one_to_many :map_entries, :order => :id many_to_one :from_value_set, :class => :ValueSet many_to_one :to_value_set, :class => :ValueSet plugin :validation_helpers plugin :nested_attributes nested_attributes :map_entries plugin :timestamps def self.from_default_to_user_defined from_value_sets(ValueSet.default, ValueSet.user_defined) end def self.from_user_defined_to_default from_value_sets(ValueSet.user_defined, ValueSet.default) end def self.from_value_sets(from_value_set, to_value_set) map = where( :from_value_set_id => from_value_set.id, :to_value_set_id => to_value_set.id ).eager(:map_entries).all.first if map.nil? map = Map.new map.from_value_set = from_value_set map.to_value_set = to_value_set end (map.from_value_set.referenced_entities.map(&:id) - map.map_entries.map(&:from_referenced_entity_id)).each do |from_referenced_entity_id| map.map_entries << MapEntry.new(:from_referenced_entity_id => from_referenced_entity_id) end map end def as_json { :id => id, :from_value_set => from_value_set.as_json, :to_value_set => to_value_set.as_json, :map_entries => map_entries.map(&:as_json) } end def validate super validates_presence [:from_value_set_id, :to_value_set_id] validates_unique [:from_value_set_id, :to_value_set_id] end end
class Voter attr_accessor :name @@ballots = {rep: 1, dem:1} def initialize(name) @name = name end def to_s "#{self.class}: #{name}" end def self.list self.all.each do |instance| puts instance end end def self.find_by(name) self.all.each do |instance| if instance.name == name return instance end end return nil end def self.vote Person.all.each do |person| person.consider(Politician.all.sample) end dark_hole puts "The ballots are in!" @@ballots.each do |k,v| puts "#{k}: #{v}" end @@ballots = {rep: 1, dem:1} end def tally(party) if party == :rep @@ballots[:rep] += 1 else @@ballots[:dem] += 1 end end end class Politician < Voter attr_accessor :party @@politicians = [] def initialize(name, party) super(name) @party = party @@politicians << self end def self.all @@politicians end def to_s "#{party} " + super end def self.parties ["Democrat", "Republican"] end end class Person < Voter attr_accessor :politics @@persons = [] def initialize(name, politics) super(name) @politics = politics @@persons << self end def self.all @@persons end def to_s "#{politics} " + super end def self.political_views ["Tea Party", "Conservative", "Neutral", "Liberal", "Socialist" ] end def consider(politician) case politics when "Tea Party" view_party(politician, 10) when "Conservative" view_party(politician, 25) when "Neutral" view_party(politician, 50) when "Liberal" view_party(politician, 75) when "Socialist" view_party(politician, 90) end end def vote(party) Voter.tally(party) end def view_party(politician, prob) chance = rand(100) + 1 if (politician.party == "Republican") && (chance > prob) tally(:rep) elsif (politician.party == "Democrat") && (chance < prob) tally(:dem) else view_party(politician, prob) end end end
class CreateTweets < ActiveRecord::Migration def change create_table :tweets do |t| t.string :content t.integer :user_id end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) # location = Location.create(:workplace_id, :latitude, :longitude, :address1, :address2, :city, :zip) location1 = Location.create(:latitude => 40.74451, :longitude => -73.99013, :address1 => "33 West 26th st", :address2 => "2nd Floor", :city => "New York", :state => "NY", :zip => "10001") location2 = Location.create(:latitude => 40.75311, :longitude => -73.98921, :address1 => "500 7th Avenue", :address2 => "17th Floor", :city => "New York", :state => "NY", :zip => "10018") location3 = Location.create(:latitude => 40.75598, :longitude => -73.99040, :address1 => "620 8th Ave", :address2 => "1st Floor", :city => "New York", :state => "NY", :zip => "10018") location4 = Location.create(:latitude => 40.76044, :longitude => -73.98049, :address1 => "1271 Avenue of the Americas", :address2 => "1st Floor", :city => "New York", :zip => "10020") location5 = Location.create(:latitude => 40.71886, :longitude => -74.00254, :address1 => "401 Broadway", :address2 => "25th Floor", :city => "New York", :state => "NY", :zip => "10013") location6 = Location.create(:latitude => 40.73959, :longitude => -73.98838, :address1 => "35 E 21st Street", :address2 => "10th Floor", :city => "New York", :state => "NY", :zip => "10010") location7 = Location.create(:latitude => 40.73452, :longitude => -73.99102, :address1 => "841 Broadway", :address2 => "8th Floor", :city => "New York", :state => "NY", :zip => "10003") location8 = Location.create(:latitude => 40.75791, :longitude => -73.98876, :address1 => "229 W 43rd St", :address2 => "1st Floor", :city => "New York", :state => "NY", :zip => "10036") location9 = Location.create(:latitude => 40.70292, :longitude => -73.98948, :address1 => "55 Washington St", :address2 => "1st Floor", :city => "Brooklyn", :state => "NY", :zip => "11201") location10 = Location.create(:latitude => 40.73997, :longitude => -73.99013, :address1 => "10 E 21st St", :address2 => "17th Floor", :city => "New York", :state => "NY", :zip => "10010") # workplace = Workplace.create(:user_id, :name) workplace1 = Workplace.create(:name => "Flatiron School") workplace2 = Workplace.create(:name => "The Alley NYC") workplace3 = Workplace.create(:name => "The New York Times") workplace4 = Workplace.create(:name => "Time Inc") workplace5 = Workplace.create(:name => "Artsy") workplace6 = Workplace.create(:name => "Tumblr") workplace7 = Workplace.create(:name => "Pivotal Labs") workplace8 = Workplace.create(:name => "10gen") workplace9 = Workplace.create(:name => "Etsy") workplace10 = Workplace.create(:name => "General Assembly") user1 = User.create(:name => "Jeff") user2 = User.create(:name => "Blake") user3 = User.create(:name => "Ashley") user4 = User.create(:name => "Joe") user5 = User.create(:name => "Avi") user6 = User.create(:name => "Adam") user7 = User.create(:name => "Kelly") user8 = User.create(:name => "Rebekah") user9 = User.create(:name => "Yehuda") user10 = User.create(:name => "Aidan") user1.friends << user2 user3.friends << user4 user3.friends << user1 user4.friends << user1 user5.friends << user1 user6.friends << user2 user7.friends << user5 user8.friends << user6 user8.friends << user7 user9.friends << user8 user9.friends << user10 user10.friends << user9 workplace1.users << user1 workplace2.users << user2 workplace3.users << user3 workplace4.users << user4 workplace5.users << user5 workplace6.users << user6 workplace7.users << user7 workplace8.users << user8 workplace9.users << user9 workplace10.users << user10 workplace1.location = location1 workplace2.location = location2 workplace3.location = location3 workplace4.location = location4 workplace5.location = location5 workplace6.location = location6 workplace7.location = location7 workplace8.location = location8 workplace9.location = location9 workplace10.location = location10
require "spec_helper" require "rack/test" require 'tempfile' describe "The peers registration manager" do include Rack::Test::Methods def app; Capybara.app end before(:all) do gen_key = OpenSSL::PKey::RSA.new(128) @pem_file = Tempfile.new('pem') @pem_file.write gen_key.public_key.to_pem @name = "me@example.com" @local_url = "http://localhost:9999/application" @existing_peer_name = "existing_peer" @db["peers"].save("_name" => @existing_peer_name, "key" => gen_key.public_key.to_pem, "local_url" => @local_url) end before(:each) {@pem_file.rewind} after(:all) {@pem_file.close} it "rejects registration requests without key" do post "/a/peers/#@name/register", "local_url" => @local_url last_response.status.should == 400 last_response.body.should match(/^KO/) end it "rejects registration requests without local url" do post "/a/peers/#@name/register", "key" => Rack::Test::UploadedFile.new(@pem_file.path, "application/x-pem-file") last_response.status.should == 400 last_response.body.should match(/^KO/) end it "rejects registration requests for previously registered peers" do post "/a/peers/#@existing_peer_name/register", "local_url" => @local_url, "key" => Rack::Test::UploadedFile.new(@pem_file.path, "application/x-pem-file") last_response.status.should == 500 last_response.body.should match(/^KO/) end it "receives registration requests" do post "/a/peers/#@name/register", "local_url" => @local_url, "key" => Rack::Test::UploadedFile.new(@pem_file.path, "application/x-pem-file") last_response.status.should == 200 last_response.body.should == "OK" # Check database @pem_file.rewind peer_request = @db["peers.register"].find_one peer_request.should be peer_request.delete "_id" peer_request.delete "date" peer_request.should == { "_name" => @name, "user_agent" => nil, "local_url" => @local_url, "key" => @pem_file.read, "ip" => "127.0.0.1" } end end describe "The peers manager", :type => :request do before(:all) do @key = OpenSSL::PKey::RSA.new(128) @name = "me@example.com" @local_url = "http://localhost:9999/application" peer_request = {"date" => Time.now.utc, "ip" => "127.0.0.1", "user_agent" => "User Agent", "_name" => @name, "local_url" => @local_url, "key" => @key.public_key.to_pem } @db["peers.register"].save peer_request end it "advertises a unique public key" do visit "/a/key.pem" page.response_headers["Content-Type"].should == "application/x-pem-file" key = source key.should match(/^-----BEGIN PUBLIC KEY-----$/) visit "/a/key.pem" source.should == key end it "displays registration requests" do visit "/a/peers" find("input[type='checkbox']").value.should == @name end it "accepts registrations" do visit "/a/peers" check("users[]") click_on "save" current_path.should == "/a/peers" all("input[type='checkbox']").should be_empty end it "displays peers" do visit "/a/peers" find("li").text.strip.should == @name end it "provides peer keys" do visit "/a/peers/#@name.pem" page.response_headers["Content-Type"].should == "application/x-pem-file" source.should match(/^-----BEGIN PUBLIC KEY-----$/) end it "can add a peer" do url = "http://example.com/openreqs" remote_name = "server_name" remote = {"_name" => remote_name, "key" => "KEY"} FakeWeb.register_uri :get, url + "/a.json", :body => remote.to_json visit "/a/peers" fill_in "server", :with => url click_on "add" current_path.should == "/a/peers" Qu::Worker.new.work_off visit "/a/peers" find("input[type='checkbox']").value.should == remote_name end end describe "The peers authentication verifier" do include Rack::Test::Methods def app; Capybara.app end before(:all) do @key = OpenSSL::PKey::RSA.new(2048) @name = "me@example.com" @local_url = "http://localhost:9999/application" @session = OpenSSL::Random.random_bytes(16).unpack("H*")[0] peer = {"_name" => @name, "key" => @key.public_key.to_pem, "local_url" => @local_url} @db["peers"].save peer end it "rejects unknown peers" do post "/a/peers/unknown/authentication", :session => @session, :name => "unknown", :signature => "BAD_SIGNATURE" last_response.status.should == 404 last_response.body.should match(/^KO/) end it "rejects unknown sessions" it "rejects not signed requests" do post "/a/peers/#@name/authentication", :session => @session, :name => @name last_response.status.should == 400 last_response.body.should match(/^KO/) end it "rejects bad signatures" do post "/a/peers/#@name/authentication", :session => @session, :name => @name, :signature => "BAD_SIGNATURE" last_response.status.should == 400 last_response.body.should match(/^KO/) end it "verifies signatures of messages" do auth_params = {:session => @session, :name => @name} sig_base_str = "name=me%40example.com&session=#@session" auth_params["signature"] = [@key.sign(OpenSSL::Digest::SHA1.new, sig_base_str)].pack('m0').gsub(/\n$/,'') post "/a/peers/#@name/authentication", auth_params last_response.status.should == 200 last_response.body.should == "OK" end end describe "The peers authenticater", :type => :request do before(:all) do @key = OpenSSL::PKey::RSA.new(2048) @name = "me@example.com" @local_url = "http://localhost:9999/application" @data = "CONTENT" peer = {"_name" => @name, "key" => @key.public_key.to_pem, "local_url" => @local_url} self_peer = {"_name" => @name, "private_key" => @key.to_pem, "key" => @key.public_key.to_pem, "self" => true} @db["peers"].save peer @db["peers"].save self_peer end it "authenticate users" do session = OpenSSL::Random.random_bytes(16).unpack("H*")[0] args = {"name" => @name, "peer" => @name, "session" => session, "return_to" => "/a/peers/#@name/authentication"} visit "/a/peers/authenticate?#{URI.encode_www_form(args)}" click_on "save" source.should == "OK" end end describe "The cloner", :type => :request do it "can clone" do docs, reqs = ["doc1", "doc2"], ["req1"] doc1 = [{"_name" => "doc1", "date" => Time.now.utc, "_content" => "doc1 content"}] doc2 = [{"_name" => "doc2", "date" => Time.now.utc, "_content" => "doc2 content"}] req1 = [{"_name" => "req1", "date" => Time.now.utc, "_content" => "req1 content"}] url = "http://example.com" FakeWeb.register_uri :get, url + "/d.json", :body => docs.to_json FakeWeb.register_uri :get, url + "/d/doc1.json?with_history=1", :body => doc1.to_json FakeWeb.register_uri :get, url + "/d/doc2.json?with_history=1", :body => doc2.to_json FakeWeb.register_uri :get, url + "/r.json", :body => reqs.to_json FakeWeb.register_uri :get, url + "/r/req1.json?with_history=1", :body => req1.to_json visit "/a/clone" fill_in "url", :with => url click_on "clone" Qu::Worker.new.work_off @db["docs"].find.count.should == 2 @db["requirements"].find.count.should == 1 end end
# :include: rdoc/configurator # # == Other Info # # Version:: $Id: configurator.rb,v 1.12 2004/03/17 19:13:07 fando Exp $ require "log4r/logger" require "log4r/outputter/staticoutputter" require "log4r/lib/xmlloader" require "log4r/logserver" require "log4r/outputter/remoteoutputter" # TODO: catch unparsed parameters #{FOO} and die module Log4r # Gets raised when Configurator encounters bad XML. class ConfigError < Exception end # See log4r/configurator.rb class Configurator include REXML if HAVE_REXML @@params = Hash.new # Get a parameter's value def self.[](param); @@params[param] end # Define a parameter with a value def self.[]=(param, value); @@params[param] = value end # Sets the custom levels. This method accepts symbols or strings. # # Configurator.custom_levels('My', 'Custom', :Levels) # # Alternatively, you can specify custom levels in XML: # # <log4r_config> # <pre_config> # <custom_levels> # My, Custom, Levels # </custom_levels> # ... def self.custom_levels(*levels) return Logger.root if levels.size == 0 for i in 0...levels.size name = levels[i].to_s if name =~ /\s/ or name !~ /^[A-Z]/ raise TypeError, "#{name} is not a valid Ruby Constant name", caller end end Log4r.define_levels *levels end # Given a filename, loads the XML configuration for Log4r. def self.load_xml_file(filename) detect_rexml actual_load Document.new(File.new(filename)) end # You can load a String XML configuration instead of a file. def self.load_xml_string(string) detect_rexml actual_load Document.new(string) end ####### private ####### def self.detect_rexml unless HAVE_REXML raise LoadError, "Need REXML to load XML configuration", caller[1..-1] end end def self.actual_load(doc) confignode = doc.elements['//log4r_config'] if confignode.nil? raise ConfigError, "<log4r_config> element not defined", caller[1..-1] end decode_xml(confignode) end def self.decode_xml(doc) decode_pre_config(doc.elements['pre_config']) doc.elements.each('outputter') {|e| decode_outputter(e)} doc.elements.each('logger') {|e| decode_logger(e)} doc.elements.each('logserver') {|e| decode_logserver(e)} end def self.decode_pre_config(e) return Logger.root if e.nil? decode_custom_levels(e.elements['custom_levels']) global_config(e.elements['global']) global_config(e.elements['root']) decode_parameters(e.elements['parameters']) e.elements.each('parameter') {|p| decode_parameter(p)} end def self.decode_custom_levels(e) return Logger.root if e.nil? or e.text.nil? begin custom_levels *Log4rTools.comma_split(e.text) rescue TypeError => te raise ConfigError, te.message, caller[1..-4] end end def self.global_config(e) return if e.nil? globlev = e.value_of 'level' return if globlev.nil? lev = LNAMES.index(globlev) # find value in LNAMES Log4rTools.validate_level(lev, 4) # choke on bad level Logger.global.level = lev end def self.decode_parameters(e) e.elements.each{|p| @@params[p.name] = p.text} unless e.nil? end def self.decode_parameter(e) @@params[e.value_of('name')] = e.value_of 'value' end def self.decode_outputter(e) # fields name = e.value_of 'name' type = e.value_of 'type' level = e.value_of 'level' only_at = e.value_of 'only_at' # validation raise ConfigError, "Outputter missing name", caller[1..-3] if name.nil? raise ConfigError, "Outputter missing type", caller[1..-3] if type.nil? Log4rTools.validate_level(LNAMES.index(level)) unless level.nil? only_levels = [] unless only_at.nil? for lev in Log4rTools.comma_split(only_at) alev = LNAMES.index(lev) Log4rTools.validate_level(alev, 3) only_levels.push alev end end formatter = decode_formatter(e.elements['formatter']) # build the eval string buff = "Outputter[name] = #{type}.new name" buff += ",:level=>#{LNAMES.index(level)}" unless level.nil? buff += ",:formatter=>formatter" unless formatter.nil? params = decode_hash_params(e) buff += "," + params.join(',') if params.size > 0 begin eval buff rescue Exception => ae raise ConfigError, "Problem creating outputter: #{ae.message}", caller[1..-3] end Outputter[name].only_at *only_levels if only_levels.size > 0 Outputter[name] end def self.decode_formatter(e) return nil if e.nil? type = e.value_of 'type' raise ConfigError, "Formatter missing type", caller[1..-4] if type.nil? buff = "#{type}.new " + decode_hash_params(e).join(',') begin return eval(buff) rescue Exception => ae raise ConfigError, "Problem creating outputter: #{ae.message}", caller[1..-4] end end ExcludeParams = %w{formatter level name type} # Does the fancy parameter to hash argument transformation def self.decode_hash_params(e) buff = [] e.attributes.each_attribute {|p| next if ExcludeParams.include? p.name buff << ":" + p.name + "=>" + paramsub(p.value) } e.elements.each {|p| next if ExcludeParams.include? p.name buff << ":" + p.name + "=>" + paramsub(p.text) } buff end # Substitues any #{foo} in the XML with Parameter['foo'] def self.paramsub(str) return nil if str.nil? @@params.each {|param, value| str.sub! '#{'+param+'}', value} "'" + str + "'" end def self.decode_logger(e) l = Logger.new e.value_of('name') decode_logger_common(l, e) end def self.decode_logserver(e) return unless HAVE_REXML name = e.value_of 'name' uri = e.value_of 'uri' l = LogServer.new name, uri decode_logger_common(l, e) end def self.decode_logger_common(l, e) level = e.value_of 'level' additive = e.value_of 'additive' trace = e.value_of 'trace' l.level = LNAMES.index(level) unless level.nil? l.additive = additive unless additive.nil? l.trace = trace unless trace.nil? # and now for outputters outs = e.value_of 'outputters' Log4rTools.comma_split(outs).each {|n| l.add n.strip} unless outs.nil? e.elements.each('outputter') {|e| name = (e.value_of 'name' or e.text) l.add Outputter[name] } end end end
class AddUniqueDateCfsDirectoryIndexToAmazonBackups < ActiveRecord::Migration def change remove_index :amazon_backups, :cfs_directory_id add_index :amazon_backups, [:cfs_directory_id, :date], unique: true end end
# frozen_string_literal: true class CreateStudentLessonDetails < ActiveRecord::Migration[5.2] def change create_view :student_lesson_details end end
class ContactGroup < ActiveRecord::Base attr_accessible :description, :title has_many :location_contact_groups has_many :users, :through => :location_contact_groups def to_element return GContacts::Element.new({ "category" => { "@term" => "group" }, "title" => "#{self.title}", "gd:extendedProperty" => { "@name" => "description", "@value" => "#{self.description}", } }) end def new_group?(location_owner_id) ContactGroup.joins(:location_contact_groups).where('contact_groups.id = ? AND location_contact_groups.location_owner_id = ?', self.id, location_owner_id).empty? end def get_gg_contact_group(location_owner_id) return LocationContactGroup.find_by_location_owner_id_and_contact_group_id(location_owner_id, self.id) end end
class Proposal < ApplicationRecord has_many :proposal_items, dependent: :destroy belongs_to( :customer, class_name: 'User', foreign_key: :customer_id, inverse_of: :proposals_as_customer ) belongs_to( :artist, class_name: 'User', foreign_key: :artist_id, inverse_of: :proposals_as_artist ) validates :status, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 3 } # STATUSES # 1 - PENDING # 2 - SUBMITTED # 3 - ACCEPTED def pending? status == 1 end def submitted? status == 2 end def accepted? status == 3 end end
class AccountantsController < ApplicationController skip_before_action :authenticate_user!, only: [:index, :show, :send_email] before_action :find_accountant, only: [:send_email, :show] def index # Load all accountants @accountants = policy_scope(Accountant).paginate(page: params[:page], per_page: 10) if params[:accountant] # Filter by service if params[:accountant][:services].reject(&:blank?).any? to_search = params[:accountant][:services].reject(&:blank?).map(&:to_i) base_sql = "SELECT id FROM \"accountants\" WHERE EXISTS (SELECT \"accountant_services\".* FROM \"accountant_services\" WHERE (accountants.id = accountant_services.accountant_id AND service_id = #{to_search.first}))" to_search[1..-1].each do |id| add_serv = " AND EXISTS (SELECT \"accountant_services\".* FROM \"accountant_services\" WHERE (accountants.id = accountant_services.accountant_id AND service_id = #{id}))" base_sql += add_serv end results = Accountant.find_by_sql(base_sql) @accountants = @accountants.where(id: results.map(&:id)).paginate(page: params[:page], per_page: 10) end # Filter by industry if params[:accountant][:industries].reject(&:blank?).any? to_search = params[:accountant][:industries].reject(&:blank?).map(&:to_i) base_sql = "SELECT id FROM \"accountants\" WHERE EXISTS (SELECT \"accountant_industries\".* FROM \"accountant_industries\" WHERE (accountants.id = accountant_industries.accountant_id AND industry_id = #{to_search.first}))" to_search[1..-1].each do |id| add_serv = " AND EXISTS (SELECT \"accountant_industries\".* FROM \"accountant_industries\" WHERE (accountants.id = accountant_industries.accountant_id AND industry_id = #{id}))" base_sql += add_serv end results = Accountant.find_by_sql(base_sql) @accountants = @accountants.where(id: results.map(&:id)).paginate(page: params[:page], per_page: 10) end end # filter by unless params[:search].nil? @accountants = @accountants.near(params[:search], 50, order: 'distance') unless params[:search].empty? end end def show @show_button = true cnt = 0 if user_signed_in? @open_enquiries = current_user.enquiries @open_enquiries_no_quote = [] @open_enquiries.each do |e| @open_enquiries_no_quote << e unless e.quotes.any? { |quote| quote.accountant == @accountant } end current_user.enquiries.each do |enquiry| enquiry.quotes.each do |quote| if quote.accountant_id == @accountant.id cnt += 1 end @show_button = false if cnt == current_user.enquiries.count end end else @open_enquiries = [] @open_enquiries_no_quote = [] end end def send_email @body = params[:body] @email_from = current_user.email @subject = params[:subject] AccountantMailer.contact(@body, @email_from, @subject, @accountant.email).deliver_now end private def find_accountant @accountant = Accountant.find(params[:id] || params[:accountant_id]) authorize @accountant end end
require 'prometheus/client' require 'prometheus/client/push' require 'solr_ead' require 'fileutils' ## # Ead Indexer # # This class will index a file or directory into a Solr index configured via blacklight.yml # It essentially wraps the functionality of SolrEad::Indexer with some customizations # mainly the ability to index directories and reindex changed files from a Git diff. # # The #index function takes in a file or directory and calls update on all the valid .xml files it finds. # The #reindex_changed_since_last_commit function finds all the files changed since the previous commit and updates, adds or deletes accordingly. # The #reindex_changed_since_yesterday function finds all the files changed since yesterday and updates, adds or deletes accordingly. # The #reindex_changed_since_last_week function finds all the files changed since last week and updates, adds or deletes accordingly. # The .delete_all convenience method wraps Blacklight.default_index.connection to easily clear the index class EadIndexer::Indexer def self.delete_all Blacklight.default_index.connection.tap do |solr| solr.delete_by_query("*:*") solr.commit end end attr_accessor :indexer, :data_path, :prom_metrics def initialize(data_path="findingaids_eads") @data_path = data_path @indexer = SolrEad::Indexer.new(document: EadIndexer.configuration.document_class, component: EadIndexer.configuration.component_class) @prom_metrics = init_prom_metrics('git-trigger') end def index(file) if file.blank? raise ArgumentError.new("Expecting #{file} to be a file or directory") end unless File.directory?(file) update(file) else updated_files = [] Dir.glob(File.join(file,"*")).each do |dir_file| updated_files << update(dir_file) end updated_files.all? end end # Reindex files changed only since the last commit def reindex_changed_since_last_commit @prom_metrics = init_prom_metrics('git-trigger') prom_metrics&.register_metrics! begin reindex_changed(commits) ensure prom_metrics&.push_metrics! end end # Reindex all files changed in the last week def reindex_changed_since_last_hour reindex_changed(commits('--since=1.hour')) end # Reindex all files changed in the last day def reindex_changed_since_yesterday @prom_metrics = init_prom_metrics('nightly') begin reindex_changed(commits('--since=1.day')) ensure prom_metrics&.push_metrics! end end # Reindex all files changed in the last week def reindex_changed_since_last_week @prom_metrics = init_prom_metrics('weekly') begin reindex_changed(commits('--since=1.week')) ensure prom_metrics&.push_metrics! end end # Reindex all files changed since x days ago def reindex_changed_since_days_ago(days_ago) @prom_metrics = init_prom_metrics('x-days') # assert that argument can be converted to an integer days = Integer(days_ago) begin reindex_changed(commits("--since=#{days}.day")) ensure prom_metrics&.push_metrics! end end private # Reindex files changed in list of commit SHAs def reindex_changed(last_commits) updated_files = [] changed_files(last_commits).each do |file| status, filename, message = file.split("\t") fullpath = File.join(data_path, filename) updated_files << update_or_delete(status, fullpath, message) # sleep for rate limiting https://docs.websolr.com/article/178-http-429-too-many-requests sleep ENV['FINDINGAIDS_RAKE_INDEX_SLEEP_INTERVAL'].to_i if ENV['FINDINGAIDS_RAKE_INDEX_SLEEP_INTERVAL'] end if updated_files.empty? log.info "No files to index." puts "No files to index." end # Return true is all the files were sucessfully updated # or if there were no files (updated_files.all? || updated_files.empty?) end # TODO: Make time range configurable by instance variable # and cascade through to rake jobs # Get the sha for the time range given # # time_range git option to get set of results based on a date/time range; # default is -1, just the last commit def commits(time_range = '-1') @commits ||= `cd #{data_path} && git log --pretty=format:'%h' #{time_range} && cd ..`.split("\n") end # Get list of files changed since last commit def changed_files(last_commits) changed_files = [] last_commits.each do |commit| files_in_commit = (`cd #{data_path} && git diff-tree --no-commit-id --name-status -r #{commit} && cd ..`).split("\n") commit_message = (`cd #{data_path} && git log --pretty=format:'%s' -1 -c #{commit} && cd ..`).gsub(/(\n+)$/,'') files_in_commit.each do |changed_file| changed_files << [changed_file, commit_message].join("\t") end end changed_files.flatten end # Update or delete depending on git status def update_or_delete(status, file, message) eadid = get_eadid_from_message(file, message) # Only reindex for XML files if File.exist?(file) update(file) # Status == D means the file was deleted elsif status.eql? "D" delete(file, eadid) end end def get_eadid_from_message(file, message) # Strip out initial folder name to match filename in commit message file_without_data_path = file.gsub(/#{data_path}(\/)?/,'') eadid_matches = message.match(/#{file_without_data_path} EADID='(.+?)'/) eadid_matches.captures.first unless eadid_matches.nil? end # Wrapper method for SolrEad::Indexer#update(file) # => @file filename of EAD def update(file) if file.blank? raise ArgumentError.new("Expecting #{file} to be a file or directory") end if /\.xml$/.match(file).present? begin # The document is built around a repository that relies on the folder structure # since it does not exist consistently in the EAD, so we pass in the full path to extract the repos. ENV["EAD"] = file indexer.update(file) record_success("Indexed #{file}.", { action: 'update' }) rescue StandardError => e record_failure("Failed to index #{file}: #{e}.", { action: 'update', ead: file }) raise e end else record_failure("Failed to index #{file}: not an XML file.", { action: 'update', ead: file }) end end # Wrapper method for SolrEad::Indexer#delete # => @id EAD id def delete(file, eadid) if file.blank? raise ArgumentError.new("Expecting #{file} to be a file or directory") end if /\.xml$/.match(file).present? # If eadid was passed in, use it to delete # it not, make a guess based on filename id = (eadid || File.basename(file).split("\.")[0]) begin indexer.delete(id) record_success("Deleted #{file} with id #{id}.", { action: 'delete' }) rescue StandardError => e record_failure("Failed to delete #{file} with id #{id}: #{e}", { action: 'delete', ead: file }) raise e end else record_failure("Failed to delete #{file}: not an XML file.", { action: 'delete', ead: file }) end end # Set FINDINGAIDS_LOG=STDOUT to view logs in standard out def log @log ||= (ENV['FINDINGAIDS_LOG']) ? Logger.new(ENV['FINDINGAIDS_LOG'].constantize) : Rails.logger end def record_success(msg, labels={}) metric_labels = prom_metrics&.default_labels&.merge(labels) puts "#{msg}" log.info "#{msg}." prom_metrics&.success_counter&.increment(labels: metric_labels) true end def record_failure(msg, labels={}) metric_labels = prom_metrics&.default_labels&.merge(labels) puts "#{msg}" log.info "#{msg}." prom_metrics&.failure_counter&.increment(labels: metric_labels) false end def init_prom_metrics(cronjob) EadIndexer::PromMetrics.new('specialcollections', cronjob) if ENV['PROM_PUSHGATEWAY_URL'] end end
# Copyright (C) 2011-2014 Tanaka Akira <akr@fsij.org> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Tb::Cmd.subcommands << 'to-json' def (Tb::Cmd).op_to_json op = OptionParser.new op.banner = "Usage: tb to-json [OPTS] [TABLE]\n" + "Convert a table to JSON (JavaScript Object Notation)." define_common_option(op, "hNo", "--no-pager") op end def (Tb::Cmd).main_to_json(argv) require 'json' op_to_json.parse!(argv) exit_if_help('to-json') argv = ['-'] if argv.empty? with_output {|out| out.print "[" sep = nil argv.each {|filename| sep = ",\n\n" if sep tablereader_open(filename) {|tblreader| tblreader.each {|pairs| out.print sep if sep out.print JSON.pretty_generate(pairs) sep = ",\n" } } } out.puts "]" } end
require 'bundler/setup' require 'class_loader' autoload_path './lib' class Queue def self.create type, queue_name case type when :sqs SQSQueueImpl.new(queue_name) when :resque ResqueImpl.new(queue_name) else raise "Bad type: #{type}" end end end # class ResqueImpl < Queue # # def initialize(queue_name) # @queue = queue_name # end # # def push # puts "push!" # end # # end
# frozen-string-literal: true # # The connection_expiration extension modifies a database's # connection pool to validate that connections checked out # from the pool are not expired, before yielding them for # use. If it detects an expired connection, it removes it # from the pool and tries the next available connection, # creating a new connection if no available connection is # unexpired. Example of use: # # DB.extension(:connection_expiration) # # The default connection timeout is 14400 seconds (4 hours). # To override it: # # DB.pool.connection_expiration_timeout = 3600 # 1 hour # # Note that this extension does not work with the single # threaded and sharded single threaded connection pools. # As the only reason to use the single threaded # pools is for speed, and this extension makes the connection # pool slower, there's not much point in modifying this # extension to work with the single threaded pools. The # non-single threaded pools work fine even in single threaded # code, so if you are currently using a single threaded pool # and want to use this extension, switch to using another # pool. # # Related module: Sequel::ConnectionExpiration # module Sequel module ConnectionExpiration class Retry < Error; end Sequel::Deprecation.deprecate_constant(self, :Retry) # The number of seconds that need to pass since # connection creation before expiring a connection. # Defaults to 14400 seconds (4 hours). attr_accessor :connection_expiration_timeout # The maximum number of seconds that will be added as a random delay to the expiration timeout # Defaults to 0 seconds (no random delay). attr_accessor :connection_expiration_random_delay # Initialize the data structures used by this extension. def self.extended(pool) case pool.pool_type when :single, :sharded_single raise Error, "cannot load connection_expiration extension if using single or sharded_single connection pool" end pool.instance_exec do sync do @connection_expiration_timestamps ||= {} @connection_expiration_timeout ||= 14400 @connection_expiration_random_delay ||= 0 end end end private # Clean up expiration timestamps during disconnect. def disconnect_connection(conn) sync{@connection_expiration_timestamps.delete(conn)} super end # Record the time the connection was created. def make_new(*) conn = super @connection_expiration_timestamps[conn] = [Sequel.start_timer, @connection_expiration_timeout + (rand * @connection_expiration_random_delay)].freeze conn end # When acquiring a connection, check if the connection is expired. # If it is expired, disconnect the connection, and retry with a new # connection. def acquire(*a) conn = nil 1.times do if (conn = super) && (cet = sync{@connection_expiration_timestamps[conn]}) && Sequel.elapsed_seconds_since(cet[0]) > cet[1] case pool_type when :sharded_threaded, :sharded_timed_queue sync{@allocated[a.last].delete(Sequel.current)} else sync{@allocated.delete(Sequel.current)} end disconnect_connection(conn) redo end end conn end end Database.register_extension(:connection_expiration){|db| db.pool.extend(ConnectionExpiration)} end
class Tmi < ApplicationRecord belongs_to :author, class_name: 'User' has_many :stars end
require 'openssl' require_relative '../lib/luhn_validator' require_relative '../helpers/model_helper' # Credit Card class, the basis for humanity class CreditCard < ActiveRecord::Base include ModelHelper, LuhnValidator def number=(params) enc = RbNaCl::SecretBox.new(key) nonce = RbNaCl::Random.random_bytes(enc.nonce_bytes) self.nonce_64 = enc64(nonce) self.encrypted_number = enc64(enc.encrypt(nonce, "#{params}")) end def number dec = RbNaCl::SecretBox.new(key) dec.decrypt(dec64(nonce_64), dec64(encrypted_number)) end def number_obfuscate(num) (5..num.length).to_a.each { |x| num[-x] = '*' } if num.length > 4 num end # returns all card information as single string def to_s { number: number_obfuscate(number), owner: owner, expiration_date: expiration_date, credit_network: credit_network }.to_json end # return a new CreditCard object given a serialized (JSON) representation def self.from_s(card_s) new(*(JSON.parse(card_s).values)) end # return a cryptographically secure hash def hash_secure sha256 = OpenSSL::Digest::SHA256.new enc64(sha256.digest) end end
class Map @@default_width = 80 @@default_height = 24 def initialize(width=nil, height=nil) @width = width || @@default_width @height = height || @@default_height end def width @width end def height @height end def fill(value) map = Array.new (0..@width-1).each do |x| map << Array.new (0..@height-1).each do map[x] << value end end map end end
class Api::V1::TransactionsController < ApiController before_action :authenticate_consumer_from_token!, only: [:new, :charge] before_action :authenticate_consumer!, only: [:new, :charge] before_action :validate_payment_request, only: [:charge] rescue_from Pingpp::APIConnectionError, with: :handle_ping_xx_connection_error def new if params[:sn].nil? || (order = Order.find_by_sn(params[:sn])).try(:consumer) != current_consumer || order.state == '已支付' @error = 'Invalid payment request' return render :error end if params[:channel].nil? @error = 'Channel not provided' return render :error end order = Order.find_by_sn(params[:sn]) ip = request.remote_ip @charge = PingPPService.create_payment(order, ip, params[:channel], params[:success_url]) end def charge @charge = PingPPService.create_payment_for_multiple_orders(params[:sns], '192.168.1.1', params[:channel], params[:success_url]) unless @charge @error = 'Invalid payment request' return render :error end render :new end def create order_group_name = 'ORDERGROUP' if params['data']['object']['order_no'].start_with?(order_group_name) order_no = params['data']['object']['order_no'] order_group_id = order_no.slice(order_group_name.length, order_no.length - order_group_name.length) orders = OrderGroup.find(order_group_id).try(:orders) || [] raise Exception if orders.select {|order| order.consumer != current_consumer}.present? || orders.select {|order| order.paid?}.present? orders.each {|order| order.update_attributes(state: '已支付')} else order = Order.find_by_sn(params['data']['object']['order_no']) raise Exception if order.paid? order.update_attributes(state: '已支付') end Transaction.create!(pingpp_id: params['id'], order_sn: params['data']['object']['order_no'], status: params['data']['object']['paid'], transaction_type: params['type'], amount: params['data']['object']['amount']) return render json: {status: 200} rescue Exception render json: {status: 500} end def validate_payment_request if params[:sns].nil? || params[:channel].nil? @error = 'Invalid parameters' return render :error end orders = params[:sns].map {|sn| Order.find_by_sn(sn)} if orders.select {|order| order.consumer != current_consumer}.present? || orders.select {|order| order.paid?}.present? @error = 'Invalid payment request' return render :error end end private def handle_ping_xx_connection_error @error = '连接超时' return render :error end end
class ApplicationController < ActionController::Base include Pundit protect_from_forgery # skip_before_action :verify_authenticity_token, if: -> { controller_name == 'sessions' && action_name == 'create' } before_action :set_paper_trail_whodunnit before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters permits = [:sign_up, :account_update] keys = [:email, :name, :birthday] permits.each do |p| devise_parameter_sanitizer.permit(p, keys: keys) end end end
# frozen_string_literal: true module GoogleDriveContent def self.included(clas) clas.after_create_commit { |record| GoogleDriveUploadJob.perform_later(record.id) } end def content_data_io GoogleDriveUploadJob.perform_later(id) unless google_drive_reference content_data_db_io || google_drive_io || cloudinary_io || self.class.where(id: id).pick(:content_data) end def content_data_db_io StringIO.new(content_data) if content_loaded? end def google_drive_file return unless google_drive_reference logger.info "get google drive file: #{id} #{google_drive_reference}" GoogleDriveService.new.get_file(google_drive_reference) end def google_drive_io return unless google_drive_reference logger.info "get google drive io: #{id} #{google_drive_reference}" GoogleDriveService.new.get_file_io(google_drive_reference) end def cloudinary_io return unless cloudinary_identifier Cloudinary::Downloader .download(cloudinary_identifier, type: 'upload', resource_type: video? ? 'video' : 'image') end def cloudinary_file return unless cloudinary_identifier Cloudinary::Api .resource(cloudinary_identifier, type: 'upload', resource_type: video? ? 'video' : 'image') end def move_to_google_drive! loaded_content, google_reference = self.class.where(id: id).pick(:content_data, :google_drive_reference) if loaded_content.blank? if google_reference self.google_drive_reference = google_reference return end GoogleDriveUploadJob.perform_now(id) return end upload_to_google_drive(loaded_content) unless Rails.env.test? loaded_content end def upload_to_google_drive(loaded_content) return if Rails.env.test? logger.info "Store image in Google Drive: #{id}, #{name}" file = GoogleDriveService.new .store_file(self.class.name.pluralize.underscore, id, loaded_content, content_type) update! google_drive_reference: file.id, content_data: nil, md5_checksum: file.md5_checksum end private def content_loaded? attribute_present?(:content_data) && content_data.present? end end
class PaymentsController < ApplicationController before_action :authenticate_user! before_action :set_order, :only => [:new, :execute] def new @payment = PayPal::SDK::REST::Payment.new payment_params if @payment.create @redirect_url = @payment.links.find{|v| v.method == "REDIRECT" }.href @payment_local = Payment.create({ :payment_id => @payment.id, :order_id => @order.id, :total => @payment.transactions.last.amount.total }) @order.update({ :total => params[:total][:val] }) redirect_to @redirect_url and return else logger.error @payment.error.inspect end redirect_to root_path end def execute payment = PayPal::SDK::REST::Payment.find params[:paymentId] if payment.execute(:payer_id => params[:PayerID]) @payment = Payment.find_by :payment_id => payment.id @payment.update(:complited => true) if @order.order_valid? flash[:success] = "Ordr validation complite" OrderMailer.order_notification(@order).deliver! else flash[:danger] = "Order validation error" OrderMailer.order_fail(@order).deliver! end else payment.error # Error Hash flash[:danger] = "Payment failed" end redirect_to root_path end private def set_order @order = Order.cur_user(current_user.id).active.first end def payment_params { :intent => "sale", :payer => { :payment_method => "paypal" }, :redirect_urls => { :return_url => "http://localhost:3000/payments/execute", :cancel_url => "http://localhost:3000/" }, :description => "This is the payment transaction description." } .merge({ :transactions => [{ :amount => { :total => params[:total][:val], :currency => "USD" } }] }) end end
require 'test_helper' class UserTest < ActiveSupport::TestCase def setup @name = 'Alex' @email = 'azagniotov@gmail.com' @password = '12345' end def teardown User.delete_all end test 'should save new user to DB when all required properties are set' do user = User.new(name: @name, email: @email, password: @password) assert user.save end test 'should not save new user to DB when name is not set' do user = User.new(email: @email, password: @password) assert_not user.save end test 'should not save new user to DB when email is not set' do user = User.new(name: @name, password: @password) assert_not user.save end test 'should not save new user to DB when password is not set' do user = User.new(name: @name, email: @email) assert_not user.save end test 'should authenticate user when email & password are correct' do user = User.new(name: @name, email: @email, password: @password) assert user.save auth_token = User.authenticate(@email, @password) assert_equal(user.auth_token, auth_token) end test 'should not authenticate user when email is wrong' do user = User.new(name: @name, email: @email, password: @password) assert user.save auth_token = User.authenticate('wrongov@gmail.com', @password) assert_nil auth_token end test 'should not authenticate user when password is wrong' do user = User.new(name: @name, email: @email, password: @password) assert user.save auth_token = User.authenticate(@email, '123') assert_nil auth_token end end
require "image_processing/mini_magick" class ImageUploader < Shrine ALLOWED_TYPES = %w[image/jpeg image/png image/webp image/bmp image/x-icon image/tiff] MAX_SIZE = 50*1024*1024 # 50 MB MAX_DIMENSIONS = [5000, 5000] # 5000x5000 plugin :validation_helpers # File validations (requires `validation_helpers` plugin) Attacher.validate do validate_size 0..MAX_SIZE validate_mime_type ALLOWED_TYPES end Attacher.derivatives do |original| magick = ImageProcessing::MiniMagick.source(original) { large: magick.resize_to_limit!(900, 400), medium: magick.resize_to_limit!(900, 350), small: magick.resize_to_limit!(700, 400), thumb: magick.resize_to_limit!(100, 100) } end end
class DashboardController < ApplicationController def show @github = GithubService.new(current_user) @user_info = UserInfo.new(@github.user_info) @github.starred_info @github.repos_info @github.activity_info end end
FactoryBot.define do factory :order_address do post_number { '123-4567' } place_id { 27 } city { '大阪市' } street { '中央区' } building { 'マンション' } tell_number { '09012345678' } token { 'aaa' } user_id { 1 } item_id { 1 } end end
describe RequirementsService::Commands::ResetRequirements do include_context 'stubbed_network' subject { described_class.new(context_module: context_module) } let(:subject_2) { described_class.new(context_module: context_module, exam: true) } let(:course) { double('course', id: 1) } let(:context_module) do double( 'context module', completion_requirements: completion_requirements, course: course, update_column: nil, touch: nil, ) end let(:completion_requirements) do [ {:id=>53, :type=>"must_view"}, {:id=>56, :type=>"min_score", :min_score => 70}, unit_exam ] end let(:unit_exam) do {:id=>58, :type=>"min_score", :min_score => 75} end before do ContentTag.create(id: 56) allow(subject).to receive(:unit_exam?).and_call_original allow(subject).to receive(:unit_exam?).with(unit_exam).and_return(true) end describe "#call" do it "skips the unit exam" do subject.call req_scores = context_module.completion_requirements.select { |req| req[:min_score] } expect(req_scores.size).to eq(1) expect(req_scores.first[:min_score]).to eq(75) end it "converts to a must_submit" do subject.call expect(context_module.completion_requirements[1][:type]).to eq("must_submit") end context "DiscussionTopic" do before do ContentTag.find(56).update(content_type: "DiscussionTopic") end it "Turns to a must contribute when content_type is DiscussionTopic" do subject.call expect(context_module.completion_requirements[1][:type]).to eq("must_contribute") end end context "Unit Exam" do before do content_tag = ContentTag.create(id: 58) allow(RequirementsService).to receive(:is_unit_exam?).and_call_original allow(RequirementsService).to receive(:is_unit_exam?).with(content_tag: content_tag).and_return(true) end it "converts the unit exam" do subject_2.call expect(context_module.completion_requirements[2][:type]).to eq("must_submit") end end end end
# encoding: utf-8 module ValidatiousOnRails module Helpers def self.included(base) base.class_eval do extend ClassMethods end end def attach_validator_for(object_name, method, options = {}) options = ::ValidatiousOnRails::ModelValidations.options_for(object_name, method, options, @content_for_validatious) custom_js = options.delete(:js) content_for :validatious, custom_js << "\n" if custom_js.present? options end # Helper for the layout to host the custom Validatious-validators for forms rendered. # This will only show up if the current view contains one - or more - forms that # are triggered to be validated with Validatous (i.e. ValidatiousOnRails that is). # def attached_validators if @content_for_validatious.present? javascript_tag(@content_for_validatious, :id => 'custom_validators') end end alias :javascript_for_validatious :attached_validators def self.extract_args!(*args) tail = [] tail.unshift(args.pop) until args.blank? || args.last.is_a?(::Hash) unless args.last.is_a?(::Hash) args = tail tail = [] end return args, tail end module ClassMethods def define_with_validatious_support(field_type) begin define_method :"#{field_type}_with_validation" do |*args| args, tail = ::ValidatiousOnRails::Helpers.extract_args!(*args) options = self.attach_validator_for(args.first, args.second, args.extract_options!) self.send :"#{field_type}_without_validation", *((args << options) + tail) end alias_method_chain field_type, :validation rescue # Rails version compability. Note: :respond_to? don't seems to work... end end end end end ::ActionController::Base.helper ::ValidatiousOnRails::Helpers
@authors = { jorge_bejar: { name: 'Jorge Bejar', email: 'jorge@wyeworks.com ', twitter_handle: 'jmbejar', github_handle: 'jmbejar', image: 'jorge-bejar.jpg', description: 'Software Engineer, Rubist, Certified Scrum Master. Working at @wyeworks' }, jose_ignacio_costa: { name: 'José Costa', email: 'jose@wyeworks.com', twitter_handle: 'joseicosta', github_handle: 'joseicosta', image: 'jose-ignacio-costa.jpg', description: 'Cofounder & CEO at WyeWorks. Fitness aficionado. Home Barista wannabe.' }, mario_saul: { name: 'Mario Saul', email: 'mario@wyeworks.com', twitter_handle: 'mario_saul', github_handle: 'mariiio', image: 'mario-saul.jpg', description: 'Software developer at WyeWorks.' }, rodrigo_ponce_de_leon: { name: 'Rodrigo Ponce de León', email: 'rodrigo@wyeworks.com', twitter_handle: 'rponce_89', github_handle: 'rodrigopdl', image: 'rodrigo-pdl.jpg', description: 'Ruby on Rails developer at WyeWorks. Beatlemaniac. Guitar freak.' }, santiago_pastorino: { name: 'Santiago Pastorino', email: 'santiago@wyeworks.com', twitter_handle: 'spastorino', github_handle: 'spastorino', image: 'santiago-pastorino.jpg', description: 'WyeWorks Co-Founder & CTO, Ruby on Rails Core Team Member' }, sebastian_martinez: { name: 'Sebastián Martínez', email: 'sebastian@wyeworks.com', twitter_handle: 'smartinez87', github_handle: 'smartinez87', image: 'sebastian-martinez.jpg', description: 'VP of Engineering at WyeWorks. Love to travel the world and experience all the different foods and spices in it. Lifestyle medicine advocate.' }, federico_kauffman: { name: 'Federico Kauffman', email: 'federico@wyeworks.com', twitter_handle: 'fedekauffman', github_handle: 'fedekau', image: 'federico-kauffman.jpg', description: 'Software Engineer at WyeWorks. Currently working with Javascript and Ruby. Learnaholic.' }, undefined_author: { name: '', email: '', twitter_handle: '', github_handle: '', image: '', description: '' }, wyeworks: { name: 'WyeWorks', email: 'webmaster@wyeworks.com', twitter_handle: 'wyeworks', github_handle: 'wyeworks', image: 'wyeworks.jpg', description: '' } }
namespace :load do task :defaults do set :monit_bin, '/usr/bin/monit' set :sneakers_monit_default_hooks, true set :sneakers_monit_conf_dir, '/etc/monit/conf.d' set :sneakers_monit_use_sudo, true set :sneakers_monit_templates_path, 'config/deploy/templates' end end namespace :deploy do before :starting, :check_sneakers_monit_hooks do if fetch(:sneakers_default_hooks) && fetch(:sneakers_monit_default_hooks) invoke 'sneakers:monit:add_default_hooks' end end end namespace :sneakers do namespace :monit do task :add_default_hooks do before 'deploy:updating', 'sneakers:monit:unmonitor' after 'deploy:published', 'sneakers:monit:monitor' end desc 'Config Sneakers monit-service' task :config do on roles(fetch(:sneakers_roles)) do |role| @role = role upload_sneakers_template 'sneakers_monit', "#{fetch(:tmp_dir)}/monit.conf", @role mv_command = "mv #{fetch(:tmp_dir)}/monit.conf #{fetch(:sneakers_monit_conf_dir)}/#{sneakers_monit_service_name}.conf" sudo_if_needed mv_command sudo_if_needed "#{fetch(:monit_bin)} reload" end end desc 'Monitor Sneakers monit-service' task :monitor do on roles(fetch(:sneakers_roles)) do begin sudo_if_needed "#{fetch(:monit_bin)} monitor #{sneakers_monit_service_name}" rescue invoke 'sneakers:monit:config' sudo_if_needed "#{fetch(:monit_bin)} monitor #{sneakers_monit_service_name}" end end end desc 'Unmonitor Sneakers monit-service' task :unmonitor do on roles(fetch(:sneakers_roles)) do begin sudo_if_needed "#{fetch(:monit_bin)} unmonitor #{sneakers_monit_service_name}" rescue # no worries here end end end desc 'Start Sneakers monit-service' task :start do on roles(fetch(:sneakers_roles)) do sudo_if_needed "#{fetch(:monit_bin)} start #{sneakers_monit_service_name}" end end desc 'Stop Sneakers monit-service' task :stop do on roles(fetch(:sneakers_roles)) do sudo_if_needed "#{fetch(:monit_bin)} stop #{sneakers_monit_service_name}" end end desc 'Restart Sneakers monit-service' task :restart do on roles(fetch(:sneakers_roles)) do sudo_if_needed "#{fetch(:monit_bin)} restart #{sneakers_monit_service_name}" end end def sneakers_monit_service_name fetch(:sneakers_monit_service_name, "sneakers_#{fetch(:application)}_#{fetch(:sneakers_env)}") end def sudo_if_needed(command) fetch(:sneakers_monit_use_sudo) ? sudo(command) : execute(command) end def upload_sneakers_template(from, to, role) template = sneakers_template(from, role) upload!(StringIO.new(ERB.new(template).result(binding)), to) end def sneakers_template(name, role) local_template_directory = fetch(:sneakers_monit_templates_path) search_paths = [ "#{name}-#{role.hostname}-#{fetch(:stage)}.erb", "#{name}-#{role.hostname}.erb", "#{name}-#{fetch(:stage)}.erb", "#{name}.erb" ].map { |filename| File.join(local_template_directory, filename) } global_search_path = File.expand_path( File.join(*%w[.. .. .. generators capistrano sneakers monit templates], "#{name}.conf.erb"), __FILE__ ) search_paths << global_search_path template_path = search_paths.detect { |path| File.file?(path) } File.read(template_path) end end end
class Public::VolumesController < ApplicationController layout "public" before_action :authenticate_user! # GET /public/volumes def index @volumes = Volume.order(:title).page(params[:page]) end # GET /public/volumes/1 # TODO don't use multiple controller actions across different Models def show #redirect_to volumes_path(@volumes) @volume = Volume.find(params[:id]) @citations = VolumeCitation.where(:volume_id => @volume.id) @referenced_texts = Text.where(:volume_id => @volume.id) end end
require "manageiq_helper" RSpec.describe "Relay specification compliance (integration)" do let(:token_service) { Api::UserTokenService.new(:base => {:module => "api", :name => "API"}) } let(:token) { token_service.generate_token(user.userid, "api") } describe "Global Object Identification" do context "given an object with an ID" do as_user do before do FactoryGirl.create(:vm, :name => "Sooper Special VM") post( "/graphql", :headers => { "HTTP_X_AUTH_TOKEN" => token }, :params => { :query => "{ vms { edges { node { id name } } } }" }, :as => :json ) end example "the same object can be requeried by its node ID" do vm_id = response.parsed_body.dig('data', 'vms', 'edges').first.dig('node', 'id') query = <<~QUERY { node(id: "#{vm_id}") { id ... on Vm { name } } } QUERY post( "/graphql", :headers => { "HTTP_X_AUTH_TOKEN" => token }, :params => { :query => query }, :as => :json ) expected = { "data" => { "node" => { "id" => vm_id, "name" => "Sooper Special VM" } } } expect(response.parsed_body).to eq(expected) end end end end end
require "test_helper" class DinosaurBreedsControllerTest < ActionDispatch::IntegrationTest setup do @dinosaur_breed = dinosaur_breeds(:one) end test "should get index" do get dinosaur_breeds_url assert_response :success end test "should get new" do get new_dinosaur_breed_url assert_response :success end test "should create dinosaur_breed" do assert_difference('DinosaurBreed.count') do post dinosaur_breeds_url, params: { dinosaur_breed: { name: @dinosaur_breed.name } } end assert_redirected_to dinosaur_breed_url(DinosaurBreed.last) end test "should show dinosaur_breed" do get dinosaur_breed_url(@dinosaur_breed) assert_response :success end test "should get edit" do get edit_dinosaur_breed_url(@dinosaur_breed) assert_response :success end test "should update dinosaur_breed" do patch dinosaur_breed_url(@dinosaur_breed), params: { dinosaur_breed: { name: @dinosaur_breed.name } } assert_redirected_to dinosaur_breed_url(@dinosaur_breed) end test "should destroy dinosaur_breed" do assert_difference('DinosaurBreed.count', -1) do delete dinosaur_breed_url(@dinosaur_breed) end assert_redirected_to dinosaur_breeds_url end end
class Dummy::Module::Target::Platform < Metasploit::Model::Base include Metasploit::Model::Module::Target::Platform # # Associations # # @!attribute [rw] module_target # The module target that supports {#platform}. # # @return [Dummy::Module::Target] attr_accessor :module_target # @!attribute [rw] platform # The platform supported by the {#module_target}. # # @return [Dummy::Platform] attr_accessor :platform end
module Bitcourier module Protocol module Message class PeerInfo < Base ID = 0x3 attr_accessor :ip, :port, :last_seen_at def payload [*ip_array, port.to_i, last_seen_at.to_i].pack('CCCCSL') end def extract(bytes) data = bytes.unpack('CCCCSL') self.ip = data[0..3].join('.') self.port = data[4].to_i self.last_seen_at = Time.at(data[5].to_i).utc self end private def ip_array ip.split('.').map(&:to_i) end end end end end
# frozen_string_literal: true # Generator to fake data class Fake def self.user firstname = Faker::Name.first_name lastname = Faker::Name.last_name prepare_user_hash firstname, lastname end # rubocop:disable Metrics/MethodLength # rubocop:disable Metrics/AbcSize def self.create_fake_user_table(database) database.create_table :fake_user do primary_key :id String :firstname String :lastname String :login String :email String :telephone String :company String :street String :postcode String :city String :full_address String :vat_id String :ip String :quote String :website String :iban String :regon String :pesel String :json end end def self.prepare_user_hash(firstname, lastname) { firstname: firstname, lastname: lastname, email: Faker::Internet.email("#{firstname} #{lastname}"), login: Faker::Internet.user_name("#{firstname} #{lastname}", %w[. _ -]), telephone: Faker::PhoneNumber.cell_phone, company: Faker::Company.name, street: Faker::Address.street_name, postcode: Faker::Address.postcode, city: Faker::Address.city, full_address: Faker::Address.full_address, vat_id: Faker::Company.swedish_organisation_number, ip: Faker::Internet.private_ip_v4_address, quote: Faker::StarWars.quote, website: Faker::Internet.domain_name, iban: Faker::Bank.iban, regon: generate_regon, pesel: Fake::Pesel.generate, json: '{}' } end # rubocop:enable Metrics/AbcSize # rubocop:enable Metrics/MethodLength def self.generate_regon regon = district_number 6.times do regon += Random.rand(0..9).to_s end sum = sum_for_wigths(regon, regon_weight) validation_mumber = (sum % 11 if sum % 11 != 10) || 0 regon + validation_mumber.to_s end def self.regon_weight [8, 9, 2, 3, 4, 5, 6, 7] end def self.sum_for_wigths(numbers, weight_array) sum = 0 numbers[0, numbers.length - 1].split('').each_with_index do |number, index| sum += number.to_i * weight_array[index] end sum end def self.district_number %w[01 03 47 49 91 93 95 97].sample end end
class Public::ShippingAddressesController < Public::Base before_action :authenticate_end_user! def index @shipping_addresses = ShippingAddress.where(end_user_id: current_end_user.id) @shipping_address = ShippingAddress.new end def create @shipping_address = ShippingAddress.new(shipping_address_params) @shipping_address.end_user_id = current_end_user.id if @shipping_address.save redirect_to shipping_addresses_path else @shipping_addresses = ShippingAddress.where(end_user_id: current_end_user.id) render 'index' end end def edit @shipping_address = ShippingAddress.find(params[:id]) end def update @shipping_address = ShippingAddress.find(params[:id]) if @shipping_address.update(shipping_address_params) redirect_to shipping_addresses_path else render 'edit' end end def destroy shipping_address = ShippingAddress.find(params[:id]) shipping_address.destroy redirect_to shipping_addresses_path end private def shipping_address_params params.require(:shipping_address).permit(:postal_code, :address, :name) end end
# frozen_string_literal: true RSpec.describe Jsonschema::Generator do subject(:generator) { described_class.call(json) } let(:json) { {}.to_json } describe 'Success' do let(:draft07) { instance_double(described_class::Draft07) } it 'calls draft07 with correct input' do expect(described_class::Draft07) .to receive(:new).with(json).and_return(draft07) expect(draft07).to receive(:call) generator end end end
if File.exist?('/usr/bin/uptrack-uname') Facter.add(:ksplice_kernelrelease) do setcode do Facter::Util::Resolution.exec('/usr/bin/uptrack-uname -r 2>/dev/null') end end Facter.add(:ksplice_kernelversion) do setcode do Facter.value(:ksplice_kernelrelease).split('-')[0] end end Facter.add(:ksplice_kernelmajversion) do setcode do Facter.value(:ksplice_kernelversion).split('.')[0..1].join('.') end end Facter.add(:ksplice_kernel_package_version) do setcode do Facter::Util::Resolution.exec('/usr/bin/uptrack-uname --package-version 2>/dev/null').split[2] end end end
# # 6.4 Assignment # module Shout # def self.yell_angrily(words) # words + "!!!" + " :(" # end # def self.yell_happily(words) # words + "!!!" + " :)" # end # end # # Driver Code # Shout.yell_angrily("Why") # Shout.yell_happily("yay") module Shout def yell_angrily(words) words + "!!!" + " :(" end def yell_happily(words) words + "!!!" + " :)" end end class Children include Shout end class Animals include Shout end # Driver Code child = Children.new child.yell_angrily("I want ice cream") child.yell_happily("I love summer a lot") animal = Animals.new animal.yell_angrily("Stay away from my food") animal.yell_happily("What's for dinner?")
require File.dirname(__FILE__) + '/../test_helper' class LineItemTest < Test::Unit::TestCase fixtures :line_items, :products def setup @rails = products(:rails_book) @cart_item = CartItem.new(@rails) end def test_create_line_item_from_cart_item line_item = LineItem.from_cart_item(@cart_item) assert_equal line_item.quantity, @cart_item.quantity assert_equal line_item.total_price, @cart_item.price assert_equal line_item.product, @cart_item.product end end
require 'rails_helper' xdescribe ItemOptionController do login_user describe '#batch_delete' do it 'deletes the specified menus' do first_item_option = create(:item_option) second_item_option = create(:item_option) expect(first_item_option).to be expect(second_item_option).to be delete :batch_delete, items_to_delete: [first_item_option.id, second_item_option.id] expect{first_item_option.reload}.to raise_error expect{second_item_option.reload}.to raise_error expect(response).to have_http_status(:ok) end end end
#!/usr/bin/env ruby require File.join(File.dirname(__FILE__), '..', 'script', 'vp_script') Dir.chdir RAILS_ROOT options = vp_script do |opts, options| opts.separator "" opts.on(:REQUIRED, "-f", "--file FILE", "Required file") do |f| options[:file] = f end end logger.fatal("No file given...exiting") and exit unless options[:file] logger.info "Parsing log file #{options[:file]}" def persist_profile_page_view(display_id, opts, l) return 0 unless display_id if user = User.find_by_display_id(display_id) return persist_page_view(opts, user, user.id, l) else logger.info "Couldn't find User '#{display_id}'. Full log line:\n#{l}" return 0 end end def persist_review_page_views(permalinks, opts, l) return 0 unless permalinks cnt = 0 permalinks.split.each do |permalink| cnt += persist_review_page_view permalink, opts, l end return cnt end def persist_review_page_view(permalink, opts, l) return 0 unless permalink if review = Review.find_by_permalink(permalink) return persist_page_view(opts, review, review.user_id, l) else logger.info "Couldn't find Review '#{permalink}'. Full log line:\n#{l}" return 0 end end def persist_page_view(opts, owner, owner_user_id, l) rpv = RawPageView.new opts.merge({ :owner => owner, :owner_user_id => owner_user_id }) if rpv.save return 1 else logger.info "Unable to save record #{rpv.inspect}.\nFull log line:\n#{l}" return 0 end end line_cnt = review_cnt = profile_cnt = 0 common_log_regex = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s\S+\s\S+\s\[(\d{1,2}\/\w+\/\d{4}):(.+)\]\s"([A-Z]{3,4})\s(\S+)[^"]*"\s(\d{1,3})\s([\d-]+)\s"([^"]+)"\s"([^"]+)"/ ip_exclusion_regex = /^(208.96.213.130|192.168.1.\d{1,3}|10.241.76.75|10.241.66.178|10.241.76.76)$/ File.open(options[:file]) do |reader| reader = Zlib::GzipReader.new(reader) if options[:file] =~ /\.gz$/ reader.each_line do |l| line_cnt += 1 next unless md = common_log_regex.match(l) next unless md[5] =~ /^\/images\/d.gif/ next unless ['200', '304'].include?(md[6]) next if md[1] =~ ip_exclusion_regex params = Rack::Utils.parse_nested_query md[5].gsub(/^.+\?/, '') opts = { :ip_address => md[1], :viewed_at => Time.parse("#{md[2]} #{md[3]}".gsub('/', ' ')), :session_id => params['s'] } profile_cnt += persist_profile_page_view params['u'], opts, l review_cnt += persist_review_page_views params['r'], opts, l end end logger.info "Completed parsing log file #{options[:file]}" logger.info " Saw #{line_cnt} lines; Saved #{review_cnt} review and #{profile_cnt} profile views"
# frozen_string_literal: true control 'Habitat Service' do describe command('/bin/hab') do it { should exist } end describe user('hab') do it { should exist } end describe group('hab') do it { should exist } end describe systemd_service('habitat') do it { should be_installed } it { should be_enabled } it { should be_running } end describe http('http://0.0.0.0:9631/services') do its('status') { should cmp 200 } end end control 'Test httpd hab service' do describe http('http://0.0.0.0/') do its('status') { should cmp 200 } end end
require 'test_helper' class AccountTest < ActiveSupport::TestCase # AccountTest.1 test "should not save account without information" do account = Account.new assert !account.save end # AccountTest.2 test "should not save account without a name" do account = Account.new(name:"", email:"frida@csu.fullerton.edu", password:"test123", password_confirmation:"test123" ) assert !account.save end # AccountTest.3 test "should not save account without an email" do account = Account.new(name:"frida", email:"", password:"test123", password_confirmation:"test123" ) assert !account.save end # AccountTest.4 test "should not save account with an already existing email" do a = Account.new(name:"frida", email:"frida.k@csu.fullerton.edu", password:"test123", password_confirmation:"test123" ) assert a.save b = Account.new(name:"frida kiriakos", email:"frida.k@csu.fullerton.edu", password:"test123", password_confirmation:"test123" ) assert !b.save end end
require 'rails_helper' RSpec.describe 'タスク投稿', type: :system do before do @user = FactoryBot.create(:user) @category = FactoryBot.build(:category) end context 'タスク投稿ができるとき'do it 'ログインしたユーザーはタスク投稿できる' do # ログインする visit new_user_session_path fill_in 'Email', with: @user.email fill_in 'Password', with: @user.password find('input[name="commit"]').click expect(current_path).to eq root_path # フォームに情報を入力する fill_in 'category[task]', with: @category.task find('input[name="commit"]').click # 投稿完了ページに遷移することを確認する expect(current_path).to eq root_path end end end
# ActiveAdmin.register Address do # menu parent: 'Users' # # config.sort_order = 'name_asc' # permit_params :line1, :line2, :town_city, :county, :country_id, :zip, # :addressible_id, :addressible_type, :created_at, :updated_at # # filter :addressible, as: :select, collection: -> { User.companies } # # index do # column :line1 # column :line2 # column :town_city # column :county # column :country_id # column :zip # column :addressible # column :addressible_type # actions # end # # form do |f| # f.inputs do # f.input :line1 # f.input :line2 # f.input :town_city # f.input :county # f.input :country_id # f.input :zip # # f.has_many :address, allow_destroy: true, new_record: false do |addr_f| # addr_f.input :line1 # addr_f.input :line2 # addr_f.input :town_city # addr_f.input :county # addr_f.input :country # addr_f.input :zip # end # end # # f.actions # end # # end
require 'rails_helper' RSpec.describe Collaborator, type: :model do it 'has a default value of false for cynical' do fred = Collaborator.new(name: 'Fred') expect(fred.cynical).to eq(false) end it 'can become cynical' do fred = Collaborator.new(name: 'Fred') fred.cynical = true jaded_fred = fred.save expect(jaded_fred).to eq(true) end it 'is valid with a name' do fred = Collaborator.new(name: 'Fred') expect(fred).to be_valid end it 'is invalid without a name' do nemo = Collaborator.new(catchphrase: "i am no one") expect(nemo).to_not be_valid end end
require 'carrierwave/orm/activerecord' class Hotel < ActiveRecord::Base include AASM attr_accessible :status,:title,:rating,:breakfast,:price_for_room,:country,:state,:city,:street, :room_description, :name_of_photo, :id belongs_to :user belongs_to :admin has_many :ratings has_many :raters, :through => :ratings, :source => :users mount_uploader :name_of_photo, PhotosUploader validates :title, presence: true, length: { maximum: 140 } validates :user_id, presence: true validates :room_description, presence: true validates :price_for_room, presence: true, numericality: true validates :country, presence: true validates :state, presence: true validates :city, presence: true validates :street, presence: true scope :status, -> (status) { where status: status } def average_rating @value = 0 self.ratings.each do |rating| @value = @value + rating.value end @total = self.ratings.size '%.2f' % (@value.to_f / @total.to_f) update_attributes(rating: '%.2f' % (@value.to_f / @total.to_f)) end aasm :column => 'status' do state :pending, :initial => true state :approved state :rejected event :approve do transitions :from => :pending, :to => :approved end event :reject do transitions :from => :pending, :to => :rejected end end end
# CJW: As of 5/7, active_full_review_count is deprecated, use only active_review_count # CJW: As of 5/7, active_rating_review_count is deprecated, use only active_review_count class ProductStat < ActiveRecord::Base SMALL_NUMBER_NAMES = %w(zero one two three four five) MIN_REVIEW_COUNT_TO_RANK = 1 CAP_REVIEW_COUNT_TO_RANK = 10 belongs_to :product belongs_to :representative_review, :class_name => 'Review', :foreign_key => 'representative_review_id' belongs_to :most_helpful_pro_review, :class_name => 'Review', :foreign_key => 'most_helpful_pro_review_id' belongs_to :most_helpful_con_review, :class_name => 'Review', :foreign_key => 'most_helpful_con_review_id' def update_all_stats begin ProductStat.transaction do update_active_review_count update_review_count update_average_word_count self.average_rating = self.product.reviews.active.average(:points).to_f update_helpful_count update_inappropriate_count update_star_counts update_representative_review update_recommend_count update_dont_recommend_count update_ranking_score update_most_helpful_con_review update_most_helpful_pro_review end rescue => e logger.error("Unable to update stats for product #{ self.product.blank? ? '<unknown>' : self.product.id}: #{e.backtrace.join("\n")}") end true end def update_active_review_count self.active_review_count = self.product.reviews.active.count end def update_review_count self.review_count = Review.count :conditions => "product_id = #{self.product.id}" end def update_average_word_count if self.active_review_count.zero? self.average_word_count = 0 else self.average_word_count = self.product.reviews.active.inject(0) { |count, review| count += review.content.gsub(/<\/?[^>]*>/, "").scan(/(\w|-)+/).size } / self.active_review_count end end def update_helpful_count self.helpful_count = Review.count_by_sql <<-SQL SELECT COUNT(r.product_id) FROM reviews r INNER JOIN helpfuls h ON h.owner_id = r.id AND h.value = 1 AND h.owner_type = 'Review' WHERE r.status = 'active' AND product_id = #{self.product.id} GROUP BY r.product_id; SQL end def update_inappropriate_count # AJA TODO: take inappropriate status into account? self.inappropriate_count = Review.count_by_sql <<-SQL SELECT inappropriated_id, COUNT(inappropriated_id) FROM inappropriates WHERE inappropriated_type = 'Product' AND inappropriated_id = #{self.product.id} GROUP BY inappropriated_id SQL end def update_star_counts sql = <<-SQL SELECT ROUND(points * #{Review::POINTS_TO_STARS_CONVERSION}) AS stars, COUNT(*) AS count FROM reviews WHERE product_id = #{self.product.id} and reviews.status = 'active' GROUP BY ROUND(points * #{Review::POINTS_TO_STARS_CONVERSION}) ORDER BY ROUND(points * #{Review::POINTS_TO_STARS_CONVERSION}) ASC SQL result_set = ActiveRecord::Base.connection.execute sql self.one_star_count = 0 self.two_star_count = 0 self.three_star_count = 0 self.four_star_count = 0 self.five_star_count = 0 result_set.each do |r| stars = r[0].to_i count = r[1] stars_word = SMALL_NUMBER_NAMES[stars] self.send("#{stars_word}_star_count=", count.to_i ) end end def update_representative_review self.representative_review = nil if self.active_review_count < 1 self.representative_review = self.product.reviews.active.first if self.active_review_count == 1 sql = <<-SQL SELECT r.*, ABS(ROUND(ps.average_rating - r.points * 0.05 * 2.0) / 2.0) AS points_dist FROM reviews r LEFT OUTER JOIN review_stats rs on r.id = rs.review_id JOIN product_stats ps on ps.product_id = r.product_id WHERE (ps.product_id = #{self.product.id} AND r.status = 'active') ORDER BY rs.inappropriate_count ASC, rs.violation_count ASC, points_dist ASC, rs.ranking_score DESC LIMIT 1 SQL rs = Review.find_by_sql sql self.representative_review = rs[0] unless rs.blank? end def update_recommend_count self.recommend_count = self.product.reviews.active.count :conditions => '(recommend = 1 OR (recommend IS NULL AND points >= 80))' end def update_dont_recommend_count self.dont_recommend_count = self.product.reviews.active.count :conditions => '(recommend = 0 OR (recommend IS NULL AND points <= 40))' end def update_ranking_score multiplier = active_review_count >= CAP_REVIEW_COUNT_TO_RANK ? CAP_REVIEW_COUNT_TO_RANK : 1 self.ranking_score = if self.active_review_count >= MIN_REVIEW_COUNT_TO_RANK self.average_rating * multiplier else 0.0 end end def update_most_helpful_con_review sql = <<-SQL SELECT r.* FROM reviews r JOIN review_stats rs ON rs.review_id = r.id JOIN user_stats us ON us.user_id = r.user_id WHERE product_id = #{self.product_id} AND r.points <= 60 AND r.status = 'active' AND rs.ranking_score >= 0 AND rs.character_count >= 250 ORDER BY r.product_id, rs.ranking_score DESC, us.helpful_count DESC, us.reviews_written DESC, length(r.content) DESC LIMIT 1 SQL r = Review.find_by_sql sql self.most_helpful_con_review = (r.blank? ? nil : r[0]) r end def update_most_helpful_pro_review sql = <<-SQL SELECT r.* FROM reviews r JOIN review_stats rs ON rs.review_id = r.id JOIN user_stats us ON us.user_id = r.user_id WHERE product_id = #{self.product_id} AND r.points >= 80 AND r.status = 'active' AND rs.ranking_score >= 0 AND rs.character_count >= 250 ORDER BY r.product_id, rs.ranking_score DESC, us.helpful_count DESC, us.reviews_written DESC, length(r.content) DESC LIMIT 1 SQL r = Review.find_by_sql sql self.most_helpful_pro_review = (r.blank? ? nil : r[0]) r end def self.calculate_for_all ProductStat.calculate_review_count_for_all ProductStat.calculate_active_review_count_for_all ProductStat.calculate_average_rating_for_all ProductStat.calculate_helpful_count_for_all ProductStat.calculate_inappropriate_count_for_all ProductStat.calculate_star_count_for_all ProductStat.calculate_representative_review_for_all ProductStat.calculate_recommend_count_for_all ProductStat.calculate_dont_recommend_count_for_all ProductStat.calculate_ranking_score_for_all ProductStat.calculate_rank_in_subcat_for_all end def self.calculate_review_count_for_all logger.debug "calculating all review counts..." if logger.debug? sql = <<-SQL UPDATE product_stats ps SET ps.review_count = 0 SQL ActiveRecord::Base.connection.execute sql sql = <<-SQL UPDATE product_stats ps JOIN (SELECT product_id, count(product_id) AS cnt FROM reviews GROUP BY product_id) AS xx ON xx.product_id = ps.product_id SET ps.review_count = xx.cnt SQL ActiveRecord::Base.connection.execute sql end def self.calculate_active_review_count_for_all logger.debug "calculating all active review counts..." if logger.debug? sql = <<-SQL UPDATE product_stats ps SET ps.active_review_count = 0 SQL ActiveRecord::Base.connection.execute sql sql = <<-SQL UPDATE product_stats ps JOIN (SELECT product_id, count(product_id) AS cnt FROM reviews where status = 'active' GROUP BY product_id) AS xx ON xx.product_id = ps.product_id SET ps.active_review_count = xx.cnt SQL ActiveRecord::Base.connection.execute sql end def self.calculate_helpful_count_for_all logger.debug "calculating all helpful counts..." if logger.debug? sql = <<-SQL UPDATE product_stats ps SET ps.helpful_count = 0 SQL ActiveRecord::Base.connection.execute sql sql = <<-SQL UPDATE product_stats ps JOIN ( SELECT product_id, count(r.product_id) cnt FROM reviews r INNER JOIN helpfuls h ON h.owner_id = r.id AND h.owner_type = 'Review' AND h.value = 1 WHERE r.status = 'active' GROUP BY r.product_id) AS xx ON xx.product_id = ps.product_id SET ps.helpful_count = cnt SQL ActiveRecord::Base.connection.execute sql end def self.calculate_inappropriate_count_for_all logger.debug "calculating all inappropriate_counts..." if logger.debug? sql = <<-SQL UPDATE product_stats ps SET ps.inappropriate_count = 0 SQL ActiveRecord::Base.connection.execute sql sql = <<-SQL UPDATE product_stats ps JOIN ( SELECT inappropriated_id, count(inappropriated_id) AS cnt FROM inappropriates WHERE inappropriated_type = 'Product' GROUP BY inappropriated_id ) AS xx ON xx.inappropriated_id = ps.product_id SET ps.inappropriate_count = cnt SQL ActiveRecord::Base.connection.execute sql end def self.calculate_star_count_for_all logger.debug "calculating all star counts..." if logger.debug? 1.upto(5) do |stars| points = Review.convert_stars_to_points(stars) stars_word = ProductStat::SMALL_NUMBER_NAMES[stars] sql = <<-SQL UPDATE product_stats ps SET ps.#{stars_word}_star_count = 0 SQL ActiveRecord::Base.connection.execute sql sql = <<-SQL UPDATE product_stats ps JOIN ( SELECT product_id, COUNT(product_id) AS cnt FROM reviews WHERE reviews.status = 'active' AND points = #{points} GROUP BY product_id ORDER BY product_id ) AS xx ON xx.product_id = ps.product_id SET ps.#{stars_word}_star_count = xx.cnt SQL ActiveRecord::Base.connection.execute sql end end def self.calculate_representative_review_for_all logger.debug "calculating all representative reviews..." if logger.debug? sql = <<-SQL UPDATE product_stats ps SET ps.representative_review_id = null SQL ActiveRecord::Base.connection.execute sql sql = <<-SQL update product_stats ps join ( select reviews_with_distance.*, min(@cnt := @cnt + 1) as ord from ( SELECT r.*, ABS(ROUND(ps.average_rating - r.points * 0.05 * 2.0) / 2.0) AS points_dist FROM reviews r LEFT OUTER JOIN review_stats rs on r.id = rs.review_id JOIN product_stats ps on ps.product_id = r.product_id WHERE (r.status = 'active') ORDER BY rs.inappropriate_count ASC, rs.violation_count ASC, points_dist ASC, rs.helpful_count DESC) reviews_with_distance JOIN (SELECT @cnt := 0) tmp GROUP BY product_id) as closest_reviews ON ps.product_id = closest_reviews.product_id SET ps.representative_review_id = closest_reviews.id SQL ActiveRecord::Base.connection.execute sql end def self.calculate_recommend_count_for_all logger.debug "calculating all recommend counts..." if logger.debug? sql = <<-SQL UPDATE product_stats ps SET ps.recommend_count = 0 SQL ActiveRecord::Base.connection.execute sql sql = <<-SQL UPDATE product_stats ps JOIN (SELECT product_id, count(product_id) AS cnt FROM reviews where status = 'active' AND (recommend = 1 OR (recommend IS NULL AND points >= 80)) GROUP BY product_id) AS xx ON xx.product_id = ps.product_id SET ps.recommend_count = xx.cnt SQL ActiveRecord::Base.connection.execute sql end def self.calculate_dont_recommend_count_for_all logger.debug "calculating all don't recommend counts..." if logger.debug? sql = <<-SQL UPDATE product_stats ps SET ps.dont_recommend_count = 0 SQL ActiveRecord::Base.connection.execute sql sql = <<-SQL UPDATE product_stats ps JOIN (SELECT product_id, count(product_id) AS cnt FROM reviews where status = 'active' AND (recommend = 0 OR (recommend IS NULL AND points <= 40)) GROUP BY product_id) AS xx ON xx.product_id = ps.product_id SET ps.dont_recommend_count = xx.cnt SQL ActiveRecord::Base.connection.execute sql end def self.calculate_ranking_score_for_all logger.debug "calculating all ranking scores..." if logger.debug? sql = <<-SQL UPDATE product_stats ps SET ps.ranking_score = 0 SQL ActiveRecord::Base.connection.execute sql sql = <<-SQL UPDATE product_stats ps JOIN (SELECT product_id, average_rating * #{CAP_REVIEW_COUNT_TO_RANK}.0 AS score FROM product_stats WHERE active_review_count >= #{CAP_REVIEW_COUNT_TO_RANK}) AS xx ON xx.product_id = ps.product_id SET ps.ranking_score = xx.score SQL ActiveRecord::Base.connection.execute sql sql = <<-SQL UPDATE product_stats ps JOIN (SELECT product_id, average_rating AS score FROM product_stats WHERE active_review_count < #{CAP_REVIEW_COUNT_TO_RANK} AND active_review_count >= #{MIN_REVIEW_COUNT_TO_RANK}) AS xx ON xx.product_id = ps.product_id SET ps.ranking_score = xx.score SQL ActiveRecord::Base.connection.execute sql sql = "UPDATE product_stats SET ranking_score = 0 WHERE active_review_count < #{MIN_REVIEW_COUNT_TO_RANK}" ActiveRecord::Base.connection.execute sql end def self.calculate_rank_in_subcat_for_all leaves = Category.find_root.find_all_leaves leaves.each do |cat| ProductStat.transaction do # NULL out all ranks in this subcat sql = <<-SQL UPDATE product_stats ps JOIN ( SELECT id AS product_id FROM products WHERE category_id = #{cat.id} ) AS xx ON xx.product_id = ps.product_id SET ps.rank_in_subcat = NULL SQL ActiveRecord::Base.connection.execute sql # This voodoo with @a is magic to replicate Oracle's ROWID functionality so I don't # need to load lots of objects into memory and can instead do everything in the DB sql = "set @a := 0" ActiveRecord::Base.connection.execute sql # Calculate an update the ranked order in this subcat sql = <<-SQL UPDATE product_stats ps JOIN ( SELECT product_id, ps.ranking_score, @a := @a+1 as rowid FROM products p JOIN product_stats ps ON p.id = ps.product_id WHERE p.category_id = #{cat.id} AND ps.ranking_score > 0 ORDER BY ps.ranking_score DESC, ps.active_review_count DESC ) AS xx ON xx.product_id = ps.product_id SET ps.rank_in_subcat = xx.rowid SQL ActiveRecord::Base.connection.execute sql end # of transaction end end def self.calculate_most_helpful_pro_reviews_for_all sql = <<-SQL UPDATE product_stats ps SET ps.most_helpful_pro_review_id = NULL SQL ActiveRecord::Base.connection.execute sql pro_sql = <<-SQL update product_stats ps join ( SELECT dyn_tabl.*, min(@cnt := @cnt + 1) AS ord FROM ( SELECT product_id, r.id as review_id, r.user_id, r.points, rs.ranking_score, us.helpful_count AS user_helpful_count, us.reviews_written AS user_reviews FROM reviews r JOIN review_stats rs ON rs.review_id = r.id JOIN user_stats us ON us.user_id = r.user_id WHERE r.points >= 80 AND r.status = 'active' AND rs.ranking_score >= 0 AND rs.character_count >= 250 ORDER BY r.product_id, rs.ranking_score DESC, us.helpful_count DESC, us.reviews_written DESC, length(r.content) DESC ) AS dyn_tabl JOIN (SELECT @cnt := 0) tmp GROUP BY product_id ) as helpful_pros ON ps.product_id = helpful_pros.product_id SET ps.most_helpful_pro_review_id = helpful_pros.review_id SQL ActiveRecord::Base.connection.execute pro_sql end def self.calculate_most_helpful_con_reviews_for_all sql = <<-SQL UPDATE product_stats ps SET ps.most_helpful_con_review_id = NULL SQL ActiveRecord::Base.connection.execute sql con_sql = <<-SQL update product_stats ps join ( SELECT dyn_tabl.*, min(@cnt := @cnt + 1) AS ord FROM ( SELECT product_id, r.id as review_id, r.user_id, r.points, rs.ranking_score, us.helpful_count AS user_helpful_count, us.reviews_written AS user_reviews FROM reviews r JOIN review_stats rs ON rs.review_id = r.id JOIN user_stats us ON us.user_id = r.user_id WHERE r.points <= 60 AND r.status = 'active' AND rs.ranking_score >= 0 AND rs.character_count >= 250 ORDER BY r.product_id, rs.ranking_score DESC, us.helpful_count DESC, us.reviews_written DESC, length(r.content) DESC ) AS dyn_tabl JOIN (SELECT @cnt := 0) tmp GROUP BY product_id) as helpful_cons ON ps.product_id = helpful_cons.product_id SET ps.most_helpful_con_review_id = helpful_cons.review_id SQL ActiveRecord::Base.connection.execute con_sql end def self.calculate_average_rating_for_all logger.debug "calculating all average ratings..." if logger.debug? sql = <<-SQL UPDATE product_stats ps SET ps.average_rating = 0 SQL ActiveRecord::Base.connection.execute sql sql = <<-SQL UPDATE product_stats ps JOIN ( SELECT product_id, AVG(r.points) avg FROM reviews r WHERE status = 'active' GROUP BY r.product_id) AS xx ON xx.product_id = ps.product_id SET ps.average_rating = avg SQL ActiveRecord::Base.connection.execute sql end def total_recommend_or_not_count self.recommend_count + self.dont_recommend_count end def recommend_percentage_data? total_recommend_or_not_count > 0 end def recommend_percentage percentage recommend_count, total_recommend_or_not_count end def dont_recommend_percentage percentage dont_recommend_count, total_recommend_or_not_count end private def percentage(x, n) return nil if n == 0 ((x.to_f / n.to_f) * 100).round end end
# frozen_string_literal: true module Dynflow class ThrottleLimiter attr_reader :core def initialize(world) @world = world spawn end def initialize_plan(plan_id, semaphores_hash) core.tell([:initialize_plan, plan_id, semaphores_hash]) end def finish(plan_id) core.tell([:finish, plan_id]) end def handle_plans!(*args) core.ask!([:handle_plans, *args]) end def cancel!(plan_id) core.tell([:cancel, plan_id]) end def terminate core.ask(:terminate!) end def observe(parent_id = nil) core.ask!([:observe, parent_id]) end def core_class Core end private def spawn Concurrent::Promises.resolvable_future.tap do |initialized| @core = core_class.spawn(:name => 'throttle-limiter', :args => [@world], :initialized => initialized) end end class Core < Actor def initialize(world) @world = world @semaphores = {} end def initialize_plan(plan_id, semaphores_hash) @semaphores[plan_id] = create_semaphores(semaphores_hash) set_up_clock_for(plan_id, true) end def handle_plans(parent_id, planned_ids, failed_ids) failed = failed_ids.map do |plan_id| ::Dynflow::World::Triggered[plan_id, Concurrent::Promises.resolvable_future].tap do |triggered| execute_triggered(triggered) end end planned_ids.map do |child_id| ::Dynflow::World::Triggered[child_id, Concurrent::Promises.resolvable_future].tap do |triggered| triggered.future.on_resolution! { self << [:release, parent_id] } execute_triggered(triggered) if @semaphores[parent_id].wait(triggered) end end + failed end def observe(parent_id = nil) if parent_id.nil? @semaphores.reduce([]) do |acc, cur| acc << { cur.first => cur.last.waiting } end elsif @semaphores.key? parent_id @semaphores[parent_id].waiting else [] end end def release(plan_id, key = :level) return unless @semaphores.key? plan_id set_up_clock_for(plan_id) if key == :time semaphore = @semaphores[plan_id] semaphore.release(1, key) if semaphore.children.key?(key) if semaphore.has_waiting? && semaphore.get == 1 execute_triggered(semaphore.get_waiting) end end def cancel(parent_id, reason = nil) if @semaphores.key?(parent_id) reason ||= 'The task was cancelled.' @semaphores[parent_id].waiting.each do |triggered| cancel_plan_id(triggered.execution_plan_id, reason) triggered.future.reject(reason) end finish(parent_id) end end def finish(parent_id) @semaphores.delete(parent_id) end private def cancel_plan_id(plan_id, reason) plan = @world.persistence.load_execution_plan(plan_id) steps = plan.run_steps steps.each do |step| step.state = :error step.error = ::Dynflow::ExecutionPlan::Steps::Error.new(reason) step.save end plan.update_state(:stopped) plan.save end def execute_triggered(triggered) @world.execute(triggered.execution_plan_id, triggered.finished) end def set_up_clock_for(plan_id, initial = false) if @semaphores[plan_id].children.key? :time timeout_message = 'The task could not be started within the maintenance window.' interval = @semaphores[plan_id].children[:time].meta[:interval] timeout = @semaphores[plan_id].children[:time].meta[:time_span] @world.clock.ping(self, interval, [:release, plan_id, :time]) @world.clock.ping(self, timeout, [:cancel, plan_id, timeout_message]) if initial end end def create_semaphores(hash) semaphores = hash.keys.reduce(Utils.indifferent_hash({})) do |acc, key| acc.merge(key => ::Dynflow::Semaphores::Stateful.new_from_hash(hash[key])) end ::Dynflow::Semaphores::Aggregating.new(semaphores) end end end end
class Admin::DataCancersController < Admin::BaseController before_action :load_data_cancer, only: [:update, :edit, :show, :destroy] def index @search = DataCancer.ransack(params[:q]) @data_cancers = @search.result @data_cancers = @data_cancers.page(params[:page]).per Settings.per_page.admin.data_cancer respond_to do |format| format.html format.js end end def new @data_cancer = DataCancer.new end def show end def create @data_cancer = DataCancer.new data_cancer_params if @data_cancer.save flash[:success] = t "admin.data_cancers.create_success" redirect_to admin_data_cancers_path else flash[:success] = t "admin.data_cancers.create_success" render :new end end def edit end def update if @data_cancer.update_attributes data_cancer_params flash[:success] = t "admin.data_cancers.updated_success" redirect_to [:admin, @data_cancer] else render :edit end end def destroy if @data_cancer.destroy flash[:success] = t("delete") + t("success") redirect_to admin_data_cancers_path else flash[:error] = t("delete") + t("fail") redirect_to admin_data_cancers_path end end private def load_data_cancer @data_cancer = DataCancer.find_by id: params[:id] return if @data_cancer.present? flash[:warning] = t "not_found_item" redirect_to :back end def data_cancer_params params.require(:data_cancer).permit DataCancer::ATTR_PARAMS end end
namespace :env do task :dev => [:environment] do set :domain, 'dev.etradecreative.com' set :user, 'deploy' set :group, 'deploy' set :rvm_path, '/home/deploy/.rvm' set :rvm, "#{rvm_path}/scripts/rvm" set :nvm_path, '/home/deploy/.nvm' set :nvm, "#{nvm_path}/nvm.sh" # set :rvm_version, '2.1.2' # set :nvm_version, '0.10.26' set :upstart_path, '/etc/init/' set :nginx_path, '/etc/nginx' set :fpm_path, '/etc/php5/fpm' set :deploy_server, 'dev' invoke :defaults # invoke :"rvm:use[#{rvm_version}]" # invoke :"nvm:use[#{nvm_version}]" end end
class SettingsController < ApplicationController before_filter :confirm_logged_in, :except => :thanks before_filter :current_user #form for users to edit their profile settings def settingspage @user=User.find(session[:user_id]) @uptotal=0 contents= Content.where(:user_id => session[:user_id], :privacy => true) contents.each do |content|#Calculate total upvotes @uptotal+=content.flaggings.size content.upvotes=content.flaggings.size end end #updates the user's info with changes def updateInformation #Find object using form parameters @user = User.find(session[:user_id]) #Update the object if @user.update_attributes(params[:user]) #If update succeeds redirect to the list action flash[:notice]="Your information has been successfully updated." redirect_to(:controller => 'profile', :action => 'show') else #If save fails, redisplay the form so user can fix problems render('settingspage') end end #updates user's password with changes def updatePassword #Find object using form parameters @user = User.find(session[:user_id]) #Update the object if @user.update_attributes(params[:user]) #If update succeeds redirect to the list action flash[:notice]="Your information has been successfully updated." redirect_to(:controller => 'profile', :action => 'show') else #If save fails, redisplay the form so user can fix problems render('changepassword') end end #form for changing password def changepassword @user = User.find(session[:user_id]) confirm_logged_in if session[:user_id] != @user.id flash[:error]="You do not have permission to change this user's information." redirect_to(:controller => 'access', :action => 'index') end end def thanks end end
# frozen_string_literal: true class Link < ApplicationRecord belongs_to :house belongs_to :lot, class_name: 'House' validates :house_id, presence: true validates :lot_id, presence: true end
class CustomersController < ApplicationController def new @customer = Customer.new end def show end def index @customers = Customer.all end def create Customer.find_by(customer_email: customer_email) #render plain: params[:customer].inspect @customer = Customer.new(customer_params) respond_to do |format| if @customer.save format.html { redirect_to @customer, notice: 'User was successfully created.' } format.js {} format.json { render json: @customer, status: :created, location: @customer } else format.html { render action: "new" } format.json { render json: @user.errors, status: :unprocessable_entity } end end #redirect_to @customer end private def customer_params params.require(:customer).permit(:customer_name, :customer_lastname, :customer_email, :customer_phone, :customer_uin) end end
class Search::Actors attr_reader :page, :per_page def initialize(options) @id = 1 initialize_params(options) initialize_query end def results @query.limit(@per_page). offset(@per_page * (@page-1)).all end def total_cnt @query.size end private def initialize_params(options) @options = Search::ActorsParams.sanitize(options) @options.keys.each { |k| instance_variable_set("@#{k}", @options[k]) } end # Table name LOCATIONS # Model name Localizations def initialize_query @query = Actor.all @query = @query.where(type: @levels) if @levels if @domains.present? @query = @query.joins(:categories).where({ categories: { id: @domains }}) end if @search_term.present? @query = @query.where("actors.name ILIKE ? OR actors.short_name ILIKE ? OR actors.observation ILIKE ?", "%#{@search_term}%", "%#{@search_term}%", "%#{@search_term}%") end if @start_date || @end_date @first_date = (Time.zone.now - 50.years).beginning_of_day @second_date = (Time.zone.now + 50.years).end_of_day end if @start_date && !@end_date where_query = "COALESCE(locations.start_date, '#{@first_date}') >= ? OR COALESCE(locations.end_date, '#{@second_date}') >= ?", @start_date.to_time.beginning_of_day, @start_date.to_time.beginning_of_day a = @query.joins(:location).where(where_query) b = @query.joins(:localizations).where(where_query) sql = @query.connection.unprepared_statement { "((#{a.to_sql}) UNION (#{b.to_sql})) AS actors" } @query = Actor.from(sql) end if @end_date && !@start_date where_query = "COALESCE(locations.end_date, '#{@second_date}') <= ? OR COALESCE(locations.start_date, '#{@first_date}') <= ?", @end_date.to_time.end_of_day, @end_date.to_time.beginning_of_day a = @query.joins(:location).where(where_query) b = @query.joins(:localizations).where(where_query) sql = @query.connection.unprepared_statement { "((#{a.to_sql}) UNION (#{b.to_sql})) AS actors" } @query = Actor.from(sql) end if @start_date && @end_date where_query = "COALESCE(locations.start_date, '#{@first_date}') BETWEEN ? AND ? OR COALESCE(locations.end_date, '#{@second_date}') BETWEEN ? AND ? AND ? BETWEEN COALESCE(locations.start_date, '#{@first_date}') AND COALESCE(locations.end_date, '#{@second_date}')", @start_date.to_time.beginning_of_day, @end_date.to_time.end_of_day, @start_date.to_time.beginning_of_day, @end_date.to_time.end_of_day, @start_date.to_time.beginning_of_day a = @query.joins(:location).where(where_query) b = @query.joins(:localizations).where(where_query) sql = @query.connection.unprepared_statement { "((#{a.to_sql}) UNION (#{b.to_sql})) AS actors" } @query = Actor.from(sql) end @query = @query.distinct end end
module Refinery module PagesHelper def sanitize_hash(input_hash) sanitized_hash = HashWithIndifferentAccess.new input_hash.each do |key, value| # ActionPack's sanitize calls html_safe on sanitized input. sanitized_hash[key] = if value.respond_to? :html_safe sanitize value elsif value.respond_to? :each sanitize_hash value else value end end sanitized_hash end end end
class AddTeamCachesToMatchesAndRounds < ActiveRecord::Migration[5.0] def change add_index :league_matches, :winner_id add_column :league_matches, :loser_id, :integer, null: true, index: true, default: nil add_foreign_key :league_matches, :league_rosters, column: :loser_id add_column :league_match_rounds, :loser_id, :integer, null: true, index: true, default: nil add_foreign_key :league_match_rounds, :league_rosters, column: :loser_id add_column :league_match_rounds, :winner_id, :integer, null: true, index: true, default: nil add_foreign_key :league_match_rounds, :league_rosters, column: :winner_id add_column :league_match_rounds, :has_outcome, :bool, null: false, index: true, default: false rename_column :league_rosters, :forfeit_won_matches_count, :won_matches_count rename_column :league_rosters, :forfeit_lost_matches_count, :lost_matches_count add_column :league_rosters, :drawn_matches_count, :integer, default: 0, null: false reversible do |dir| dir.up do League::Match.includes(:rounds).find_each do |match| match.update_team_cache! match.valid? or fail match.save! end League::Roster.find_each do |roster| roster.update_match_counters! end end end end end
class DmCms::Admin::CmsPagesController < DmCms::Admin::AdminController include DmCms::PermittedParams helper "dm_cms/cms_pages" before_filter :current_page, :except => [:index, :file_tree, :expire_cache_total] #------------------------------------------------------------------------------ def index CmsPage.create_default_site if CmsPage.roots.empty? # @tree = CmsPage.arrange(order: :position) @tree = CmsPage.arrange(order: :row_order) end #------------------------------------------------------------------------------ def new_page @cms_page = CmsPage.new end #------------------------------------------------------------------------------ def create_page @cms_page = @current_page.children.new(cms_page_params) respond_to do |format| if @cms_page.save format.html { redirect_to admin_cms_page_url(@cms_page), notice: 'Page was successfully created.' } format.json { render json: @cms_page, status: :created, location: @cms_page } else format.html { render action: "new_page" } format.json { render json: @cms_page.errors, status: :unprocessable_entity } end end end #------------------------------------------------------------------------------ def edit @cms_page = @current_page end #------------------------------------------------------------------------------ def update if @current_page.update_attributes(cms_page_params) redirect_to :action => :show, :id => @current_page else @cms_page = @current_page render :action => :edit end end #------------------------------------------------------------------------------ def show end #------------------------------------------------------------------------------ def duplicate_page new_page = @current_page.duplicate_with_associations if new_page.nil? redirect_to admin_cms_page_url(@current_page), :flash => { :error => 'A duplicate page already exists' } else redirect_to edit_admin_cms_page_url(new_page), :flash => { :notice => 'Duplicate page created. Please customize it.' } end end # Given a new parent_id and position, place item in proper place # Note that position comes in as 0-based, increment to make 1-based #------------------------------------------------------------------------------ def ajax_sort @current_page.update_attributes(row_order_position: params[:item][:position], parent_id: params[:item][:parent_id]) #--- this action will be called via ajax render nothing: true end #------------------------------------------------------------------------------ def destroy @current_page.destroy redirect_to :action => :index end # Removes all cache files. This can be used when we're not sure if the # cache file for a changed page has been deleted or not #------------------------------------------------------------------------------ def expire_cache_total #--- expire only items for this account key_start = fragment_cache_key(Account.current.id) expire_fragment(%r{\A#{key_start}}) # expire_fragment(%r{\S}) #--- this would expire *all* cache files respond_to do |format| format.html { redirect_to({:action => :index}, :notice => 'Page Cache was cleared') } format.js { render :nothing => true } end end protected #------------------------------------------------------------------------------ def current_page @current_page = CmsPage.friendly.find(params[:id]) end end
class Cause < ActiveRecord::Base has_and_belongs_to_many :headaches validate :valid_description validates_presence_of :description validates_uniqueness_of :description attr_accessible :description, :is_active, :default def valid_description has_one_letter = self.description =~ /[a-zA-Z]/ errors.add(:description, "must have at least one letter") unless (has_one_letter) end end
require 'rails_helper' describe User do context "#add_book" do let(:asin) { 'something' } let(:user) { User.create! } let(:book) do Book.create!(:asin => asin, :title => "a title", :authors => "Fred Smith", :details_url => "http://www.example.com/a-title") end context "when the user does not have the book" do it "adds the book to the user" do user.add_book(book) expect(user.books).to eql [book] end end context "when the user already has the book" do it "does not add the book to the user" do user.add_book(book) expect{user.add_book(book)}.to_not change{user.books.count} end end end end
class Description < ActiveRecord::Base has_many :users, through: :feelings has_many :feeling end
class StudioController < ApplicationController require 'nokogiri' require 'open-uri' def switch1 @page_title = 'Switch 1' end def switch2 @page_title = 'Switch 2' end def payloads @page_title = 'Payloads' end def git @page_title = 'Git' end def loot @page_title = 'Loot' if bunny_mounted? @loot_path = "#{bunny_path}/loot" FileUtils.mkpath @loot_path unless File.exist?(@loot_path) end end def extensions @page_title = 'Extensions' @loaded_extensions = [] if bunny_mounted? Dir.foreach("#{bunny_path}/payloads/extensions") do |extension| @loaded_extensions << extension end end end def debug @page_title = 'Debug' if bunny_mounted? @debug_path = "#{bunny_path}/debug" FileUtils.mkpath @debug_path unless File.exist?(@debug_path) end end def learn @page_title = 'Learn' end def configure @page_title = 'Configure' end def firmware @page_title = 'Firmware' end # API def write_payload if bunny_mounted? file_path = "#{bunny_path}#{params[:file]}" File.open(file_path, 'w') { |file| file.write(params[:payload]) } render json: { status: 200, file: file_path } else render json: { status: 500 } end end def clone_repo Git.clone(params[:repo], '', path: local_repo_path) render json: { status: 200 } end def git_command output = `cd #{local_repo_path} && git #{params[:command]}` render json: { status: 200, output: output } end def delete_repo FileUtils.rm_r local_repo_path, force: true FileUtils.mkpath local_repo_path render json: { status: 200 } end def sync_extensions if bunny_mounted? extension_path = '/payloads/extensions' FileUtils.rm_r "#{bunny_path}#{extension_path}", force: true FileUtils.mkpath "#{bunny_path}#{extension_path}" extensions = params[:extensions].split(',') index = 0 if bunny_mounted? Dir.foreach("#{local_repo_path}#{extension_path}") do |extension| index += 1 next if extension == '.' || extension == '..' if extensions.include?(index.to_s) FileUtils.cp "#{local_repo_path}#{extension_path}/#{extension}", "#{bunny_path}#{extension_path}/#{extension}" end end end render json: { status: 200 } else render json: { status: 500 } end end def copy_payload if bunny_mounted? FileUtils.rm_r "#{bunny_path}/payloads/switch#{params[:switch_position]}", force: true FileUtils.mkpath "#{bunny_path}/payloads/switch#{params[:switch_position]}" FileUtils.cp_r "#{params[:path]}/.", "#{bunny_path}/payloads/switch#{params[:switch_position]}/" render json: { status: 200 } else render json: { status: 500 } end end def eject_bunny if File.exist?(bunny_path) begin `umount #{bunny_path}` render json: { status: 200 } rescue # Windows - Untested `mountvol #{bunny_path} /D` render json: { status: 200 } end else render json: { status: 500 } end end def payload_script file_path = "#{bunny_path}#{params[:file]}" render json: { status: 200, payload: File.exist?(file_path) ? File.read(file_path) : '', file: file_path } end def raw_file render plain: File.read("#{params[:path]}/#{params[:file]}") end def share_internet # download and run bb.sh here end end
class ChangeStringFormatToDateInLeads < ActiveRecord::Migration def change change_column :leads, :birthday, 'date USING CAST(birthday AS date)' end end
class Company < ActiveRecord::Base attr_accessible :industry, :name, :password, :link has_many :postings has_secure_password validates :name, presence: true, length: { maximum:50 } validates :industry, presence: true, length: { maximum:50 } validates :password, :on=> :create, length: { minimum: 6 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :link, presence: true, format: { with: VALID_EMAIL_REGEX } before_save :create_remember_token def self.degree_conditions(degree) find(:all, :conditions => ['degree LIKE ?', "%#{degree}%"]) unless degree.blank? end def self.title_conditions(title) find(:all, :conditions => ['title LIKE ?', "%#{title}%"]) unless title.blank? end def self.skills_conditions(skills) find(:all, :conditions => ['skills LIKE ?', "%#{skills}%"]) unless skills.blank? end def self.profession_conditions(profession) find(:all, :conditions => ['profession LIKE ?', "%#{profession}%"]) unless profession.blank? end def self.professionandtitle_conditions(profession,title ) find(:all, :conditions => (['title LIKE ?', "%#{title}%"] or ['profession LIKE ?', "%#{profession}%"] )) end def self.degreeandtitle_conditions(degree,title ) find(:all, :conditions => (['title LIKE ?', "%#{title}%"] or ['degree LIKE ?', "%#{degree}%"] )) end def self.skillsandtitle_conditions(skills,title ) find(:all, :conditions => (['title LIKE ?', "%#{title}%"] or ['skills LIKE ?', "%#{skills}%"] )) end def self.skillsanddegree_conditions(skills,degree ) find(:all, :conditions => (['degree LIKE ?', "%#{degree}%"] or ['skills LIKE ?', "%#{skills}%"] )) end def self.professionanddegree_conditions(degree,profession ) find(:all, :conditions => (['degree LIKE ?', "%#{degree}%"] or ['profession LIKE ?', "%#{profession}%"] )) end def self.skillsandprofession_conditions(skills,profession ) find(:all, :conditions => (['skills LIKE ?', "%#{skills}%"] or ['profession LIKE ?', "%#{profession}%"] )) end def self.skillsdegreetitle_conditions(skills,degree,title ) find(:all, :conditions => (['skills LIKE ?', "%#{skills}%"] or ['degree LIKE ?', "%#{degree}%"] or ['title LIKE ?', "%#{title}%"] )) end def self.skillsdegreeprofession_conditions(skills,degree,profession ) find(:all, :conditions => (['skills LIKE ?', "%#{skills}%"] or ['degree LIKE ?', "%#{degree}%"] or ['profession LIKE ?', "%#{profession}%"] )) end def self.degreeprofessiontitle_conditions(degree,profession,title ) find(:all, :conditions => (['title LIKE ?', "%#{title}%"] or ['degree LIKE ?', "%#{degree}%"] or ['profession LIKE ?', "%#{profession}%"] )) end def self.skillseprofessiontitle_conditions(skills,profession,title ) find(:all, :conditions => (['title LIKE ?', "%#{title}%"] or ['skills LIKE ?', "%#{skills}%"] or ['profession LIKE ?', "%#{profession}%"] )) end def self.all_conditions(skills, degree, profession, title) find(:all, :conditions => (['title LIKE ?', "%#{title}%"] or ['skills LIKE ?', "%#{skills}%"] or ['profession LIKE ?', "%#{profession}%"] or ['degree LIKE ?', "%#{degree}%"] )) end private def create_remember_token self.remember_token = SecureRandom.urlsafe_base64 end end
require File.dirname(__FILE__) + "/../../spec_helper" require File.dirname(__FILE__) + "/../fixtures/classes" describe "Added method clr_new" do it "calls the CLR ctor for a CLR type" do ctor = CLRNew::Ctor.clr_new ctor.should be_kind_of CLRNew::Ctor ctor.tracker.should == 1 end it "calls the CLR ctor for a subclassed CLR type" do ctor = CLRNew::Ctor.clr_new ctor.should be_kind_of CLRNew::Ctor ctor.tracker.should == 1 end it "calls the CLR ctor for aliased CLR types" do Array.clr_new.should == [] Hash.clr_new.should == {} (Thread.clr_new(System::Threading::ThreadStart.new {})).should be_kind_of Thread IO.clr_new.should be_kind_of IO String.clr_new.should == "" Object.clr_new.should be_kind_of Object Exception.clr_new.should be_kind_of Exception #TODO: All builtins? end it "doesn't call any Ruby initializer" do ctor = CLRNew::Ctor.clr_new ctor.tracker.should_not == 2 end it "raises a TypeError if called on a pure Ruby type" do class Bar;end lambda { Bar.clr_new }.should raise_error TypeError lambda { Class.new.clr_new }.should raise_error TypeError lambda { Numeric.clr_new }.should raise_error TypeError end end
require 'json' class MorrisChart def initialize(params = {}) raise 'No chart specified' unless params[:chart] raise 'No stats specified' unless params[:stats] raise 'No interval specified' unless params[:interval] @chart = params[:chart] @stats = params[:stats] @element = params[:element] || 'chart' @interval = params[:interval] end def to_hash @hash ||= { element: @element, data: data, xkey: 'time', ykeys: ['c'], labels: [@chart.name], xLabels: xlabels } end def to_json @json ||= to_hash.to_json end def data @data ||= filter_data(@stats).map { |s| { time: s.time.strftime(time_format), c: s.count } } end def filter_data(stats) if @chart.countable? if @chart.default_interval == 'daily' and @interval == 'daily' stats elsif @chart.default_interval == 'daily' and @interval == 'monthly' stats.group_by {|s| DateTime.new(s.time.year, s.time.month, 1) }.reduce([]) {|sum, e| time, stats = e sum << Stat.new(time: time, count: stats.reduce(0) {|sum, s| sum + s.count }) } end else stats end end def time_format case @interval when 'daily' then '%Y-%m-%d' when 'monthly' then '%Y-%m' end end def xlabels case @interval when 'daily' then 'day' when 'monthly' then 'month' end end def empty? @stats.empty? end end
module Api class Transaction < ConvertableStruct member :id, :integer member :title, :string member :uri, :string member :expired_at, :string member :initialized_at, :string member :expired, :boolean member :stopped, :boolean member :cancelled, :boolean end end
case node['platform'] when 'debian', 'ubuntu' execute "installing Datadog Agent on ubuntu" do command '"DD_API_KEY=31671308f852b47e8c80cab4dde17db0 bash -c "$(curl -L https://raw.githubusercontent.com/DataDog/dd-agent/master/packaging/datadog-agent/source/install_agent.sh)""' end execute "cp the process file" do command 'cp /etc/dd-agent/conf.d/process.yaml.example /etc/dd-agent/conf.d/process.yaml' end execute "restrting the seervice in redhat/centos" do command 'service dd-agent restart' end when 'redhat', 'centos', 'fedora' execute "installing Datadog Agent on redhat and centos" do command '"DD_API_KEY=31671308f852b47e8c80cab4dde17db0 bash -c "$(curl -L https://raw.githubusercontent.com/DataDog/dd-agent/master/packaging/datadog-agent/source/install_agent.sh)""' end execute "cp the process file" do command 'cp /etc/dd-agent/conf.d/process.yaml.example /etc/dd-agent/conf.d/process.yaml' end execute "restrting the seervice in redhat/centos" do command 'service dd-agent restart' end when 'windows' remote_file "c:/windows/temp/ddagent-cli-latest.msi" do source "https://s3.amazonaws.com/ddagent-windows-stable/ddagent-cli-latest.msi" end execute 'installing datadog agent' do command 'msiexec /qn /i c:\windows\temp\ddagent-cli-latest.msi APIKEY="31671308f852b47e8c80cab4dde17db0"' end file 'C:\ProgramData\Datadog\conf.d\win32_event_log.yaml' do content ::File.open('C:\ProgramData\Datadog\conf.d\win32_event_log.yaml.example').read action :create end file 'C:\ProgramData\Datadog\conf.d\windows_service.yaml' do content ::File.open('C:\ProgramData\Datadog\conf.d\windows_service.yaml.example').read action :create end windows_service 'DataDogAgent' do action :restart end end
class HomeController < ApplicationController def index @mark = Mark.new end private def mark_params params.require(:mark).permit(:lng, :lat, :msg) end end
class CreateMathPowers < ActiveRecord::Migration[6.1] def change create_table :math_powers do |t| t.integer :base t.integer :exp t.timestamps end end end
class Types::UserType < Types::BaseObject description 'ユーザー' field :id, ID, null: true, description: 'ユーザーID' field :name, String, null: false, description: 'ユーザー名' field :email, String, null: false, description: 'メールアドレス' field :avatarUrl, String, null: true, description: 'アバター' field :followerCount, Integer, null: false, description: 'フォロワー数' field :followingCount, Integer, null: false, description: 'フォロー数' field :followedByMe, Boolean, null: true, description: 'フォロー済みかどうか' end
module Ricer::Plugins::Log class Binlog def self.upgrade_1 m = ActiveRecord::Migration m.create_table :binlogs do |t| t.integer :user_id t.integer :channel_id t.string :input t.string :output t.datetime :created_at end end def self.irc_message(message, input) create!({ user_id: message.sender.id, channel_id: message.channel_id, input: input ? message.raw : nil, output: input ? nil : message.reply, created_at: irc_message.time, }) end def self.channel_log(channel) end end end
require 'rails_helper' RSpec.describe ConfirmationsController, type: :controller do let (:order) { FactoryGirl.create :submitted_order } describe "GET #show" do it "returns http success" do get :show, id: order.confirmation expect(response).to have_http_status(:success) end end end
# typed: false # frozen_string_literal: true # This file was generated by GoReleaser. DO NOT EDIT. class Stopgo < Formula desc "" homepage "" version "0.3.2" license "MIT" bottle :unneeded if OS.mac? url "https://github.com/jdhayford/stopgo/releases/download/v0.3.2/stopgo_0.3.2_Darwin_x86_64.tar.gz" sha256 "2d9d392823fc5e6e9d74b0f27e778b7efc12d0e4fd2643f80fee57d1932b7e98" end if OS.linux? && Hardware::CPU.intel? url "https://github.com/jdhayford/stopgo/releases/download/v0.3.2/stopgo_0.3.2_Linux_x86_64.tar.gz" sha256 "39a0c770b4edb8b8ca97be16ec4240f5fd690f44741490dbba911080c1af4cb8" end if OS.linux? && Hardware::CPU.arm? && Hardware::CPU.is_64_bit? url "https://github.com/jdhayford/stopgo/releases/download/v0.3.2/stopgo_0.3.2_Linux_arm64.tar.gz" sha256 "f05846731c2c5b65b4e794375df165dde880914d11629b39c0cd5f4835dcca3d" end depends_on "git" depends_on "zsh" => :optional def install bin.install "stopgo" end end
class RoomAssignment < ActiveRecord::Base belongs_to :room belongs_to :member validates_associated :room end
class AddOptOutToRsvp < ActiveRecord::Migration def self.up add_column :rsvps, :opt_out, :boolean, :default=>false add_column :rsvps, :display_id, :string end def self.down remove_column :rsvps, :opt_out remove_column :rsvps, :display_id end end
class ModEdge < ActiveRecord::Base has_one :modifier, as: :mod belongs_to :edge end
class StudentStatus def self.get_option id case id when 0 'Cursando' when 1 'Aprobado' when 2 'Repitio este año' when 3 'Repetidor del año pasado, pero cursando año lectivo actual' when 4 'Retirado de la institución' end end end
require 'rspec' require_relative '../registry' RSpec.describe Registry do let(:registry) { described_class.new } describe '#process_payment' do let(:coin) { described_class::Coin.new('2p', 2, 1) } subject { registry.process_payment(coin)} it 'increments the quantity of coins of the declared value' do expect { subject }.to change(registry, :length).by(1) expect(registry).to match_array([coin]) end context 'when the same value coin is already present' do let(:registry) { described_class.new << coin } it 'increments the quantity of coins of the declared value' do expect { subject }.to_not change(registry, :length) expect(coin.quantity).to eq 2 end end end describe '#give_change' do let(:coin) { described_class::Coin.new('5p', 5, 1) } let(:change_coin) { described_class::Coin.new('5p', 5, 1) } let(:expected_change) { described_class.new << change_coin } before do registry << coin end subject { registry.give_change(coin.unit_value) } it 'removes the only coin from the registry' do expect(subject).to match_array expected_change expect(registry).to be_empty end context 'when change cannot be given because of insufficient funds' do subject { registry.give_change(100) } it 'raises an error' do expect { subject }.to raise_error(described_class::ImpossibleToGiveChange) end end end describe '#self.value' do subject { described_class.value(coin_type) } context 'for supported coin_type' do let(:coin_type) { '5p' } it 'returns the correct value' do expect(subject).to eq 5 end end context 'for unsupported coin_type' do let(:coin_type) { '$5' } it 'returns the correct value' do expect { subject}.to raise_error(described_class::UnsupportedCoin) end end end describe '#self.coin' do subject { described_class.coin(coin_type) } context 'for supported coin_type' do let(:coin_type) { '5p' } it 'returns the correct value' do expect(subject).to be_an_instance_of(described_class::Coin) end end context 'for unsupported coin_type' do let(:coin_type) { '$5' } it 'returns the correct value' do expect { subject}.to raise_error(described_class::UnsupportedCoin) end end end end
class Tile < ApplicationRecord belongs_to :game has_one :player # # Check if player is on tile and # # return player if true # def has_player # Player.find_by(game_id: self.game_id, tile_id: self.id) # end end
Pod::Spec.new do |s| s.name = "PYControllers" s.version = "0.5.2" s.summary = "Most used UI controllers in iOS application, which is an extend for PYUIKit" s.homepage = "https://github.com/littlepush/PYControllers" s.license = { :type => "LGPLv3", :file => "LICENSE" } s.author = { "Push Chen" => "littlepush@gmail.com" } s.platform = :ios, "8.0" s.source = { :git => "https://github.com/littlepush/PYControllers.git", :tag => "0.5.2" } s.source_files = "PYControllers/*.{h,m}" s.frameworks = "QuartzCore" s.requires_arc = true s.dependency "PYCore" s.dependency "PYUIKit" end
# coding: utf-8 class WorksController < ApplicationController before_filter :auth_required def index end def search @items = Work.order(:title).joins(:participants) if !params[:q].blank? @items = @items.where("(title LIKE :q) OR (event_name LIKE :q) OR (event_organizer LIKE :q)", {:q => "%#{params[:q]}%"}) end if params[:filter] == 'sent' @items = @items.where("(works.status = :s)", {:s => Work::SENT}) end if params[:filter] == 'accepted' @items = @items.where("(works.status = :s)", {:s => Work::ACCEPTED}) end if params[:filter] == 'published' @items = @items.where("(works.status = :s)", {:s => Work::PUBLISHED}) end if params[:filter] == 'rejected' @items = @items.where("(works.status = :s)", {:s => Work::REJECTED}) end if params[:filter].to_i > 0 @items = @items.where("(works.status = :s AND year(published_date) = :y)", {:s => Work::PUBLISHED, :y => params[:filter]}) end if params[:filter] == 'validation_accepted' @items = @items.where("(validation_status = :s)", {:s => Work::VALIDATION_ACCEPTED}) end if params[:filter] == 'validation_not_validated' @items = @items.where("(works.status = :s AND validation_status = :v)", {:s => Work::PUBLISHED, :v => Work::VALIDATION_NOT_VALIDATED}) end if params[:filter] == 'validation_proccess' @items = @items.where("(works.status = :s AND validation_status = :v)", {:s => Work::PUBLISHED, :v => Work::VALIDATION_PROCCESS}) end if params[:filter] == 'validation_rejected' @items = @items.where("(works.status = :s AND validation_status = :v)", {:s => Work::PUBLISHED, :v => Work::VALIDATION_REJECTED}) end @items = @items.where("participants.user_id = :u", {:u => current_user_watching.id}) render :layout => false end def new @work = Work.new render :layout => false end def create raise "User watching must be equal to user logged in" if current_user.id != current_user_watching.id params[:work][:user_id] = current_user.id @work = Work.new(work_params) @work.status = Work::SENT @work.last_updated_by = current_user.id flash = {} if @work.save flash[:notice] = "Trabajo creado satisfactoriamente." # LOG @work.activity_log.create(user_id: current_user.id, message: "Creó el trabajo \"#{@work.title}\" (ID: #{@work.id}).") json = {} json[:id] = @work.id json[:title] = @work.title json[:flash] = flash render :json => json else flash[:error] = "No se pudo crear el trabajo." json = {} json[:flash] = flash json[:model_name] = self.class.name.sub("Controller", "").singularize json[:errors] = {} json[:errors] = @work.errors render :json => json, :status => :unprocessable_entity end end def show @work = Work.find(params[:id]) render :layout => false end def update @work = Work.find(params[:id]) @work.last_updated_by = current_user.id previous_status_class = @work.status_class flash = {} if @work.update_attributes(work_params) flash[:notice] = "Trabajo actualizado satisfactoriamente." json = {} json[:id] = @work.id json[:title] = @work.title json[:status_text] = @work.status_text json[:status_class] = @work.status_class json[:previous_status_class] = previous_status_class json[:flash] = flash render :json => json else flash[:error] = "No se pudo actualizar el trabajo." json = {} json[:flash] = flash json[:model_name] = self.class.name.sub("Controller", "").singularize json[:errors] = {} json[:errors] = @work.errors render :json => json, :status => :unprocessable_entity end end protected def work_params params[:work].permit( :title, :authors, :work_type, :event_name, :event_organizer, :event_location, :sent_date, :user_id, :status, :accepted_date, :published_date, :is_international, :country_id, :last_updated_by, :validation_status, :agreement_id, :institutional_program_id ) end end
class Comedian < ActiveRecord::Base belongs_to :user has_many :ratings has_many :reviews attr_accessor :crop_x, :crop_y, :crop_w, :crop_h attr_accessible :bio, :image, :remote_image_url, :user_id, :video, :stage_name, :email_is_public, :crop_x, :crop_y, :crop_w, :crop_h mount_uploader :image, ImageUploader validates :stage_name, presence: true, uniqueness: true, length: { in: 2..255 } validates :bio, length: { maximum: 8000 } validates :video, length: { maximum: 255 } extend FriendlyId friendly_id :stage_name, use: :slugged after_update :crop_image def crop_image image.recreate_versions! if crop_x.present? end def avg_rating total = 0.0 self.ratings.each do |rating| total += rating.score end count = self.ratings.count total/count end end
require 'boxzooka/base_response' require 'boxzooka/landed_quote_response_rate' module Boxzooka class LandedQuoteResponse < BaseResponse scalar :destination_country_code scalar :destination_province scalar :duty_amount, type: :decimal scalar :landed_cost_token collection :rates, entry_field_type: :entity, entry_type: LandedQuoteResponseRate, entry_node_name: 'Rate' scalar :tax_amount, type: :decimal end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # email :string not null # password_digest :string not null # session_token :string not null # created_at :datetime # updated_at :datetime # fname :string # lname :string # provider :string # uid :string # image_file_name :string # image_content_type :string # image_file_size :integer # image_updated_at :datetime # class User < ActiveRecord::Base attr_reader :password validates :email, :fname, :lname, :session_token, presence: true validates :password, length: { minimum: 5, allow_nil: true } validates :email, uniqueness: true has_attached_file :image, styles: { mini: '25x25>', profile: '160x160>' }, default_url: 'logo.png' validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/ after_initialize :ensure_session_token has_many :projects, class_name: "Project", foreign_key: :user_id, primary_key: :id, inverse_of: :user, dependent: :destroy has_many :follows, class_name: "Follow", foreign_key: :user_id, primary_key: :id, inverse_of: :follower, dependent: :destroy has_many :followed_projects, through: :follows, source: :project has_many :backings, class_name: "Backing", foreign_key: :user_id, primary_key: :id, dependent: :destroy, inverse_of: :backer has_many :backed_projects, through: :backings, source: :project def self.find_by_credentials(email, password) user = User.find_by_email(email) return nil unless user user.is_password?(password) ? user : nil end def self.find_or_create_by_auth_hash(auth_hash) user = User.find_by( provider: auth_hash[:provider], uid: auth_hash[:uid]) unless user user = User.create!( provider: auth_hash[:provider], uid: auth_hash[:uid], fname: auth_hash[:info][:name].split.first, lname: auth_hash[:info][:name].split.last, email: "cash_cow" + SecureRandom.urlsafe_base64(16) + "@cash-cow.io", password: SecureRandom.urlsafe_base64(16), image: auth_hash[:info][:image] ) end user end def password=(password) @password = password self.password_digest = BCrypt::Password.create(password) end def is_password?(password) BCrypt::Password.new(self.password_digest).is_password?(password) end def reset_token! self.session_token = SecureRandom.urlsafe_base64(16) self.save! self.session_token end protected def ensure_session_token self.session_token ||= SecureRandom.urlsafe_base64(16) end end
class CreateEmpresas < ActiveRecord::Migration def change create_table :empresas do |t| t.string :dns t.string :rfc t.string :urlwebservice t.string :usuariosob t.string :passob t.timestamps null: false end end end
# Write a program that checks if the sequence of characters "lab" # exists in the following strings. If it does exist, print out the word. # "laboratory" # "experiment" # "Pans Labyrinth" # "elaborate" # "polar bear" # /lab/.match("word") or using a method /lab/ =~ word # What will the following program print to the screen? What will it return? #needs a call to activate the block # What is exception handling and what problem does it solve? #exception handling is a method that helps code run through errors #Modify the code in exercise 2 to make the block execute properly. #add .call to the block inside the method #Why does the following code...Give us the following error when we run it? #need & in front of the block parameter
class User < ActiveRecord::Base has_and_belongs_to_many :titles attr_accessor :password attr_accessible :name, :email, :password, :password_confirmation, :address_line, :city, :state, :zipcode email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates_presence_of :name, :email, :password, :address_line, :city, :state, :zipcode validates_confirmation_of :password validates_uniqueness_of :email, :case_sensitive => false validates_length_of :name, :within => 3..20 validates_length_of :password, :within => 8..20 validates_numericality_of :zipcode validates_format_of :email, :with => email_regex validates_format_of :name, :city, :state, :with => /\A([A-Za-z\s\'\.-]*)\Z/ before_save :encrypt_password # Return true if the user's password matches the submitted password. def has_password?(submitted_password) # Compare encrypted_password with the encrypted version of # submitted_password. encrypted_password == encrypt(submitted_password) end def self.authenticate(email, submitted_password) user = find_by_email(email) return nil if user.nil? return user if user.has_password?(submitted_password) end def self.authenticate_with_salt(id, cookie_salt) user = find_by_id(id) (user && user.salt == cookie_salt) ? user : nil end private def encrypt_password self.salt = make_salt if new_record? self.encrypted_password = encrypt(password) end def encrypt(string) secure_hash("#{salt}--#{string}") end def make_salt secure_hash("#{Time.now.utc}--#{password}") end def secure_hash(string) Digest::SHA2.hexdigest(string) end end
# encoding: utf-8 class FileUploader < CarrierWave::Uploader::Base include Rails.application.routes.url_helpers #Rails.application.routes.default_url_options = ActionMailer::Base.default_url_options # see https://gist.github.com/995663 for examples of how to use per-extension processing rules # Include RMagick or MiniMagick support: # include CarrierWave::RMagick # include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: #storage :file storage :fog after :store, :zencode # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}/#{model.updated_at.to_i}" end AUDIO_EXTENSIONS = Settings.allowed_upload_types.audio VIDEO_EXTENSIONS = Settings.allowed_upload_types.video DOCUMENT_EXTENSIONS = Settings.allowed_upload_types.documents def extension_white_list AUDIO_EXTENSIONS + DOCUMENT_EXTENSIONS end def filename return unless original_filename #return 'video.mp4' if is_type? :video #return 'audio.mp3' if is_type? :audio original_filename end def is_type? type extension = File.extname(original_filename).downcase extension = extension[1..-1] if extension[0,1] == '.' extensions = %w() extensions = AUDIO_EXTENSIONS if type == :audio extensions = VIDEO_EXTENSIONS if type == :video extensions = DOCUMENT_EXTENSIONS if type == :document extensions.include?(extension) end def self.process_extensions(*args) extensions = args.shift args.each do |arg| if arg.is_a?(Hash) arg.each do |method, args| processors.push([:process_trampoline, [extensions, method, args]]) end else processors.push([:process_trampoline, [extensions, arg, []]]) end end end def process_trampoline(extensions, method, args) extension = File.extname(original_filename).downcase extension = extension[1..-1] if extension[0,1] == '.' self.send(method, *args) if extensions.include?(extension) end private def zencode(args) return unless is_type? :audio # or is_type? :video return unless Settings.use_zencoder settings = { :input => "s3://#{Settings.s3_bucket}/uploads/media_file/file/#{@model.id}/#{model.updated_at.to_i}/#{filename}", :output => [{ :base_url => "s3://#{Settings.s3_bucket}/uploads/media_file/file/#{@model.id}/#{model.updated_at.to_i}", :filename => filename, :label => "web", :notifications => ['http://sermonspeaker.com/media_files/notify'], :public => 1 }] } if is_type? :video settings[:output][0].merge!({ :video_codec => "h264", :audio_codec => "aac", :quality => 3, :width => 854, :height => 480, :format => "mp4", :aspect_mode => "preserve", }) elsif is_type? :audio settings[:output][0].merge!({ :audio_codec => "mp3", :audio_quality => 3, :format => "mp3", }) end zencoder_response = Zencoder::Job.create(settings) # Rails.logger.info zencoder_response.to_json zencoder_response.body["outputs"].each do |output| if output["label"] == "web" @model.job_id = output["id"] @model.save(:validate => false) end end end # Provide a default URL as a default if there hasn't been a file uploaded: # def default_url # "/images/fallback/" + [version_name, "default.png"].compact.join('_') # end # Process files as they are uploaded: # process :scale => [200, 300] # # def scale(width, height) # # do something # end # Create different versions of your uploaded files: # version :thumb do # process :scale => [50, 50] # end # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: # def extension_white_list # %w(jpg jpeg gif png) # end # Override the filename of the uploaded files: # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename # end end
json.array!(@group_mems) do |group_mem| json.extract! group_mem, :id json.url group_mem_url(group_mem, format: :json) end