text
stringlengths
10
2.61M
feature 'InvitationsController' do let!(:user){ create(:user) } describe 'send contact from webpage' do context 'send_contact' do it 'successfully sends contact email' do mail_count = ActionMailer::Base.deliveries.count visit "#{send_contact_invitations_path}.json?contact%5Bnombre%5D=test&contact%5Btelefono%5D=4353453&contact%5Bemail%5D=tonklis%40gmail.com&contact%5Benteraste%5D=&contact%5Bcomentarios%5D=&_=1442606277769" response = JSON.parse(page.body) expect(response['success']).to be true expect(ActionMailer::Base.deliveries.count).to eql (mail_count + 1) end end end describe 'request process' do context 'request creation' do it 'successfully creates invitation' do new_invitation = { recipient_name: "Pedrito Bodoque", recipient_email: "dmiramon@gmail.com", user_id:user.id} login_with_service u = { email: user.email, password: '12345678' } # Validates request creation with_rack_test_driver do page.driver.post "/invitations.json", { invitation: new_invitation} end response = JSON.parse(page.body) expect(response['success']).to be true expect(response['result']['token']).not_to eql nil expect(response['result']['recipient_email']).to eql "dmiramon@gmail.com" end it 'raises error on incorrect invitation' do new_invitation = { recipient_name: "Pedrito Bodoque", recipient_email: "dmiramon@gmail.com", user_id:-1} login_with_service u = { email: user.email, password: '12345678' } # Validates request creation with_rack_test_driver do page.driver.post "/invitations.json", { invitation: new_invitation} end response = JSON.parse(page.body) expect(response['success']).to be false end end end end
# frozen_string_literal: true FactoryBot.define do factory :reservation do user schedule { find_or_create(:schedule, date: Time.zone.today, count: 10) } hour { (1..12).to_a.sample } guests { (1..10).to_a.sample } status :placed end end
# -*- coding: utf-8 -*- require File.expand_path("../test_helper", File.dirname(__FILE__)) require "s7n/gpass_file" require "time" module S7n class GPassFileTest < Test::Unit::TestCase # パスフレーズが不正な場合、 InvalidPassphrase 例外が発生する。 def test_read__invalid_passphrase invalid_passphrases = ["", "1234", "qwert", "qwertyu", "QWERTY"] file = GPassFile.new invalid_passphrases.each do |s| assert_raises(InvalidPassphrase) do file.read(s, gpass_file_path("empty")) end end end # 機密情報がひとつもないファイルを読み込む。 def test_read__empty file = GPassFile.new res = file.read("qwerty", gpass_file_path("empty")) assert(res.entries.empty?) end # 機密情報がひとつのファイルを読み込む。 def test_read__one_entry file = GPassFile.new res = file.read("qwerty", gpass_file_path("one_entry")) entry = res.entries.first assert_equal(1, entry.id) assert_equal("entry1", entry.name) assert_equal("This is entry 1.", entry.description) assert_equal(Time.parse("2008-10-05 00:17:06").to_datetime, entry.created_at) assert_equal(Time.parse("2008-10-05 00:17:06").to_datetime, entry.updated_at) assert_equal("foo", entry.username) assert_equal("1234", entry.password) assert_equal(true, entry.expiration) assert_equal(Time.parse("2009-10-05 09:00:00").to_datetime, entry.expire_at) assert_equal([], entry.tags) assert_equal(1, res.entries.length) end # 機密情報が 3 つのファイルを読み込む。 def test_read__three_entry file = GPassFile.new res = file.read("qwerty", gpass_file_path("three_entries")) entry = res.entries[0] assert_equal(1, entry.id) assert_equal("entry1", entry.name) assert_equal("This is entry 1.", entry.description) assert_equal(Time.parse("2008-10-05 00:17:06").to_datetime, entry.created_at) assert_equal(Time.parse("2008-10-05 00:17:06").to_datetime, entry.updated_at) assert_equal("foo", entry.username) assert_equal("1234", entry.password) assert_equal(true, entry.expiration) assert_equal(Time.parse("2009-10-05 09:00:00").to_datetime, entry.expire_at) assert_equal("example.com", entry.hostname) assert_equal([], entry.tags) entry = res.entries[1] assert_equal(2, entry.id) assert_equal("entry2", entry.name) assert_equal("This is entry 2.", entry.description) assert_equal(Time.parse("2008-10-05 00:18:41").to_datetime, entry.created_at) assert_equal(Time.parse("2008-10-05 00:18:41").to_datetime, entry.updated_at) assert_equal("bar", entry.username) assert_equal("5678", entry.password) assert_equal(false, entry.expiration) assert_equal("", entry.hostname) assert_equal([], entry.tags) entry = res.entries[2] assert_equal(3, entry.id) assert_equal("entry3", entry.name) assert_equal("This is entry 3.", entry.description) assert_equal(Time.parse("2008-10-05 00:19:15").to_datetime, entry.created_at) assert_equal(Time.parse("2008-10-05 00:19:15").to_datetime, entry.updated_at) assert_equal("baz", entry.username) assert_equal("9876", entry.password) assert_equal(false, entry.expiration) assert_equal("", entry.hostname) assert_equal([], entry.tags) assert_equal(3, res.entries.length) end # フォルダを含むファイルを読み込む。 def test_read__with_folders file = GPassFile.new res = file.read("qwerty", gpass_file_path("with_folders")) entry = res.entries[0] assert_equal(1, entry.id) assert_equal("entry1-1", entry.name) assert_equal("This is entry 1-1.", entry.description) assert_equal(Time.parse("2008-10-05 00:17:06").to_datetime, entry.created_at) assert_equal(Time.parse("2008-10-05 00:20:58").to_datetime, entry.updated_at) assert_equal("foo", entry.username) assert_equal("1234", entry.password) assert_equal(true, entry.expiration) assert_equal(Time.parse("2009-10-05 09:00:00").to_datetime, entry.expire_at) assert_equal("example.com", entry.hostname) assert_equal(["folder1"], entry.tags) entry = res.entries[1] assert_equal(2, entry.id) assert_equal("entry1-2", entry.name) assert_equal("This is entry 1-2.", entry.description) assert_equal(Time.parse("2008-10-05 00:20:33").to_datetime, entry.created_at) assert_equal(Time.parse("2008-10-05 00:20:33").to_datetime, entry.updated_at) assert_equal("", entry.username) assert_equal("", entry.password) assert_equal(false, entry.expiration) assert_equal("", entry.hostname) assert_equal(["folder1"], entry.tags) entry = res.entries[2] assert_equal(3, entry.id) assert_equal("entry2-1", entry.name) assert_equal("This is entry 2-1.", entry.description) assert_equal(Time.parse("2008-10-05 00:18:41").to_datetime, entry.created_at) assert_equal(Time.parse("2008-10-05 00:21:33").to_datetime, entry.updated_at) assert_equal("bar", entry.username) assert_equal("5678", entry.password) assert_equal(false, entry.expiration) assert_equal("", entry.hostname) assert_equal(["folder2"], entry.tags) entry = res.entries[3] assert_equal(4, entry.id) assert_equal("entry 2-2-1", entry.name) assert_equal("This is entry 2-2-1.", entry.description) assert_equal(Time.parse("2008-10-05 00:22:00").to_datetime, entry.created_at) assert_equal(Time.parse("2008-10-05 00:22:00").to_datetime, entry.updated_at) assert_equal("", entry.username) assert_equal("", entry.password) assert_equal(false, entry.expiration) assert_equal("", entry.hostname) assert_equal(["folder2", "folder2-2"], entry.tags) entry = res.entries[4] assert_equal(5, entry.id) assert_equal("entry3", entry.name) assert_equal("This is entry 3.", entry.description) assert_equal(Time.parse("2008-10-05 00:19:15").to_datetime, entry.created_at) assert_equal(Time.parse("2008-10-05 00:19:15").to_datetime, entry.updated_at) assert_equal("baz", entry.username) assert_equal("9876", entry.password) assert_equal(false, entry.expiration) assert_equal("", entry.hostname) assert_equal([], entry.tags) assert_equal(5, res.entries.length) end private # 本テストで使用する GPass のファイル名を取得する。 # name には gpass_file_test/passwords.gps. より後の部分を指定する。 def gpass_file_path(name) return File.join(File.dirname(__FILE__), "gpass_file_test", "passwords.gps." + name) end end end
require 'sorting_strategy' class CountingSort # Important Characteristics # 1. Must have values between (0, k) where k is larger than every value in the array # 2. Counting sort is extremely fast -- Theta(k + n), O(n) for worst case, best case and average # 3. Uses spaces O(k + n) # 4. Uses spaces O(k + n) # Example: # array = [3, 2, 4, 5, 6, 1] # array = CountingSort.order(array) # puts array # Output: [1, 2, 3, 4, 5, 6] # Example: # array = [3, 2, 4, 5, 6, 1] # array = CountingSort.order(array, :desc => true) # puts array # Output: [6, 5, 4, 3, 2, 1] # # OR # # Example: # array = [3, 2, 4, 5, 6, 1] # instance = CountingSort.new(array) # puts instance.array # Output: [1, 2, 3, 4, 5, 6] # # Example: # array = [3, 2, 4, 5, 6, 1] # instance = CountingSort.new(array, :desc => true) # puts instance.array # Output: [6, 5, 4, 3, 2, 1] # # # ### Get Time Complexity: # Example: # best = CountingSort::TIME_COMPLEXITY_BEST # worst = CountingSort::TIME_COMPLEXITY_WORST # average = CountingSort::TIME_COMPLEXITY_AVERAGE include SortingStrategy TIME_COMPLEXITY_WORST = "O(n)" TIME_COMPLEXITY_AVERAGE = "O(n)" TIME_COMPLEXITY_BEST = "O(n)" SPACE_COMPLEXITY = "O(k+n)" attr_reader :array, :desc, :k # For more on k variable, read on counting sort # k indicates that every number in the container is in the range (0, k) def initialize array, k, desc=false super(array, desc= desc) unless (array.all? {|item| item >= 0 && item < k}) raise "All items in array must be greater than or equal to 0 and less than k" end @array = array @desc = desc @k = k self.sort end def self.order array, k, desc=false instance = CountingSort.new array, k, desc=desc instance.array end protected def sort n = array.length counting_sort array, k end def is_desc? @desc end def counting_sort array, k n = array.length counting_array = Array.new k, 0 for i in 0...n counting_array[array[i]] += 1 end idx = 0 comparison = is_desc? ? ((k-1).downto 0) : 0...k for i in comparison while counting_array[i] > 0 array[idx] = i counting_array[i] -= 1 idx += 1 end end end end
require "test_helper" class Admin::PostsControllerTest < ActionController::TestCase def setup setup_admin_user end def test_index post_1 = FactoryBot.create(:post, created_at: "2020-04-25") post_2 = FactoryBot.create(:post, created_at: "2020-04-26") get :index assert_template "admin/posts/index" assert_primary_keys([post_2, post_1], assigns(:posts)) end def test_show post = FactoryBot.create(:post) get :show, params: { id: post } assert_template "admin/posts/show" assert_equal(post, assigns(:post)) end def test_new get :new assert_template "admin/posts/new" assert_not_nil(assigns(:post)) end def test_create_invalid front_user_1 = FactoryBot.create(:front_user) Post.any_instance.stubs(:valid?).returns(false) post( :create, params: { post: { front_user: front_user_1, title: "The Title Wadus" } } ) assert_template "new" assert_not_nil(flash[:alert]) end def test_create_valid front_user_1 = FactoryBot.create(:front_user) post( :create, params: { post: { front_user_id: front_user_1, title: "The Title Wadus", body: "Wadus Message longer than 20 chars" } } ) post = Post.last assert_redirected_to [:admin, post] assert_equal("The Title Wadus", post.title) assert_equal(front_user_1, post.front_user) end def test_edit post = FactoryBot.create(:post) get :edit, params: { id: post } assert_template "edit" assert_equal(post, assigns(:post)) end def test_update_invalid post = FactoryBot.create(:post) Post.any_instance.stubs(:valid?).returns(false) put( :update, params: { id: post, post: { title: "The Wadus Message New" } } ) assert_template "edit" assert_not_nil(flash[:alert]) end def test_update_valid post = FactoryBot.create(:post) put( :update, params: { id: post, post: { title: "The Wadus Message New" } } ) assert_redirected_to [:admin, post] assert_not_nil(flash[:notice]) post.reload assert_equal("The Wadus Message New", post.title) end def test_destroy post = FactoryBot.create(:post) delete :destroy, params: { id: post } assert_redirected_to :admin_posts assert_not_nil(flash[:notice]) assert !Post.exists?(post.id) end end
class HimaDbDelta < Object #DbDelta = one migration command/one change to the database. require 'rubygems' require 'active_support/inflector' # * Adding a new table # * Removing an old table # * Renaming a table # * Adding a column to an existing table # * Changing a column's type and options # * Removing a column # * Renaming a column # * Adding an index # * Removing an index TableCommands = [:create_table, :rename_table, :drop_table] ColumnCommands = [:add_column, :rename_column, :change_column, :remove_column] IndexCommands = [:add_index, :remove_index] Commands = TableCommands + ColumnCommands + IndexCommands ValidTableOptions = [:table_name, :id, :force, :new_name] ValidColumnOptions = [:column_name, :column_type, :new_name, :new_type, :default, :null, :limit, :precision, :scale] ValidIndexOptions = [:column_name, :index_name, :unique] ValidOptions = ValidTableOptions + ValidColumnOptions + ValidIndexOptions attr_accessor :model_name, :command, :options def initialize self.model_name = "" self.command = nil self.options = {} end def valid? self.model_name != "" && self.model_name.camelize == self.model_name && Commands.include?(self.command) && if TableCommands.include?(self.command) self.options.keys.all? { |key| ValidTableOptions.include?(key)} elsif ColumnCommands.include?(self.command) self.options.key?(:column_name) && self.options.keys.all? { |key| ValidColumnOptions.include?(key)} else #IndexCommands.include?(self.command) self.options.key?(:column_name) && self.options.keys.all? { |key| ValidIndexOptions.include?(key)} end end def clear! self.model_name = "" self.command = nil self.options = {} end def ==(other) self.model_name == other.model_name && self.command == other.command && self.options == other.options end def to_file_text self.expect_valid_self migration_text = self.command.to_s migration_text = migration_text + " :" + self.model_name.tableize case self.command #when create_table: nothing to be done. when :rename_table migration_text = migration_text + ", :" + self.options[:new_name].tableize return migration_text when :drop_table return migration_text when :add_column migration_text = migration_text + ", :#{self.options[:column_name]}, :#{self.options[:column_type]}" when :rename_column migration_text = migration_text + ", :#{self.options[:column_name]}, :#{self.options[:new_name]}" return migration_text when :change_column if self.options.has_key?(:new_type) migration_text = migration_text + ", :#{self.options[:column_name]}, :#{self.options[:new_type]}" else migration_text = migration_text + ", :#{self.options[:column_name]}, :#{self.options[:column_type]}" end when :remove_column migration_text = migration_text + ", :#{self.options[:column_name]}" return migration_text when :add_index migration_text = migration_text + ", :#{self.options[:column_name]}" if self.options.has_key?(:index_name) migration_text = migration_text + ", :name => '#{self.options[:index_name]}'" self.options.delete(:index_name) end when :remove_index migration_text = migration_text + ", :#{self.options[:column_name]}" return migration_text end #:create_table, :add_column, :change_column or :add_index #may have additional options self.options.delete(:column_name) if self.options.key?(:column_name) self.options.delete(:column_type) if self.options.key?(:column_type) self.options.delete(:new_name) if self.options.key?(:new_name) self.options.delete(:new_type) if self.options.key?(:new_type) self.options.keys.each do |key| migration_text = migration_text + ", :" + key.to_s + " => #{self.options[key]}" if ValidOptions.include?(key) end migration_text end def expect_valid_self unless self.valid? raise "Error: cannot write migration for invalid migration command '#{self.command}' with options: '#{self.options}'" end end end
class HbaRule attr_accessor :line_no, :conn_type, :db_name, :user_name, :ip_addr, :net_mask, :auth_type, :comment def initialize args args.each do |k,v| instance_variable_set("@#{k}", v) unless v.nil? end # @conn_type ||= "local" # @user_name ||= "all" # @db_name ||= "all" # @auth_type ||= "md5" # @comment ||= "-" end def to_s "#{@line_no}:#{@conn_type}\t#{@db_name}\t#{@user_name}\t#{@auth_type}" if self.conn_type == "local" "#{@line_no}:#{@conn_type}\t#{@db_name}\t#{@user_name}\t#{@ip_addr}/#{@net_mask}\t#{@auth_type}" end def ==(other) other.class == self.class && other.state == self.state end def state self.instance_variables.map { |variable| self.instance_variable_get variable } end def valid? true false unless [ 'local', 'host', 'hostssl'].include?(:conn_type) end end
require 'spec_helper' describe RedisSet do let(:redis) { Redis.new } let(:name) { "some_set" } let(:set) { described_class.new(name, redis) } before do redis.flushall end context "instance methods" do describe '#all' do subject { set.all } it 'should return all the items in the set' do redis.sadd(name, 'a') redis.sadd(name, 'b') expect(subject).to eq(%w(a b)) end end describe '#size' do subject { set.size } it 'should return the number of items in the set' do redis.sadd(name, 'a') redis.sadd(name, 'b') expect(subject).to eq(2) end end describe '#clear' do subject { set.clear } it 'should remove all of the items in the set' do redis.sadd(name, 'a') redis.sadd(name, 'b') expect(subject).to eq([]) expect(redis.scard name).to eq(0) expect(set.size).to eq(0) end end describe '#include?' do it 'should return true for items in the set, but false otherwise' do redis.sadd(name, 'a') redis.sadd(name, 'b') expect(set.include?('a')).to be true expect(set.include?('b')).to be true expect(set.include?('c')).to be false end end describe '#add' do context 'single adds' do it 'should add items to the set' do expect(set.size).to eq(0) set.add('a') set.add('b') set.add('c') expect(set.size).to eq(3) expect(set.all.sort).to eq(%w(a b c)) end end context 'multiple adds through multiple arguments' do it 'should add items to the set' do expect(set.size).to eq(0) set.add('a', 'b', 'c') expect(set.size).to eq(3) expect(set.all.sort).to eq(%w(a b c)) end end context 'multiple adds through an array' do it 'should add items to the set' do expect(set.size).to eq(0) set.add(['a', 'b', 'c']) expect(set.size).to eq(3) expect(set.all.sort).to eq(%w(a b c)) end end context 'multiple adds through both arrays and multiple arguments' do it 'should add items to the set' do expect(set.size).to eq(0) set.add(['a', 'b', 'c'], 'd', 'e', ['f', 'g'], 'h') expect(set.size).to eq(8) expect(set.all.sort).to eq(%w(a b c d e f g h)) end end end describe '#remove' do it 'should remove a single item from a set' do redis.sadd(name, 'a') redis.sadd(name, 'b') redis.sadd(name, 'c') expect(set.size).to eq(3) set.remove 'b' expect(set.size).to eq(2) expect(set.all.sort).to eq(%w(a c)) end it 'should remove multiple items through multiple arguments' do redis.sadd(name, 'a') redis.sadd(name, 'b') redis.sadd(name, 'c') expect(set.size).to eq(3) set.remove 'b', 'c' expect(set.size).to eq(1) expect(set.all).to eq(%w(a)) end it 'should remove multiple items through an array' do redis.sadd(name, 'a') redis.sadd(name, 'b') redis.sadd(name, 'c') expect(set.size).to eq(3) set.remove ['b', 'c'] expect(set.size).to eq(1) expect(set.all).to eq(%w(a)) end it 'should remove multiple items through both multiple arguments and arrays' do redis.sadd(name, 'a') redis.sadd(name, 'b') redis.sadd(name, 'c') redis.sadd(name, 'd') redis.sadd(name, 'e') redis.sadd(name, 'f') expect(set.size).to eq(6) set.remove ['b', 'c'], 'e' expect(set.size).to eq(3) expect(set.all.sort).to eq(%w(a d f)) end end describe '#pop' do it 'should pop a single item from the set' do redis.sadd(name, 'a') redis.sadd(name, 'b') redis.sadd(name, 'c') popped = set.pop.first expect(%w(a b c)).to include(popped) expect(set.size).to eq(2) expect(set.all.sort).to eq(%w(a b c) - [popped]) end end describe '#pop' do it 'should pop multiple items from the set' do redis.sadd(name, 'a') redis.sadd(name, 'b') redis.sadd(name, 'c') popped = set.pop(2) expect(popped.size).to eq(2) expect(%w(a b c)).to include(popped.first) expect(%w(a b c)).to include(popped.last) expect(set.size).to eq(1) expect(set.all.sort).to eq(%w(a b c) - popped) end end describe '#intersection' do let(:name2){"#{name}2"} let(:name3){"#{name}3"} it 'should return the intersection between multiple sets' do redis.sadd(name, 'a') redis.sadd(name, 'b') redis.sadd(name, 'c') redis.sadd(name, 'd') redis.sadd(name2, 'b') redis.sadd(name2, 'c') redis.sadd(name2, 'd') redis.sadd(name3, 'b') redis.sadd(name3, 'c') expect(set.intersection(name2, name3).sort).to eq(%w(b c)) expect(set.intersection(RedisSet.new(name2), RedisSet.new(name3)).sort).to eq(%w(b c)) expect(set.intersection(name2, RedisSet.new(name3)).sort).to eq(%w(b c)) end end end end
################################### # framework rake tasks # # # # # # rake constants # # ENV['VERSION'] migrate版本号 # # ENV['GGA_ENV'] rake数据库环境 # ################################### # 加载核心模块 require './core/gga' # 加载自定义tasks Dir[File.dirname(__FILE__) + '/tasks/*.rake'].each {|r| import r } # 数据库操作任务 namespace :db do desc "loads database configuration in for other db tasks to run" task :load_config do ActiveRecord::Base.configurations = db_conf GGA_ENV = ((ENV['GGA_ENV'] == 'production') || (ENV['GGA_ENV'] == 'development')) ? ENV['GGA_ENV'] : 'development' # 默认为development # for PostgresSQL # drop and create need to be performed with a connection to the 'postgres' (system) database # ActiveRecord::Base.establish_connection db_conf["production"].merge('database' => 'postgres', # 'schema_search_path' => 'public') # for MySQL ActiveRecord::Base.establish_connection db_conf[GGA_ENV].merge('database' => 'mysql', 'schema_search_path' => 'public') end desc "creates and migrates your database" task :setup => :load_config do Rake::Task["db:create"].invoke Rake::Task["db:migrate"].invoke end desc "migrate your database" task :migrate => :load_config do ActiveRecord::Base.establish_connection db_conf[GGA_ENV] ActiveRecord::Migrator.migrate( ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil ) end desc 'Drops the database' task :drop => :load_config do begin ActiveRecord::Base.connection.drop_database db_conf[GGA_ENV]['database'] rescue puts "Database not exists #{e.message}" end end desc 'Creates the database' task :create => :load_config do begin ActiveRecord::Base.connection.create_database db_conf[GGA_ENV]['database'] rescue => e puts "Database exists #{e.message}" end end end # 系统环境设定任务 desc "Set the enviroment" task :environment do ActiveRecord::Base.configurations = db_conf GGA_ENV = ((ENV['GGA_ENV'] == 'production') || (ENV['GGA_ENV'] == 'development')) ? ENV['GGA_ENV'] : 'development' # 默认为development ActiveRecord::Base.establish_connection db_conf[GGA_ENV] end # 读取数据库配置文件 def db_conf config = YAML.load(ERB.new(File.read('config/database.yml')).result) end
class CreateUserLyrics < ActiveRecord::Migration[5.2] def change create_table :user_lyrics do |t| t.integer :user_id t.integer :lyric_id t.boolean :correct t.timestamps end end end
#!/home/takehiko/.rbenv/shims/ruby require "pg" class Response_To_Csv def initialize @csv_a = [] @csv_a << ["typed_char", "time1", "time2", "response_id", "question_id", "student_id", "start_at", "miss_count"] end def start connect_and_inquire make_table save_csv("response.csv") puts "save as response.csv" end def connect_and_inquire @conn = PG.connect(host: "localhost", port: 25432, user: "postgres", dbname: "postgres") @res = @conn.exec("select * from response where start_at >= '2020-01-27 00:00:00'") end def make_table @res.each_row do |row| # [response_id, student_id, question_id, start_at, finish_at, miss_count, note].nilまたは文字列 puts row.inspect response_id, student_id, question_id, start_at, finish_at, miss_count, note = row next if finish_at.nil? @csv_a << [""] * 3 + [response_id, question_id, student_id, start_at.sub(/\..*$/, ""), miss_count] @csv_a += note_to_row(note) end end def save_csv(filename = "response.csv") open(filename, "w") do |f_out| f_out.print @csv_a.map { |line| line.join(",") }.join("\r\n") + "\r\n" end end def note_to_row(note) # "66x,5.455;6Fx,0.114;72x,0.16;42S,0.479;42S,0.175;42S,0.194;69,0.432;66,0.095;28,0.337;6E,0.608;75,0.081;6D,0.222;62,0.258;65,0.067;72,0.203;3E,0.367;30,0.786;53PC,0.241;29,0.353;7B,0.96;52ET,0.238;70,0.704;72,0.16;69,0.128;6E,0.082;74,0.08;66,0.224;28,0.369;22,0.142;25,0.944;64,0.305;5C,0.147;6E,0.898;22,0.219;2C,0.238;53PC,0.529;6E,0.415;75,0.081;6D,0.19;62,0.227;65,0.065;72,0.206;29,0.288;3B,0.382;52ET,0.353;7D,0.367" # "069,7.811;066,0.149;027x,0.257;028x,0.017;042S,0.879;042S,0.144;028,0.761;06E,0.472;075,0.119;06D,0.168;062,0.52;065,0.152;072,0.104;03E,1;030,1.16;029,0.999;07B,0.777;070,1.623;072,0.144;069,0.128;06E,0.216;074,0.424;066,0.512;028,0.367;022,1.2;025,3.976;064,1.056;05C,1.224;06E,0.32;022,0.952;02C,0.904;06E,0.904;075,0.144;06D,0.144;062,0.24;065,0.136;072,0.096;029,0.984;03B,0.784;07D,1.48" # return eval(note) if /^\[\[/ =~ note # puts "DEBUG: note=#{note}" result_a = [] note_a = note.split(/;/) t_last = 0.0 note_a.each { |item| c, t = item.split(/,/) c.sub!(/^0/, "") c1 = c[0, 2].to_i(16).chr c2 = c[2..-1] || "" # c1 == "+", c2 == "x"のとき,c3 = "x+" # (Excelで「+x」のみのセルを作ることができないため, # 打ち間違いは先頭文字を「x」にする) if c2 == "x" c3 = '"' + c2 + (c1 == '"' ? (c1 + c1) : c1) + '"' else c3 = '"' + (c1 == '"' ? (c1 + c1) : c1) + c2 + '"' end # 打ち込むべき文字の経過時間 if c2.empty? t2 = "%.3f" % [t_last + t.to_f] t_last = 0.0 else t2 = nil t_last += t.to_f end # puts "DEBUG: c=#{c}, t=#{t}; c1=#{c1}, c2=#{c2}, c3=#{c3}" result_a << (t2 ? [c3, t, t2] : [c3, t]) } result_a end end if __FILE__ == $0 Response_To_Csv.new.start end
class Api::StoriesController < ApplicationController def index @stories = Story.includes(:author).all render :index end def show @story = Story.includes(:author).find(params[:id]) render :show end def create @story = Story.new(story_params) @story.author_id = current_user.id @story.date = Time.now if @story.save render :show else render json: @story.errors.full_messages, status: 422 end end def update @story = Story.find(params[:story][:id]) # @user = User.find(@story.author_id) if @story.update(story_params) render :show else render json: @story.errors.full_messages, status: 422 end end def destroy @story = Story.find(params[:id]) @story.destroy @stories = Story.includes(:author).all render :index end private def story_params params.require(:story).permit(:title, :body, :photo) end end
# frozen_string_literal: true class People < SitePrism::Section set_default_search_arguments '.people' element :headline, 'h2' element :dinosaur, '.dinosaur' # doesn't exist on the page elements :individuals, '.person' elements :optioned_individuals, 'span', class: 'person' # should not be found here element :welcome_message_on_the_parent, 'span.welcome' end
module Mirrors # A specific mirror for a class, that includes all the capabilites # and information we can gather about classes. # # @!attribute [rw] singleton_instance # @return [Mirror,nil] if a singleton class, the corresponding # instance. class ClassMirror < ObjectMirror # We are careful to not call methods directly on +@reflectee+ here, since # people really like to override weird methods on their classes. Instead we # borrow the methods from +Module+, +Kernel+, or +Class+ directly and bind # them to the reflectee. # # We don't need to be nearly as careful about this with +Method+ or # +UnboundMethod+ objects, since their +@reflectee+s are two core classes, # not an arbitrary user class. attr_accessor :singleton_instance def initialize(obj) super(obj) @field_mirrors = {} @method_mirrors = {} end # @return [Boolean] Is this a Class, as opposed to a Module? def class? reflectee_is_a?(Class) end # @return [PackageMirror] the "package" into which this class/module has # been sorted. def package @package ||= PackageInference.infer_from(self) end # The source files this class is defined and/or extended in. # # @return [Array<FileMirror>] def source_files instance_methods.map(&:file).compact.uniq end # @return [Boolean] Is the reflectee is a singleton class? def singleton_class? n = name # #<Class:0x1234deadbeefcafe> is an anonymous class. # #<Class:A> is the singleton class of A # #<Class:#<Class:0x1234deadbeefcafe>> is the singleton class of an # anonymous class n.match(/^\#<Class:.*>$/) && !n.match(/^\#<Class:0x\h+>$/) end # @return [Boolean] Is this an anonymous class or module? def anonymous? name.match(/^\#<(Class|Module):0x\h+>$/) end # @!group Instance Methods: Fields # The constants defined within this class. This includes nested # classes and modules, but also all other kinds of constants. # # @return [Array<FieldMirror>] def constants field_mirrors(reflectee_send_from_module(:constants)) end # Searches for the named constant in the mirrored namespace. May # include a colon (::) separated constant path. # # @return [ClassMirror, nil] the requested constant, or nil def constant(str) path = str.to_s.split('::') c = path[0..-2].inject(@reflectee) do |klass, s| Mirrors.rebind(Module, klass, :const_get).call(s) end owner = c || @reflectee # NameError if constant doesn't exist. Mirrors.rebind(Module, owner, :const_get).call(path.last) field_mirror(owner, path.last) rescue NameError nil end # All constants, class vars, and class instance vars. # @return [Array<FieldMirror>] def fields [constants, class_variables, class_instance_variables].flatten end # The known class variables. # @return [Array<FieldMirror>] def class_variables field_mirrors(reflectee_send_from_module(:class_variables)) end # The known class instance variables. # @return [Array<FieldMirror>] def class_instance_variables field_mirrors(reflectee_send_from_module(:instance_variables)) end # @!endgroup (Fields) # @!group Instance Methods: Methods # @return [Array<MethodMirror>] The instance methods of this class. def class_methods singleton_class.instance_methods end # The instance methods of this class. To get to the class methods, # ask the #singleton_class for its methods. # # @return [Array<MethodMirror>] def instance_methods mirrors(all_instance_methods(@reflectee)) end # The instance method of this class or any of its superclasses # that has the specified name # # @param [Symbol] name of the method to look up # @return [MethodMirror, nil] the method or nil, if none was found # @raise [NameError] if the module isn't present def instance_method(name) Mirrors.reflect(reflectee_send_from_module(:instance_method, name)) end # The singleton/static method of this class or any of its superclasses # that has the specified name # # @param [Symbol] name of the method to look up # @return [MethodMirror, nil] the method or nil, if none was found # @raise [NameError] if the module isn't present def class_method(name) singleton_class.instance_method(name) end # This will probably prevent confusion alias_method :__methods, :methods undef methods alias_method :__method, :method undef method # @!endgroup (Methods) # @!group Instance Methods: Related Classes # @return [Array<ClassMirror>] The mixins included in the ancestors of this # class. def mixins mirrors(reflectee_send_from_module(:ancestors).reject { |m| m.is_a?(Class) }) end # @return [Array<ClassMirror>] The full module nesting. def nesting ary = [] reflectee_send_from_module(:name).split('::').inject(Object) do |klass, str| ary << Mirrors.rebind(Module, klass, :const_get).call(str) ary.last end ary.reverse.map { |n| Mirrors.reflect(n) } rescue NameError [self] end # @return [Array<ClassMirror>] The classes nested within the reflectee. def nested_classes nc = reflectee_send_from_module(:constants).map do |c| # do not trigger autoloads if reflectee_send_from_module(:const_defined?, c) && !reflectee_send_from_module(:autoload?, c) reflectee_send_from_module(:const_get, c) end end consts = nc.compact.select do |c| Mirrors.rebind(Kernel, c, :is_a?).call(Module) end mirrors(consts.sort_by { |c| Mirrors.rebind(Module, c, :name).call }) end # @return [ClassMirror] The direct superclass def superclass Mirrors.reflect(reflectee_superclass) end # @return [Array<ClassMirror>] The known subclasses def subclasses mirrors(ObjectSpace.each_object(Class).select { |a| a.superclass == @reflectee }) end # @return [Array<ClassMirror>] The list of ancestors def ancestors mirrors(reflectee_send_from_module(:ancestors)) end # @!endgroup (Related Classes) # What is the primary defining file for this class/module? # This is necessarily best-effort but it will be right in simple cases. # # @return [String, nil] the path on disk to the file, if determinable. def file(resolver = PackageInference::ClassToFileResolver.new) f = resolver.resolve(self) f ? Mirrors.reflect(FileMirror::File.new(f)) : nil end # @example # Mirrors.reflect(A::B).name #=> "A::B" # Mirrors.reflect(Module.new).name #=> "#<Module:0x007fd22902d9d0>" # @return [String] the default +#inspect+ of this class def name # +name+ itself is blank for anonymous/singleton classes @name ||= reflectee_send_from_module(:inspect) end # @return [String] the last component in the module nesting of the name. # @example # Mirrors.reflect(A::B::C).demodulized_name #=> "C" def demodulized_name name.split('::').last end # Cache a {MethodMirror} related to this {ClassMirror} in order to prevent # generating garbage each time methods are returned. Idempotent. # # @param [MethodMirror] mirror the mirror to be interned # @return [MethodMirror] the interned mirror. If already interned, the # previous version. def intern_method_mirror(mirror) @method_mirrors[mirror.name] ||= mirror end # Cache a {FieldMirror} related to this {ClassMirror} in order to prevent # generating garbage each time fields are returned. Idempotent. # # @param [FieldMirror] mirror the mirror to be interned # @return [FieldMirror] the interned mirror. If already interned, the # previous version. def intern_field_mirror(mirror) @field_mirrors[mirror.name] ||= mirror end private # This one is not defined on Module since it only applies to classes def reflectee_superclass Mirrors.rebind(Class.singleton_class, @reflectee, :superclass).call end def reflectee_send_from_module(message, *args) Mirrors.rebind(Module, @reflectee, message).call(*args) end def all_instance_methods(mod) pub_prot_names = Mirrors.rebind(Module, mod, :instance_methods).call(false) priv_names = Mirrors.rebind(Module, mod, :private_instance_methods).call(false) (pub_prot_names.sort + priv_names.sort).map do |n| Mirrors.rebind(Module, mod, :instance_method).call(n) end end end end
class CreateVimCommands < ActiveRecord::Migration def change create_table :vim_commands do |t| t.string :mode_id t.string :command t.string :description t.timestamps end add_index :vim_commands, [:mode_id, :command], :unique end end
# == Schema Information # # Table name: onb_line_users # # id :bigint not null, primary key # line_uid :string # display_name :string # picture_url :string # status_message :string # language :string # archived :boolean default(FALSE) # blocked_channel_at :datetime # created_at :datetime not null # updated_at :datetime not null # class OnbLineUser < ApplicationRecord validates :line_uid, presence: true validates :display_name, presence: true validates :user_id, uniqueness: true end
class Product < ActiveRecord::Base validates :title, :description, presence: true validates :price, numericality: { greater_than: 0 } validate :title_is_shorter_than_description validate :title_downcase def title_is_shorter_than_description return if title.blank? or description.blank? if title.length > description.length errors.add(:title, "title is shorter than description") end end def title_downcase return if self.title.blank? self.title = self.title.downcase end end
# @param {Integer[]} target # @param {Integer[]} arr # @return {Boolean} def can_be_equal(target, arr) t_map = Hash.new(){0} target.each do |i| t_map[i] += 1 end a_map = Hash.new(){0} arr.each do |i| a_map[i] += 1 end t_map.keys.each do |k| return false if t_map[k] != a_map[k] end true end target = [3,7,9] arr = [3,7,11] p can_be_equal(target, arr)
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :customer_href has_many :owner_rentals, :class_name => 'Rental', :foreign_key => 'owner_id' has_many :buyer_rentals, :class_name => 'Rental', :foreign_key => 'buyer_id' has_many :listings has_many :bank_accounts has_many :payment_cards def vgs_bank_account return bank_accounts.first unless self.bank_accounts.nil? end def vgs_payment_card return payment_cards.first unless self.payment_cards.nil? end def vgs_customer self end end
module FormHelpers include ActivityHelper def fill_in_actual_form(expectations: true, value: "1000.01", financial_quarter: "4", financial_year: "2019-2020", comment: nil, receiving_organisation: OpenStruct.new(name: "Example receiver", reference: "GB-COH-123", type: "Private Sector")) fill_in "Actual amount", with: value choose financial_quarter, name: "actual_form[financial_quarter]" select financial_year, from: "Financial year" fill_in "Receiving organisation name", with: receiving_organisation.name select receiving_organisation.type, from: "Receiving organisation type" if receiving_organisation.type.present? fill_in "IATI Reference (optional)", with: receiving_organisation.reference fill_in "Comment", with: comment if comment click_on(t("default.button.submit")) if expectations within ".actuals" do start_year = financial_year.split("-").first.to_i expect(page).to have_content(FinancialQuarter.new(start_year, financial_quarter).to_s) expect(page).to have_content(ActionController::Base.helpers.number_to_currency(value, unit: "£")) expect(page).to have_content(receiving_organisation.name) end end end def fill_in_forecast_form( financial_quarter: "Q2", financial_year: "2020-2021", value: "100000" ) choose financial_quarter select financial_year, from: "Financial year" fill_in "forecast[value]", with: value click_on(t("default.button.submit")) end def fill_in_forecast_form_for_activity(activity) report = Report.editable_for_activity(activity) year = report.financial_year fill_in_forecast_form( financial_quarter: "Q#{report.financial_quarter}", financial_year: "#{year + 1}-#{year + 2}" ) end def fill_in_transfer_form(type:, destination: create(:project_activity), source: create(:project_activity), financial_quarter: FinancialQuarter.for_date(Date.today).to_i, financial_year: FinancialYear.for_date(Date.today).to_i, value: 1234, beis_identifier: nil) transfer = build( type, destination: destination, source: source, financial_quarter: financial_quarter, financial_year: financial_year, value: value ) if type == "outgoing_transfer" fill_in "outgoing_transfer[destination_roda_identifier]", with: transfer.destination.roda_identifier else fill_in "incoming_transfer[source_roda_identifier]", with: transfer.source.roda_identifier end fill_in "#{type}[beis_identifier]", with: beis_identifier if beis_identifier choose transfer.financial_quarter.to_s, name: "#{type}[financial_quarter]" select transfer.financial_year, from: "#{type}[financial_year]" fill_in "#{type}[value]", with: transfer.value transfer end def fill_in_matched_effort_form(template = build(:matched_effort)) select template.organisation.name, from: "matched_effort[organisation_id]" page.find(:xpath, "//input[@value='#{template.funding_type}']").set(true) page.find(:xpath, "//input[@value='#{template.category}']").set(true) fill_in "matched_effort[committed_amount]", with: template.committed_amount within "#matched-effort-currency-field" do find("option[value='#{template.currency}']").select_option end fill_in "matched_effort[exchange_rate]", with: template.exchange_rate fill_in "matched_effort[date_of_exchange_rate(3i)]", with: template.date_of_exchange_rate.day fill_in "matched_effort[date_of_exchange_rate(2i)]", with: template.date_of_exchange_rate.month fill_in "matched_effort[date_of_exchange_rate(1i)]", with: template.date_of_exchange_rate.year fill_in "matched_effort[notes]", with: template.notes click_on t("default.button.submit") end def fill_in_external_income_form(template = build(:external_income)) current_year = FinancialYear.new(Date.today.year).to_s page.find(:xpath, "//input[@value='#{template.financial_quarter}']").set(true) select current_year, from: "external_income[financial_year]" select template.organisation.name, from: "external_income[organisation_id]" fill_in "external_income[amount]", with: template.amount check "external_income[oda_funding]" if template.oda_funding uncheck "external_income[oda_funding]" unless template.oda_funding click_on t("default.button.submit") end end
class WeathersController < ApplicationController before_action :find_weather, only: [:update] def create @weather = Weather.create!(weather_params) render json: @weather end def update @weather.update(weather_params) if @weather.save render json: @weather, status: :accepted else render json: { errors: @weather.errors.full_messages }, status: :unprocessible_entity end end private def weather_params params.require(:weather).permit(:condition, :temperature, :sub_condition, :sub_id) end def find_weather @weather = Item.find(params[:id]) end end
# frozen_string_literal: true module ActiveInteractor # The ActiveInteractor version # @return [String] the ActiveInteractor version VERSION = '1.0.4' end
FactoryGirl.define do factory :user do password "password" password_confirmation "password" role "normal" end factory :alice, :parent => :user do login_name "alice" end end
# spec/support/models/army.rb require 'active_model/sleeping_king_studios/validations/relations' class Army include ActiveModel::Validations include ActiveModel::SleepingKingStudios::Validations::Relations attr_accessor :general def soldiers @soldiers ||= [] end # method soldiers attr_writer :soldiers validates_related_records :general validates_related_records :soldiers parse_relation_error_messages end # class
module Api module V1 class OrgsController < Api::V1::ApiController before_action :set_org, only: [:agents_info] def agents_info json = @org.to_json(only: [:id, :name, :slug], include: {agents: { only: [:id, :name, :slug] }}) respond_to do |format| if current_user.org_id == @org.id format.json { render json: json} else format.json { render json: [], status: :unauthorized } end end end private # Use callbacks to share common setup or constraints between actions. def set_org @org = Org.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def org_params params.require(:org).permit(:name, :slug) end end end end
# encoding: UTF-8 require 'test_helper' class SessionsControllerTest < ActionController::TestCase setup do @client = Client.create name: "John", email: "john@gmail.com", password: 'tre543%$#', password_confirmation: 'tre543%$#' end test "should get new" do get :new assert_response :success assert_select "form" do assert_select "[action=?]", sessions_path assert_select "input[name=?]", "client[email]" assert_select "input[name=?]", "client[password]" assert_select "input[type=submit]" end end test "should fail" do post :create, client: {email: "wrong", password: "wrong"} assert_redirected_to new_session_path assert_equal flash[:notice], "Usuário ou senha inválidos" end test "should succeed" do post :create, client: {email: "john@gmail.com", password: "tre543%$#"} assert_redirected_to root_path assert_equal session[:client_id], @client.id end end
require 'pry' require_relative 'battle.rb' # Class one raper class Raper attr_reader :name def initialize(name, list = []) @name = name @battles = list end def bad_words @bad_words = @battles.sum(&:bad_words_count) end def all_words @all_words = @battles.sum(&:sum_all_words) end def sum_battles @battles.count end def bad_words_in_battle bad_words / sum_battles end def words_in_raund all_words / sum_battles / 3 end end
# frozen_string_literal: true require './method.rb' RSpec.describe Enumerable do ar1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] describe '#my_select' do it 'should return the elements that passes the test' do expect(ar1.my_select { |x| x > 3 }).to eql([4, 5, 6, 7, 8, 9]) end it 'should return the multiple of 3' do expect(ar1.my_select { |x| x % 3 == 0 }).to eql([3, 6, 9]) end it 'should return all the integer' do expect(ar1.my_select { |x| x.is_a?(Integer) }).to eql(ar1) end end describe '#my_all?' do it 'should return false if the all the element are not greater than 5' do expect(ar1.my_all? { |x| x > 5 }).to eql(false) end it 'should return true if the word in an array has 3 letters' do expect(%w[ant bear cat].my_all? { |word| word.length >= 3 }).to eql(true) end it 'should return true if the word in the array has a letter t' do expect(%w[ant bear cat].my_all?(/t/)).to eql(false) end it 'should return if all the elements in the array are numeric' do expect([1, 2i, 3.14].my_all?(Numeric)).to eql(true) end it 'should return true if all the elements in the array return true' do expect([nil, true, 99].my_all?).to eql(false) end it 'should return false if array is empty' do expect([].my_all?).to eql(true) end end describe '#my_any?' do it 'should return true if any element in the array has 3 letters' do expect(%w[ant bear cat].my_any? { |word| word.length >= 3 }).to eql(true) end it 'should return true if any element in the array has a letter d' do expect(%w[ant bear cat].my_any?(/d/)).to eql(false) end it 'should return if any element in the array is an Integer' do expect([nil, true, 99].my_any?(Integer)).to eql(true) end it 'should return true if any element in the array return true' do expect([nil, true, 99].my_any?).to eql(true) end it 'should return false if the array is empty' do expect([].my_any?).to eql(false) end end describe '#my_none?' do it 'should return true if no element in the array has 5 letters' do expect(%w[ant bear cat].my_none? { |word| word.length == 5 }).to eql(true) end it 'should return true if no element in the array has a letter d' do expect(%w[ant bear cat].my_none?(/d/)).to eql(true) end it 'should return true if all the elements in the array are Integers' do expect([1, 3.14, 42].my_none?(Float)).to eql(false) end it 'should return true if array is empty' do expect([].my_none?).to eql(true) end end describe '#my_count' do it 'should return the number of element in the array' do expect(ar1.my_count).to eql(9) end it 'should return the number of element wich are multiple of 3' do expect(ar1.my_count { |x| x % 3 == 0 }).to eql(3) end it 'should return the number of 3 in the array' do expect(ar1.my_count(3)).to eql(1) end end describe '#my_inject' do it 'should return the sum of all elements' do expect((5..10).my_inject(:+)).to eql(45) end it 'should multiply the elemets of the array' do expect((5..10).my_inject(1, :*)).to eql(151_200) end it 'should add all the elements of the array starting by 5' do expect((5..10).my_inject(5) { |x, y| x + y }).to eql(50) end it 'should return the longest word in the array' do expect(%w[cat sheep bear].my_inject do |memo, word| memo.length > word.length ? memo : word end).to eql('sheep') end end end
# frozen_string_literal: true require 'traject' require_relative 'cover_images.macro' extend FindIt::Macros::CoverImages require_relative 'lbcc_format.macro' require_relative 'wikidata_enrichment.macro' extend FindIt::Macros::WikidataEnrichment to_field 'thumbnail_path_ss', cover_image to_field 'id', extract_marc('001', first: true) to_field 'record_provider_facet', literal('LBCC Evergreen Catalog') to_field 'record_source_facet', literal('LBCC Library Catalog') to_field 'is_electronic_facet' do |record, accumulator| field852s = record.find_all { |f| f.tag == '852' } field852s.each do |field| library = field['b'] accumulator << case library when 'LBCCHOC' 'Healthcare Occupations Center' when 'LBCCBC' 'Benton Center' when 'LBCCLIB' 'Albany Campus Library' when 'LBCC' 'Online' else 'Partner Libraries' end end end to_field 'format', FindIt::Macros::LBCCFormats.lbcc_formats, default('Book') to_field 'owning_lib_facet', extract_marc('852b') to_field 'url_fulltext_display', extract_marc('856|40|u') to_field 'professor_t', extract_marc('971a') to_field 'course_t', extract_marc('972a') to_field 'authority_data_t', keywords_from_wikidata
module Refinery module PageResources include ActiveSupport::Configurable config_accessor :captions config_accessor :captions, :attach_to self.captions = true self.attach_to = [ { :engine => 'Refinery::Page', :tab => 'Refinery::Pages::Tab' } ] end end
=begin #Location API #Geolocation, Geocoding and Maps OpenAPI spec version: 2.0.0 Generated by: https://openapi-generator.tech OpenAPI Generator version: 3.3.4 =end require 'date' module unwiredClient # You can send 1 to 7 cell ID objects. If your device supports scanning for more than 7 cell objects, reach out to us and we’ll increase this limit on your account. The first cell object has to be that of the serving cell, i.e. the tower the device is connected to. The others are neighbouring cell objects that are visible to the device. Except lac and cid all other parameters mentioned below are optional. Parameters vary depending on the radio type. Supported radio types and their corresponding parameters are class CellSchema # the Location Area Code of your operator’s network. attr_accessor :lac # Cell ID attr_accessor :cid attr_accessor :radio # \"Mobile Country Code of your operator’s network represented by an integer (Optional). Range: 0 to 999.\" attr_accessor :mcc # Mobile Network Code of your operator’s network represented by an integer (Optional). Range: 0 to 999. On CDMA, provide the System ID or SID, with range: 1 to 32767. attr_accessor :mnc # Signal Strength (RSSI) attr_accessor :signal # Primary Scrambling Code attr_accessor :psc # Arbitrary Strength Unit attr_accessor :asu # Timing Advance attr_accessor :ta # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'lac' => :'lac', :'cid' => :'cid', :'radio' => :'radio', :'mcc' => :'mcc', :'mnc' => :'mnc', :'signal' => :'signal', :'psc' => :'psc', :'asu' => :'asu', :'ta' => :'ta' } end # Attribute type mapping. def self.openapi_types { :'lac' => :'Integer', :'cid' => :'Integer', :'radio' => :'RadioSchema', :'mcc' => :'Integer', :'mnc' => :'Integer', :'signal' => :'Integer', :'psc' => :'Integer', :'asu' => :'Integer', :'ta' => :'Integer' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } if attributes.has_key?(:'lac') self.lac = attributes[:'lac'] end if attributes.has_key?(:'cid') self.cid = attributes[:'cid'] end if attributes.has_key?(:'radio') self.radio = attributes[:'radio'] end if attributes.has_key?(:'mcc') self.mcc = attributes[:'mcc'] end if attributes.has_key?(:'mnc') self.mnc = attributes[:'mnc'] end if attributes.has_key?(:'signal') self.signal = attributes[:'signal'] end if attributes.has_key?(:'psc') self.psc = attributes[:'psc'] end if attributes.has_key?(:'asu') self.asu = attributes[:'asu'] end if attributes.has_key?(:'ta') self.ta = attributes[:'ta'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new if !@lac.nil? && @lac > 65533 invalid_properties.push('invalid value for "lac", must be smaller than or equal to 65533.') end if !@lac.nil? && @lac < 1 invalid_properties.push('invalid value for "lac", must be greater than or equal to 1.') end if !@cid.nil? && @cid > 268435455 invalid_properties.push('invalid value for "cid", must be smaller than or equal to 268435455.') end if !@cid.nil? && @cid < 0 invalid_properties.push('invalid value for "cid", must be greater than or equal to 0.') end if !@signal.nil? && @signal > -25 invalid_properties.push('invalid value for "signal", must be smaller than or equal to -25.') end if !@signal.nil? && @signal < -121 invalid_properties.push('invalid value for "signal", must be greater than or equal to -121.') end if !@psc.nil? && @psc > 503 invalid_properties.push('invalid value for "psc", must be smaller than or equal to 503.') end if !@psc.nil? && @psc < 0 invalid_properties.push('invalid value for "psc", must be greater than or equal to 0.') end if !@asu.nil? && @asu > 97 invalid_properties.push('invalid value for "asu", must be smaller than or equal to 97.') end if !@asu.nil? && @asu < -5 invalid_properties.push('invalid value for "asu", must be greater than or equal to -5.') end if !@ta.nil? && @ta > 63 invalid_properties.push('invalid value for "ta", must be smaller than or equal to 63.') end if !@ta.nil? && @ta < 0 invalid_properties.push('invalid value for "ta", must be greater than or equal to 0.') end invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return false if !@lac.nil? && @lac > 65533 return false if !@lac.nil? && @lac < 1 return false if !@cid.nil? && @cid > 268435455 return false if !@cid.nil? && @cid < 0 return false if !@signal.nil? && @signal > -25 return false if !@signal.nil? && @signal < -121 return false if !@psc.nil? && @psc > 503 return false if !@psc.nil? && @psc < 0 return false if !@asu.nil? && @asu > 97 return false if !@asu.nil? && @asu < -5 return false if !@ta.nil? && @ta > 63 return false if !@ta.nil? && @ta < 0 true end # Custom attribute writer method with validation # @param [Object] lac Value to be assigned def lac=(lac) if !lac.nil? && lac > 65533 fail ArgumentError, 'invalid value for "lac", must be smaller than or equal to 65533.' end if !lac.nil? && lac < 1 fail ArgumentError, 'invalid value for "lac", must be greater than or equal to 1.' end @lac = lac end # Custom attribute writer method with validation # @param [Object] cid Value to be assigned def cid=(cid) if !cid.nil? && cid > 268435455 fail ArgumentError, 'invalid value for "cid", must be smaller than or equal to 268435455.' end if !cid.nil? && cid < 0 fail ArgumentError, 'invalid value for "cid", must be greater than or equal to 0.' end @cid = cid end # Custom attribute writer method with validation # @param [Object] signal Value to be assigned def signal=(signal) if !signal.nil? && signal > -25 fail ArgumentError, 'invalid value for "signal", must be smaller than or equal to -25.' end if !signal.nil? && signal < -121 fail ArgumentError, 'invalid value for "signal", must be greater than or equal to -121.' end @signal = signal end # Custom attribute writer method with validation # @param [Object] psc Value to be assigned def psc=(psc) if !psc.nil? && psc > 503 fail ArgumentError, 'invalid value for "psc", must be smaller than or equal to 503.' end if !psc.nil? && psc < 0 fail ArgumentError, 'invalid value for "psc", must be greater than or equal to 0.' end @psc = psc end # Custom attribute writer method with validation # @param [Object] asu Value to be assigned def asu=(asu) if !asu.nil? && asu > 97 fail ArgumentError, 'invalid value for "asu", must be smaller than or equal to 97.' end if !asu.nil? && asu < -5 fail ArgumentError, 'invalid value for "asu", must be greater than or equal to -5.' end @asu = asu end # Custom attribute writer method with validation # @param [Object] ta Value to be assigned def ta=(ta) if !ta.nil? && ta > 63 fail ArgumentError, 'invalid value for "ta", must be smaller than or equal to 63.' end if !ta.nil? && ta < 0 fail ArgumentError, 'invalid value for "ta", must be greater than or equal to 0.' end @ta = ta end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && lac == o.lac && cid == o.cid && radio == o.radio && mcc == o.mcc && mnc == o.mnc && signal == o.signal && psc == o.psc && asu == o.asu && ta == o.ta end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [lac, cid, radio, mcc, mnc, signal, psc, asu, ta].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = unwiredClient.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
# encoding: UTF-8 class Film class Scenes # Path du fichier contenant la liste des brins colllectés def collecte_file @collecte_file ||= File.join(film.collecte.folder, 'scenes.collecte') end end #/Scenes end #/Film
require 'rails_helper' RSpec.describe CoursesController, :type => :controller do before do @user = FactoryGirl.create :user sign_in @user end describe "GET index" do context 'params query' do it 'return http success' do get :index, query: "Hehe" expect(response).to have_http_status(:success) end end context 'no params search' do it "returns http success" do get :index expect(response).to have_http_status(:success) end end end describe "GET new" do it 'have success response' do get :new expect(response).to have_http_status(:success) end end describe "POST create" do context 'valid' do it 'creates course' do expect do post :create, course: { name: "12345", description: "aa", password: "123456a" } end.to change(Course, :count).by(1).and( change(Attending, :count).by(1) ) c = Course.first expect(c.private).to eq false expect(c.password).to eq '123456a' expect(c.description).to eq 'aa' expect(response).to redirect_to course_path(1) end end context 'invalid' do it 'renders new' do expect do post :create, course: { name: "", description: "aaa", password: "123456" } end.not_to change(Course, :count) expect(response).to render_template :new end end end describe "GET show" do before do FactoryGirl.create :course Attending.create(course_id: 1, user_id: 1) end it "returns http success" do get :show, id: 1 expect(response).to have_http_status(:success) end it "updates attending's last_visited" do a = spy(Attending.new) allow(Attending).to receive(:where) { a } expect(a).to receive(:update_last_visit).once get :show, id: 1 end end describe 'GET settings' do before do FactoryGirl.create :course Attending.create(course_id: 1, user_id: 1, role: 2) end it "returns http success" do get :settings, id: 1 expect(response).to have_http_status(:success) end end describe 'POST update' do before do FactoryGirl.create :course Attending.create(course_id: 1, user_id: 1, role: 2) end context 'valid params' do it "updates course" do post :update, id: 1, course: { name: "Just a name", description: "Kta" } expect(Course.first.name).to eq "Just a name" expect(Course.first.description).to eq "Kta" end end context 'valid params' do it "renders edit" do post :update, id: 1, course: { name: "", description: "Kta" } expect(response).to render_template :settings end end end describe "DELETE destroy" do before do FactoryGirl.create :course Attending.create(course_id: 1, user_id: 1, role: 2) end context 'correct name' do it 'removes course' do expect do delete :destroy, id: 1, course: { name: Course.first.name } end.to change(Course, :count).by(-1) expect(response).to redirect_to root_path end end context 'incorrect name' do it 'does not remove course' do expect do delete :destroy, id: 1, course: { name: Course.first.name + "1" } end.not_to change(Course, :count) expect(response).to redirect_to settings_course_path(1) end end end describe "POST update_attending" do before do FactoryGirl.create :course Attending.create(course_id: 1, user_id: 1, role: 2) FactoryGirl.create :user, email: "p@p.com" Attending.create(course_id: 1, user_id: 2, role: 1) end context 'own attending' do it 'does not update_attending' do post :update_attending, id: 1, attending: { role: 0, user_id: 1 } expect(Attending.first.role).not_to eq "member" end end context 'updating of other user' do it "updates_attending" do post :update_attending, id: 1, attending: { role: 0, user_id: 2 } expect(Attending.second.role).to eq "member" end end end describe 'POST send_invitation' do before do FactoryGirl.create :course Attending.create(course_id: 1, user_id: 1, role: 1) end context 'new email' do it 'sends invitation' do message = spy expect(InvitationMailer).to receive(:invite) { message } expect(message).to receive :deliver_later post :send_invitation, id: 1, invitation: { email: 'bronislaw@gmail.com' } end end context 'existing email' do it 'does not send invitation' do post :send_invitation, id: 1, invitation: { email: User.first.email } expect(InvitationMailer).not_to receive(:invite) end end end describe "GET add_user" do before do FactoryGirl.create(:course) end context 'already course member' do before do Attending.create(user_id: 1, course_id: 1) end it 'redirects to show' do get :add_user, id: 1 expect(response).to redirect_to course_path(1) end end context 'blank password' do it 'adds user to course' do expect do get :add_user, id: 1 end.to change(Attending, :count).by(1) expect(response).to redirect_to course_path(1) end end context 'password' do before do Course.first.update_attribute(:password, "123456") end it 'renders form' do get :add_user, id: 1 expect(response).to have_http_status 200 end end end describe "POST check_password" do before do FactoryGirl.create(:course, password: "123456") end context 'correct password' do it 'adds user to course' do expect do post :check_password, id: 1, course: { password: "123456" } end.to change(Attending, :count).by(1) expect(response).to redirect_to course_path(1) end end context 'incorrect passowrd' do it 'renders form' do post :check_password, id: 1, course: { password: "1" } expect(response).to render_template :add_user end end end describe "GET remove_user" do before do FactoryGirl.create :course Attending.create(course_id: 1, role: 2, user_id: 1) FactoryGirl.create :user, email: "kk@kk.com" Attending.create(user_id: 2, course_id: 1) end context 'other user' do it 'removes user from course' do expect do get :remove_user, id: 1, user_id: 2 end.to change(Attending, :count).by(-1) expect(response).to redirect_to settings_course_path(1) end end context 'same user' do it 'does not remove user from course' do expect do get :remove_user, id: 1, user_id: 1 end.not_to change(Attending, :count) expect(response).to redirect_to settings_course_path(1) end end end describe 'GET toggle_flag' do before do FactoryGirl.create :course FactoryGirl.create :lesson_category Attending.create(course_id: 1, role: 1, user_id: 1) end it 'toggles lesson category flag' do flag = LessonCategory.first.flagged get :toggle_flag, id: 1, lesson_category_id: 1 expect(LessonCategory.first.flagged).to eq !flag end end describe 'GET remove_self' do before do FactoryGirl.create :course FactoryGirl.create :lesson_category Attending.create(course_id: 1, role: 0, user_id: 1) end it 'removes user from course' do expect do get :remove_self, id: 1 end.to change(Attending, :count).by(-1) expect(response).to redirect_to root_path end end #describe 'GET exam' do #before do #FactoryGirl.create :course #Attending.create(course_id: 1, user_id: 1) #FactoryGirl.create :lesson_category #FactoryGirl.create :exam #end #it "returns http success" do #get :exam, id: 1, exam_id: 1 #expect(response).to have_http_status(:success) #end #end end
class CreateSubchurches < ActiveRecord::Migration def change create_table :subchurches do |t| t.string :subchurch_name t.string :subchurch_address t.integer :subchurch_phone_no t.integer :id_no t.timestamps end end end
namespace :scheduler do desc "Import all trials from clinicaltrials.gov" task :import_trials_from_clinicaltrials_gov => :environment do TrialsImporter.new.import RestClient.get(cronitor_url) end def cronitor_url "https://cronitor.link/#{ENV.fetch("CLINICALTRIALS_SYNC_CRONITOR_ID")}/complete" end end
class Room < ActiveRecord::Base belongs_to :floor belongs_to :roomtype has_many :polygons, as: :imageable, dependent: :destroy # поиск def self.search(params) # result = Order.includes(:tariff, {:automobile => :drivers}).references(:tariff, {:automobile => :drivers}) result = Room.all if params['room_name'].present? result = result.where(name: params['room_name']) end if params['room_roomtype'].present? result = result.where(roomtype_id: params['room_roomtype']) end if params['room_capacity_from'].present? result = result.where.not(capacity: 0...params['room_capacity_from'].to_i) end if params['room_capacity_to'].present? result = result.where(capacity: 0..params['room_capacity_to'].to_i) end result.all end end
class OZBPerson < ActiveRecord::Base set_table_name "OZBPerson" set_primary_key :mnr # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :mnr, :ueberPnr, :email, :password, :password_confirmation, :remember_me, :passwort, :pwAendDatum, :gesperrt, :canEditA, :canEditB, :canEditC, :canEditD # A: OZBPersonenverwaltung, B: Kontenverwaltung, C: Veranstaltung und Teilnahmeverwaltung, # D:Tabellen (Veranstaltung, Kontoklassen, Projektgruppen) has_one :Mitglied, :foreign_key => :mnr, :dependent => :destroy # Done, getestet has_one :Student, :foreign_key => :mnr, :dependent => :destroy # Done, ungetestet has_one :BuchungOnline, :foreign_key => :mnr, :dependent => :destroy # Done, getestet has_many :OZBKonto, :foreign_key => :mnr, :dependent => :delete_all # Done, getestet has_many :Tanliste, :foreign_key => :mnr, :dependent => :delete_all # Done, getestet has_one :Gesellschafter, :foreign_key => :mnr, :dependent => :destroy # Done, getestet belongs_to :Person, :foreign_key => :pnr # Done, getestet has_many :Buergschaft, :foreign_key => :mnrG, :dependent => :delete_all # Done, getestet end
require "google/cloud/language" require "googleauth" class Api::V1::PostsController < ApplicationController # skip_before_action :authenticate def index @posts = Post.all.reverse post_data = @posts.each_with_object([]) do |post, new_array| new_array << {id: post.id, content: post.content, created_at: post.created_at, user: post.user.name, likes: post.likes.length, user_id: post.user.id} end.sort!{ |x, y| x[:id] <=> y[:id] }.reverse render json: post_data end def create cred_io = StringIO.new(ENV['GOOGLE_APPLICATION_JSON']) Google::Auth::ServiceAccountCredentials.make_creds( scope: 'https://www.googleapis.com/auth/cloud-platform', json_key_io: cred_io ) language = Google::Cloud::Language.new project: ENV['BITTER_PROJECT_ID'] document = language.document params[:user][:content] sentiment = document.sentiment if sentiment.score < 0 post = Post.new(user: current_user, content: params[:user][:content]) if post.save render json: post else render json: {error: "couldn't post for some reason"}, status: :unauthorized end else render json: {error: "you need to be more negative than that", sentiment_score: sentiment.score}, status: :unauthorized end end def like_post @post = Post.find(params[:id]) current_user.like(@post) post_likes = Like.where(post_id: @post.id).length render json: {id: @post.id, content: @post.content, created_at: @post.created_at, user: @post.user.name, likes: post_likes} end def load_post_likes @post = Post.find(params[:id]) post_likes = Like.where(post_id: @post.id).length render json: {id: @post.id, likes: post_likes} end end
Fabricator(:hotel) do name { Faker::Company.name } address { Faker::Address.street_address } star_rating { rand(1..5) } accomodation_type { "hostel" } end
require_relative 'command.rb' module DBP::BookCompiler::TexToMarkdown class DoNothing include Command def initialize(name) @name = name end def to_s "#{self.class}(#{name})" end end end
require 'line/bot' require 'net/http' require 'uri' require 'rexml/document' class LinebotController < ApplicationController protect_from_forgery except: ['callback'] def callback message = { type: 'text', text: 'Hello, This is LINE bot' } client = Line::Bot::Client.new do |config| config.channel_secret = ENV['LINE_CHANNEL_SECRET'] config.channel_token = ENV['LINE_CHANNEL_TOKEN'] end puts events = client.parse_events_from(request.body.read) events.each do |event| case event when Line::Bot::Event::Message case event.type when Line::Bot::Event::MessageType::Text keyword_reply = KeywordReply.fetch(event['message']['text']) if !keyword_reply.nil? message['text'] = keyword_reply.reply_word elsif event['message']['text'].include?('とは') target_word = event['message']['text'].sub(/とは/, '') message['text'] = search_word(target_word) elsif event['message']['text'].include?(ENV['BOT_NAME']) target_word = event['message']['text'].sub(ENV['BOT_NAME'], '') message['text'] = talk_bot(target_word) else case event['message']['text'] when '天気' message['text'] = fetch_weather when 'アニメ一覧' target_season = DateUtil.detect_target_season message['text'] = fetch_anime(target_season) when 'こんにちは' message['text'] = greet(client, event['source']['userId']) when 'ポエム' message['text'] = PoemUtil.select_poem else return end end response = client.reply_message(event['replyToken'], message) p response.body end end end end def fetch_weather response = Weather.fetch if response.code == '200' return Weather.parse_msg(response.body) else return Weather.error_msg(response) end end def fetch_anime(target_season) response = Annict.fetch(target_season) if response.code == '200' return Annict.parse_msg(response.body) else return Annict.error_msg(response) end end def talk_bot(message) response = A3rt.talk(message) body = JSON.parse(response.body) if body['status'] == 0 return body['results'][0]['reply'] else return body['message'] end end def search_word(target_word) uri_path = "http://wikipedia.simpleapi.net/api?keyword=#{target_word}&output=json" response = NetUtil.http_request(uri_path, false) if response.code == '200' content = JSON.parse(response.body) result = "【#{content[0]['title']}】\n" result += content[0]['body'] else puts 'ERROR' end end def greet(client, userId) resProfile = client.get_profile(userId) case resProfile when Net::HTTPSuccess then contact = JSON.parse(resProfile.body) p contact['displayName'] + contact['pictureUrl'] + contact['statusMessage'] return "#{contact['displayName']}さん こんにちは♪" else return "#{resProfile.code} #{resProfile.body}" end end end
class Task < ActiveRecord::Base belongs_to :project validates_presence_of :title, :due_date, :is_completed, :project_id end
require 'csv' require 'json' module Bb10Cli module Cli class App desc 'lsvolumes', 'Lists all the mountable volumes on the BB10 device' def lsvolumes run_command do |bb| response = bb.do_command('Status', path: '/cgi-bin/dynamicProperties.cgi', 'Attribute' => 'DeviceVolumes') bb_resp = response['RimTabletResponse']['DynamicProperties'] json = {} case bb_resp['Status'] when 'Success' json['volumes'] = {} bb_resp['DeviceVolumes']['Volume'].each do |vol| json['volumes'][vol['id']] = { "StorageType" => vol['StorageType'], "ContentType" => vol['ContentType'], "Credentials" => vol['SambaConfiguration']['Credentials'], "Path" => vol['SambaConfiguration']['Path'] } end json['result'] = 'success' else json['result'] = 'failure' end puts JSON.generate(json, JSON_OPTS) end end end end end
class CommentsController < ApplicationController skip_before_filter :verify_authenticity_token def index @comments = current_user.comments end def new @comment = Comment.new end def create @comment = Comment.new(comment_params) @comment.user_id = current_user.id @comment.status = "nouveau" if @comment.save flash[:success] = "Votre avis a bien été envoyé!" redirect_to comments_path else render "new" end end private def comment_params params.require(:comment).permit(:content, :title, :user_id, :status) end end
class RemoveImageUrlFromBookmarks < ActiveRecord::Migration def up remove_column :bookmarks, :image_url end def down add_column :bookmarks, :image_url, :string end end
require 'sqlite3' namespace :users do namespace :mumble do desc 'Generate and export mumble passwords' task :export => :environment do db = SQLite3::Database.new("/var/lib/mumble-server/mumble-server.sqlite") db.prepare("INSERT OR IGNORE INTO users (server_id, name, pw, player_id) VALUES (1, :name, :password, (SELECT MAX(rowid) FROM users))") do |stmt| User.active.find_each(:batch_size => 50) do |user| user.create_mumble unless user.mumble stmt.execute(:name => user.login, :password => user.mumble.password_sha1) end end end end end
require "aethyr/core/actions/commands/reply" require "aethyr/core/actions/commands/tell" require "aethyr/core/registry" require "aethyr/core/input_handlers/command_handler" module Aethyr module Core module Commands module Tell class TellHandler < Aethyr::Extend::CommandHandler def self.create_help_entries help_entries = [] command = "tell" see_also = ["SAY", "SAYTO", "WHISPER", "REPLY"] syntax_formats = ["TELL [player] [message]"] aliases = nil content = <<'EOF' All inhabitants of Aethyr have the ability to communicate privately with each other over long distances. This is done through the TELL command. Those who investigate these kinds of things claim there is some kind of latent telepathy in all of us. However, while no one knows for certain how it works, everyone knows it does. Example: TELL Justin Hey, how's it going? EOF help_entries.push(Aethyr::Core::Help::HelpEntry.new(command, content: content, syntax_formats: syntax_formats, see_also: see_also, aliases: aliases)) command = "reply" see_also = ["TELL"] syntax_formats = ["REPLY [message]"] aliases = nil content = <<'EOF' Reply is a shortcut to send a tell to the last person who sent you a tell. EOF help_entries.push(Aethyr::Core::Help::HelpEntry.new(command, content: content, syntax_formats: syntax_formats, see_also: see_also, aliases: aliases)) return help_entries end def initialize(player) super(player, ["tell", "reply"], help_entries: TellHandler.create_help_entries) end def self.object_added(data) super(data, self) end def player_input(data) super(data) case data[:input] when /^tell\s+(\w+)\s+(.*)$/i $manager.submit_action(Aethyr::Core::Actions::Tell::TellCommand.new(@player, {:target => $1, :message => $2 })) when /^reply\s+(.*)$/i $manager.submit_action(Aethyr::Core::Actions::Reply::ReplyCommand.new(@player, {:message => $1 })) end end private #Tells someone something. end Aethyr::Extend::HandlerRegistry.register_handler(TellHandler) end end end end
require_relative '../test_helper' class ConfirmationsControllerTest < ActionController::TestCase def setup super @controller = Api::V1::ConfirmationsController.new @request.env["devise.mapping"] = Devise.mappings[:api_user] end test "should not confirm account if client host is not recognized" do u = create_user confirm: false get :show, params: { confirmation_token: u.confirmation_token, client_host: 'http://anotherhost:3333' } assert_response 400 assert_nil u.reload.confirmed_at end test "should not confirm account if token is invalid" do u = create_user confirm: false get :show, params: { confirmation_token: u.confirmation_token.reverse, client_host: CheckConfig.get('checkdesk_client') } assert_redirected_to "#{CheckConfig.get('checkdesk_client')}/check/user/confirm/unconfirmed" assert_nil u.reload.confirmed_at end test "should redirect to already confirmed page if user is valid" do u = create_user assert_not_nil u.reload.confirmed_at get :show, params: { confirmation_token: u.confirmation_token, client_host: CheckConfig.get('checkdesk_client') } assert_redirected_to "#{CheckConfig.get('checkdesk_client')}/check/user/confirm/already-confirmed" end test "should confirm account" do u = create_user confirm: false get :show, params: { confirmation_token: u.confirmation_token, client_host: CheckConfig.get('checkdesk_client') } assert_redirected_to "#{CheckConfig.get('checkdesk_client')}/check/user/confirm/confirmed" assert_not_nil u.reload.confirmed_at end test "should confirm account for new user" do u1 = create_user confirm: false User.current = User.new assert_nothing_raised do get :show, params: { confirmation_token: u1.confirmation_token, client_host: 'http://test.localhost:3333' } end User.current = nil end end
class CreateJoinTableProjectTool < ActiveRecord::Migration[5.1] def change create_join_table :projects, :tools end end
#!/usr/bin/env ruby require_relative '../lib/studio_game/game' require_relative '../lib/studio_game/clumsy_player' require_relative '../lib/studio_game/berzerk_player' knuckleheads = StudioGame::Game.new("Knuckleheads") default_player_file = File.join(File.dirname(__FILE__), 'players.csv') knuckleheads.load_players(ARGV.shift || default_player_file) klutz = StudioGame::ClumsyPlayer.new("klutz", 105) knuckleheads.add_player(klutz) berzerker = StudioGame::BerzerkPlayer.new("berzerker", 50) knuckleheads.add_player(berzerker) loop do puts "\nHow many game rounds? ('quit' to exit)" input = gets.chomp.downcase case input when /^\d+$/ knuckleheads.play(input.to_i) when 'quit', 'q', 'exit' knuckleheads.print_stats break else puts "Expected a number of rounds or quit" end end knuckleheads.save_high_scores
module Wait def self.until(timeout: nil, timeout_message:nil) wait_params = {message: timeout_message} wait_params[:timeout] = timeout if timeout # default timeout is 5 seconds Selenium::WebDriver::Wait.new(message: timeout_message).until { yield } end end
class Campaign < ActiveRecord::Base has_many :keywords, dependent: :destroy validates :name, presence: true def self.data_proccesing(yad_list) # все айди из ответа яндекса yad_ids = yad_list.map{ |c| c['Id'] } # удаляем не нужные where.not(id: yad_ids).destroy_all if yad_ids.any? # обновляем существующие exists_ids = all.pluck(:id) update_old(exists_ids, yad_list) if exists_ids.any? # добавляем отсутсвующие new_ids = yad_ids - exists_ids return unless new_ids.any? new_ids.each do |id| data = get_campaigns_hash_from_list(yad_list, id) create!(id: id, name: data['Name']) end end private def self.update_old(exists_ids, yad_list) exists_ids.each do |id| data = get_campaigns_hash_from_list(yad_list, id) find(id).update(name: data['Name']) if data end end def self.get_campaigns_hash_from_list(list, requred_id) list.select{ |c| c['Id'] == requred_id }.first end end
class Task include Mongoid::Document include Mongoid::Timestamps field :task_name field :due_date field :assigned_to field :task_type field :lead_for_task validates_presence_of :task_type, :task_name, :assigned_to, :due_date, :lead_for_task belongs_to :user DUE_DATES = [['Overdue','overdue'],['Asap', 'asap'],['Today', 'today'],['Tomorrow', 'tomorrow'],['This week', 'this_week'],['Next week','next_week'],['Sometime later','sometime_later']] TASK_TYPES = [['Call','call'], ['Email','email'], ['Follow-up', 'followup'], ['Meeting', 'meeting']] class << self def due_dates DUE_DATES end def task_type TASK_TYPES end end end
module DiceOfDebt class API resource :errors do desc 'Raise an error.' post do fail 'Internal Server Error' end get do fail 'Internal Server Error' end end helpers do def error(options = {}) error = Error.new(options) status error.status present [error], with: ErrorArrayPresenter nil end end STATUS_CODES = { GameCompleteError => 422 } rescue_from :all do |e| status_code = STATUS_CODES.fetch(e.class, 500) error = API::Error.new(status: status_code, title: e.message, backtrace: e.backtrace) ErrorResponse.build error.status, [error] end rescue_from Grape::Exceptions::ValidationErrors do |e| errors = e.map do |attributes, error| message = e.send(:full_message, attributes, error) Error.new(status: 422, title: message, source: { parameter: attributes.join(',') }) end ErrorResponse.build 422, errors end class Error attr_reader :status, :title, :detail, :source, :backtrace def initialize(opts = {}) @status = opts[:status] || 500 @title = opts[:title] || Rack::Utils::HTTP_STATUS_CODES[status] @detail = opts[:detail] || title @source = opts[:source] @backtrace = opts[:backtrace] end end module ErrorPresenter include Representer property :status, getter: -> _ { status.to_s } property :title property :detail property :source property :backtrace if ENV['RACK_ENV'] != 'production' end module ErrorArrayPresenter include Representer collection :entries, as: 'errors', extend: ErrorPresenter, embedded: true end module ErrorResponse def self.build(status, errors) headers = { 'Content-Type' => JSON_API_CONTENT_TYPE } [status, headers, [ErrorArrayPresenter.represent(errors).to_json]] end end end end
# frozen_string_literal: true module Dynflow module ExecutionPlan::Steps class AbstractFlowStep < Abstract # Method called when initializing the step to customize the behavior based on the # action definition during the planning phase def update_from_action(action) @queue = action.queue @queue ||= action.triggering_action.queue if action.triggering_action @queue ||= :default end def execute(*args) return self if [:skipped, :success].include? self.state open_action do |action| with_meta_calculation(action) do action.execute(*args) @delayed_events = action.delayed_events end end end def clone self.class.from_hash(to_hash, execution_plan_id, world) end private def open_action action = persistence.load_action(self) yield action persistence.save_action(execution_plan_id, action) persistence.save_output_chunks(execution_plan_id, action.id, action.pending_output_chunks) save return self end end end end
def Caesar(string, shift) lower = ('a'..'z').to_a.rotate(shift) upper = ('A'..'Z').to_a.rotate(shift) alphabet = lower.concat(upper).join string.tr!('a-zA-Z', alphabet) end p "Enter text to cipher" input = gets.chomp if ! /[a-zA-Z]/.match(input).nil? p "You have entered " + input + " as your text to cipher" else abort("Please have at least one letter to cipher") end p "Enter shift amount (integer)" key = gets.chomp p "You have set your shift amount to " + key p "Your Caesar Ciphered Text is: " puts Caesar(input.to_s, key.to_i)
#!/usr/bin/env ruby require 'timeout' require 'date' module PolyComp class Sign DefaultBaud = 1200 TTYFlags = 'raw -parenb cstopb' BroadcastAddr = 0 DefaultLines = 2 DefaultWidth = 16 HeaderStart = 0.chr HeaderEnd = 3.chr EndOfText = 4.chr ACK = 6 AckTimeout = 10 # seconds module SerSt Base = 0b11000000 Interrupt = 0b00000010 MorePages = 0b00000100 AckWanted = 0b00001000 SchedMode = 0b00010000 end module WeeklyStatus Base = 0b10000000 Monday = 0b00000001 Tuesday = 0b00000010 Wednesday = 0b00000100 Thursday = 0b00001000 Friday = 0b00010000 Saturday = 0b00100000 Sunday = 0b01000000 end module Tempo Base = 0b11000000 Timer = 0b00000000 AlwaysOn = 0b00100000 AlwaysOff = 0b00010000 def self.duration(n) n.to_i & 0xf end end module Function Base = 0b11000000 Time = 0b00010000 Temp = 0b00100000 def self.transition(n) n.to_i & 0xf end end module PageStatus Base = 0b10000000 Join12 = 0b00000001 Join34 = 0b00000010 Join56 = 0b00000100 Join78 = 0b00001000 Center = 0b00010000 Foreign = 0b00100000 Invert = 0b01000000 end def self.open(tty, options = {}) # TODO use a serial port library stty_str = '' begin stty_str = setup_serial(tty, (options[:baud] || DefaultBaud)) yield Sign.new(File.open(tty, 'w+'), options) ensure teardown_serial(tty, stty_str) end nil end def reset @pageno = 1 end def set_clock(time = nil) time ||= Time.now body = (SerSt::Base | SerSt::AckWanted | SerSt::MorePages).chr body += '000' body += time.strftime '%H%M%S%d%m0' body += (time.wday + 1).to_s transmit(body) end def page(line1, line2 = nil, options = {}) if line2.kind_of? Hash options = line2 line2 = nil end join = options[:join] join = true if join.nil? and line2.nil? raise 'Cannot join when two lines are given' if join and line2 transition = options[:transition] || Transitions::Auto duration = options[:duration] || 3 message = '' if line1 == :time or line1 == :temp message += ' ' * @width else line1_length = line1.gsub(Markup::Matcher, '').length if join message += line1 transition = Transitions::Slide if line1_length > @joined_width elsif line1_length > @width raise "Line 1 is limited to #{@width} characters" elsif options[:center] and ! options[:join] # FIXME - deal with markup message += line1.center(@width, ' ') else message += line1 + ' ' * (@width - line1_length) end end if line2 unless line2.kind_of? String raise 'Time/temperature not allowed on second line' end message += line2 line2_length = line2.gsub(Markup::Matcher, '').length transition = Transitions::Slide if line2_length > @width end serst = SerSt::Base | SerSt::AckWanted serst |= SerSt::MorePages unless options[:last] body = serst.chr body += ('%03d' % @pageno) body += (Tempo::Base | Tempo::duration(duration) | Tempo::AlwaysOn).chr function = Function::Base | Function::transition(transition) function |= Function::Time if line1 == :time function |= Function::Temp if line1 == :temp body += function.chr status = PageStatus::Base status |= PageStatus::Join12 if join status |= PageStatus::Center if options[:center] status |= PageStatus::Invert if options[:invert] body += status.chr body += message unless line1 == :time or line1 == :temp transmit(body) @pageno += 1 end protected def transmit(body) packet = HeaderStart + @lines.chr + @address.chr + HeaderEnd + body + EndOfText checksum = 0 packet.each_byte do |byte| checksum ^= byte end packet += checksum.chr @conn.print packet @conn.flush Timeout.timeout(AckTimeout) do unless (b = @conn.getc) == ACK raise "Did not receive ACK from the PolyComp sign. (got #{b})" end end end def self.setup_serial(filename, baud) old = `stty -F #{filename} -g`.chomp `stty -F #{filename} #{baud} #{TTYFlags}` sleep 0.5 return old end def self.teardown_serial(filename, stty_str) `stty -F #{filename} #{stty_str}`.chomp end def initialize(conn, options = {}) @conn = conn @width = options[:width] || DefaultWidth @lines = options[:lines] || DefaultLines @address = options[:address] || BroadcastAddr @joined_width = options[:joined_width] || (@width / 2) reset set_clock end end module Transitions Auto = 0x0 Appear = 0x1 Wipe = 0x2 Open = 0x3 Lock = 0x4 Rotate = 0x5 Right = 0x6 Left = 0x7 RollUp = 0x8 RollDown = 0x9 PingPong = 0xa FillUp = 0xb Paint = 0xc FadeIn = 0xd Jump = 0xe Slide = 0xf end module Markup Flash = "\x1cF" Bold = "\x1cE" Red = "\x1cR" Green = "\x1cG" Yellow = "\x1cY" Rainbow = "\x1cM" Default = "\x1cD" Matcher = /\x1c./ end end if $0 == __FILE__ # Note: All parameters in the hash argument to Sign.open are optional PolyComp::Sign.open('/dev/ttyS0', :baud => 1200, :width => 16, :lines => 2) do |sign| # Display 'Hello World' on two lines, using a random transition # and a specific duration sign.page 'HELLO', 'WORLD', :center => true, :duration => 4 # Display the current time on two lines # Duration defaults to something reasonable if not specified sign.page :time, :center => true # Use a specific transition sign.page 'PING PONG', :transition => PolyComp::Transitions::PingPong # Using markup to make it fancy (NB: this is not perfectly supported yet) sign.page "THIS IS #{PolyComp::Markup::Bold}BOLD#{PolyComp::Markup::Default}", "THIS IS #{PolyComp::Markup::Flash}FLASHING" # This is the last page; by saying so the sign starts displaying the new # pages right away, instead of waiting for a 40-second timeout. sign.page 'THE', 'END.', :last => true end end
class Upload < Sequel::Model(WoodEgg::DB) many_to_one :researcher FILEDIR = '/srv/http/uploads/' class << self # NOTE: dataset, not results def missing_info filter(transcription: nil).or(transcription: '').or(notes: nil).or(notes: '').order(:id) end # NOTE: results, not dataset def missing_info_for(researcher_id) missing_info.filter(researcher_id: researcher_id).all end def post_from_researcher(researcher_id, filefield, notes) info = {researcher_id: researcher_id, notes: notes, mime_type: filefield[:type], their_filename: filefield[:filename], our_filename: our_filename_for(researcher_id, filefield[:filename])} fullpath = FILEDIR + info[:our_filename] File.open(fullpath, 'w') do |f| f.write(filefield[:tempfile].read) end info[:bytes] = FileTest.size(fullpath) m = /\s(\d:\d{2}:\d{2})\s/.match `exiftool #{fullpath} | grep ^Duration` if m info[:duration] = m[1] end create(info) end def our_filename_for(researcher_id, their_filename) 'r%03d-%s-%s' % [ researcher_id, Time.now.strftime('%Y%m%d'), their_filename.downcase.gsub(/[^a-z0-9._-]/, '')] end def sync_next u = find(uploaded: 'n') return false if u.nil? u.update(uploaded: 'p') require 'aws/s3' AWS::S3::DEFAULT_HOST.replace 's3-ap-southeast-1.amazonaws.com' AWS::S3::Base.establish_connection!( access_key_id: WoodEgg.config['aws_key'], secret_access_key: WoodEgg.config['aws_secret']) AWS::S3::S3Object.store(u.our_filename, open(FILEDIR + u.our_filename), 'woodegg', {:access => :public_read, :content_type => u.mime_type}) u.update(uploaded: 'y') end end def url 'http://woodegg.s3.amazonaws.com/' + our_filename end def uploaded_status case uploaded when 'n' then 'not uploaded (wait 10 minutes)' when 'p' then 'currently uploading (wait 1 minute)' when 'y' then 'uploaded' end end def missing_info? (String(transcription) == '' || String(notes) == '') end end
require 'json' require 'thor' require 'English' require_relative 'consts' require_relative 'utils/run' require_relative 'utils/log' module Calypso class SimCtl < Thor KEYBOARD_PREFERENCES = { 'bool': { 'KeyboardAllowPaddle': 'NO', 'KeyboardAssistant': 'NO', 'KeyboardAutocapitalization': 'NO', 'KeyboardAutocorrection': 'NO', 'KeyboardCapsLock': 'NO', 'KeyboardCheckSpelling': 'NO', 'KeyboardPeriodShortcut': 'NO', 'KeyboardPrediction': 'NO', 'KeyboardShowPredictionBar': 'NO' } }.freeze desc 'disable_keyboard_magic <udid>', 'Turn offs all the automated keyboard behaviours' def disable_keyboard_magic(simulator_id) KEYBOARD_PREFERENCES.each do |value_type, values| next unless value_type == :bool # others not supported, yet values.each do |key, val| run "defaults write #{preferences_path simulator_id} #{key} -bool #{val}" end end end desc 'create <device_type> <runtime_name> [name]', 'Creates simulator' def create(device_type, runtime_name, name = nil) create_simulator(device_type, runtime_name, name) end desc 'repopulate [name]', 'Deletes all simulators and create all of them again if [name] is null or just create [name] if exists' def repopulate(name = nil) repopulate_all_simulators(name) end desc 'delete <udid>', 'Deletes simulator' def delete(udid) delete_simulator(udid) end desc 'list [state]', 'List all simulators' def list(state = nil) device_types_list.each do |runtime, devices| log "** #{runtime} **", color: '1;35' devices.each do |dev| desc = "#{dev['name'].color('1;34')} (#{dev['udid']}), #{dev['state'].color('1')}" next unless state.nil? || /#{state}/i =~ desc log " - #{desc}", color: '0' end end end no_commands do def run_with_simulator(device_name, runtime_name) udid = create_simulator(device_name, runtime_name) open_simulator udid yield udid delete_simulator udid end end private def create_simulator(device_name, runtime_name, name = nil) dev = find_latest_device(device_name) dev_name = dev['name'] dev_id = dev['identifier'] rt = find_latest_runtime(runtime_name) rt_name = rt['name'] rt_id = rt['identifier'] name ||= "Test #{dev_name} / #{rt_name} (#{(rand * 1_000_000).to_i.to_s(16).rjust(10, '0')})" udid = run_simctl('create', "'#{name}'", dev_id, rt_id).strip log_debug "Simulator '#{name}' (#{udid}) created" disable_keyboard_magic(udid) udid end def delete_simulators(name) find_devices(name).each do |dev| delete_simulator dev['udid'] end end def delete_simulator(udid) dev = find_device(udid) shutdown_simulator(udid) unless dev['state'] == 'Shutdown' `killall -9 Simulator 2> /dev/null` run_simctl('delete', udid) log_debug "Simulator #{dev['name']} (#{udid}) deleted" end def boot_simulator(udid) log_debug "Simulator #{udid} booting" run_simctl('boot', udid) end def open_simulator(udid) log_debug "Simulator #{udid} starting" %(open -a "simulator" --args -CurrentDeviceUDID #{udid}) end def shutdown_simulator(udid) log_debug "Simulator #{udid} shutting down" run_simctl('shutdown', udid) end def find_latest_device(name) print "Finding device #{name}... " selected_devices = simulators_list['devicetypes'].select do |dev| dev['name'] =~ /#{name}/i end device = selected_devices.sort_by do |dev| dev['identifier'] end.last log_abort("Device #{name} not found") if device.nil? puts device['name'] device end def find_latest_runtime(name) print "Finding runtime #{name}... " selected_runtimes = simulators_list['runtimes'].select do |rt| rt['name'] =~ /#{name}/ end runtime = selected_runtimes.sort do |lhs, rhs| lhs['version'].to_f <=> rhs['version'].to_f end.last log_abort("Runtime #{name} not found") if runtime.nil? puts runtime['name'] runtime end def repopulate_all_simulators(name = nil) simulators_list['devices'].each do |_, runtime_devices| runtime_devices.each do |device| delete_simulator device['udid'] end end selected_runtimes = if name.nil? available_runtimes else requested_runtimes = available_runtimes.select { |runtime| runtime['name'] == name } log_abort "Error: No runtimes for \"#{name}\" found" if requested_runtimes.empty? requested_runtimes end selected_runtimes.each do |runtime| log "## Populating #{runtime['name']}" simulators_list['devicetypes'].each do |device_type| simulator_name = "#{device_type['name']} (#{runtime['name']})" args = ["'#{simulator_name}'", device_type['identifier'], runtime['identifier']] `xcrun simctl create #{args.join ' '} 2> /dev/null` log_debug "Created #{simulator_name}" if $CHILD_STATUS.success? end end end def find_devices(name) devices_list.select do |dev| dev['name'] =~ name end end def find_device(udid) devices_list.select do |dev| dev['udid'] == udid end.first end def devices_list simulators_list['devices'].zip.flatten end def device_types_list simulators_list['devices'] end def available_runtimes simulators_list['runtimes'].select do |runtime| runtime['availability'] == '(available)' end end def simulators_list JSON.parse run_simctl('list', '-j') end def run_simctl(*args) `xcrun simctl #{args.join ' '}` end def preferences_path(uuid) "~/Library/Developer/CoreSimulator/Devices/#{uuid}/data/Library/Preferences/com.apple.Preferences.plist" end include Log include Run end end
class TipoPontoTuristicosController < ApplicationController before_action :set_tipo_ponto_turistico, only: [:show, :edit, :update, :destroy] # GET /tipo_ponto_turisticos # GET /tipo_ponto_turisticos.json def index @tipo_ponto_turisticos = TipoPontoTuristico.all end # GET /tipo_ponto_turisticos/1 # GET /tipo_ponto_turisticos/1.json def show end # GET /tipo_ponto_turisticos/new def new @tipo_ponto_turistico = TipoPontoTuristico.new end # GET /tipo_ponto_turisticos/1/edit def edit end # POST /tipo_ponto_turisticos # POST /tipo_ponto_turisticos.json def create @tipo_ponto_turistico = TipoPontoTuristico.new(tipo_ponto_turistico_params) respond_to do |format| if @tipo_ponto_turistico.save format.html { redirect_to @tipo_ponto_turistico, notice: 'Tipo ponto turistico was successfully created.' } format.json { render :show, status: :created, location: @tipo_ponto_turistico } else format.html { render :new } format.json { render json: @tipo_ponto_turistico.errors, status: :unprocessable_entity } end end end # PATCH/PUT /tipo_ponto_turisticos/1 # PATCH/PUT /tipo_ponto_turisticos/1.json def update respond_to do |format| if @tipo_ponto_turistico.update(tipo_ponto_turistico_params) format.html { redirect_to @tipo_ponto_turistico, notice: 'Tipo ponto turistico was successfully updated.' } format.json { render :show, status: :ok, location: @tipo_ponto_turistico } else format.html { render :edit } format.json { render json: @tipo_ponto_turistico.errors, status: :unprocessable_entity } end end end # DELETE /tipo_ponto_turisticos/1 # DELETE /tipo_ponto_turisticos/1.json def destroy @tipo_ponto_turistico.destroy respond_to do |format| format.html { redirect_to tipo_ponto_turisticos_url, notice: 'Tipo ponto turistico was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_tipo_ponto_turistico @tipo_ponto_turistico = TipoPontoTuristico.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def tipo_ponto_turistico_params params.require(:tipo_ponto_turistico).permit(:tipo) end end
#!/usr/bin/env ruby require 'json' require 'net/http' require 'yaml' require 'puppet_litmus' require 'etc' require_relative '../lib/task_helper' def provision(platform, inventory_location) include PuppetLitmus::InventoryManipulation uri = URI.parse('https://cinext-abs.delivery.puppetlabs.net/api/v2/request') job_id = "IAC-#{Process.pid}" headers = { 'X-AUTH-TOKEN' => token_from_fogfile('abs'), 'Content-Type' => 'application/json' } payload = { 'resources' => { platform => 1 }, 'priority' => 2, 'job' => { 'id' => job_id, 'tags' => { 'user' => Etc.getlogin, 'jenkins_build_url' => 'https://puppet_litmus' } } } http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.request_uri, headers) request.body = payload.to_json # repeat requests until we get a 200 with a html body reply = http.request(request) raise "Error: #{reply}: #{reply.message}" unless reply.is_a?(Net::HTTPAccepted) # should be a 202 now = Time.now counter = 1 loop do next if Time.now < now + counter reply = http.request(request) break if reply.code == '200' # should be a 200 counter += 1 raise 'Timeout: unable to get a 200 response in 30 seconds' if counter > 30 end data = JSON.parse(reply.body) hostname = data.first['hostname'] if platform_uses_ssh(platform) node = { 'uri' => hostname, 'config' => { 'transport' => 'ssh', 'ssh' => { 'user' => 'root', 'password' => 'Qu@lity!', 'host-key-check' => false } }, 'facts' => { 'provisioner' => 'abs', 'platform' => platform, 'job_id' => job_id } } group_name = 'ssh_nodes' else node = { 'uri' => hostname, 'config' => { 'transport' => 'winrm', 'winrm' => { 'user' => 'Administrator', 'password' => 'Qu@lity!', 'ssl' => false } }, 'facts' => { 'provisioner' => 'abs', 'platform' => platform, 'job_id' => job_id } } group_name = 'winrm_nodes' end inventory_full_path = File.join(inventory_location, 'inventory.yaml') inventory_hash = get_inventory_hash(inventory_full_path) add_node_to_group(inventory_hash, node, group_name) File.open(inventory_full_path, 'w') { |f| f.write inventory_hash.to_yaml } { status: 'ok', node_name: hostname, node: node } end def tear_down(node_name, inventory_location) include PuppetLitmus::InventoryManipulation inventory_full_path = File.join(inventory_location, 'inventory.yaml') if File.file?(inventory_full_path) inventory_hash = inventory_hash_from_inventory_file(inventory_full_path) facts = facts_from_node(inventory_hash, node_name) platform = facts['platform'] job_id = facts['job_id'] end uri = URI.parse('https://cinext-abs.delivery.puppetlabs.net/api/v2/return') headers = { 'X-AUTH-TOKEN' => token_from_fogfile('abs'), 'Content-Type' => 'application/json' } payload = { 'job_id' => job_id, 'hosts' => [{ 'hostname' => node_name, 'type' => platform, 'engine' => 'vmpooler' }] } http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.request_uri, headers) request.body = payload.to_json reply = http.request(request) raise "Error: #{reply}: #{reply.message}" unless reply.code == '200' remove_node(inventory_hash, node_name) puts "Removed #{node_name}" File.open(inventory_full_path, 'w') { |f| f.write inventory_hash.to_yaml } { status: 'ok' } end params = JSON.parse(STDIN.read) platform = params['platform'] action = params['action'] node_name = params['node_name'] inventory_location = sanitise_inventory_location(params['inventory']) raise 'specify a node_name when tearing down' if action == 'tear_down' && node_name.nil? raise 'specify a platform when provisioning' if action == 'provision' && platform.nil? unless node_name.nil? ^ platform.nil? case action when 'tear_down' raise 'specify only a node_name, not platform, when tearing down' when 'provision' raise 'specify only a platform, not node_name, when provisioning' else raise 'specify only one of: node_name, platform' end end begin result = provision(platform, inventory_location) if action == 'provision' result = tear_down(node_name, inventory_location) if action == 'tear_down' puts result.to_json exit 0 rescue => e puts({ _error: { kind: 'facter_task/failure', msg: e.message } }.to_json) exit 1 end
# == Schema Information # # Table name: policy_coverage_status_histories # # id :integer not null, primary key # coverage_effective_date :date # coverage_end_date :date # coverage_status :string # data_source :string # lapse_days :integer # policy_number :integer # policy_type :string # representative_number :integer # created_at :datetime not null # updated_at :datetime not null # policy_calculation_id :integer # representative_id :integer # # Indexes # # index_policy_coverage_status_histories_on_policy_calculation_id (policy_calculation_id) # index_policy_coverage_status_histories_on_representative_id (representative_id) # # Foreign Keys # # fk_rails_... (policy_calculation_id => policy_calculations.id) # fk_rails_... (representative_id => representatives.id) # class PolicyCoverageStatusHistory < ActiveRecord::Base belongs_to :policy_calculation belongs_to :representative def self.update_or_create(attributes) obj = first || new obj.assign_attributes(attributes) obj.save obj end def self.assign_or_new(attributes) obj = first || new obj.assign_attributes(attributes) obj end end
class ApplicationController < ActionController::Base include Pundit # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :authenticate_user! before_action :reset_flash before_action :set_paper_trail_whodunnit layout "application" private def reset_flash flash[:notice] = nil end end
feature 'Creating peeps' do scenario 'I can create a new peep if I am signed in' do sign_up visit '/peeps' fill_in 'text', with: 'Hello world!' click_button 'Create peep' expect(current_path).to eq '/peeps' within 'ol#peeps' do expect(page).to have_content('Hello world!') end end scenario 'I can see name and username on peeps' do sign_up visit '/peeps' fill_in 'text', with: 'Hello world!' click_button 'Create peep' within 'ol#peeps' do expect(page).to have_content('name, or better known as username') end end scenario 'there are no peeps in the database at the start of the test' do expect(Peep.count).to eq 0 end end
# your code goes here class Person attr_accessor :bank_account attr_reader :name, :happiness, :hygiene #happiness and hygiene must be reader methods #because we do not want to allow users to change #those values def initialize(name) @name = name @bank_account = 25 @happiness = 8 @hygiene = 8 end def hygiene=(num) if num > 10 @hygiene = 10 elsif num < 0 @hygiene = 0 else @hygiene = num end end # I don't fully understand why the code below wont work. # Is it because we are writing a customized writer method that # only allows for changes to our @hygiene(instance variable) value #according to a certain set of rules which we define? # def hygiene # if @hygiene > 10 # @hygiene = 10 # elsif @hygiene < 0 # @hygiene = 0 # else # @hygiene = @hygiene # end # end def clean? if @hygiene > 7 return true else return false end end def happiness=(num) if num > 10 @happiness = 10 elsif num < 0 @happiness = 0 else @happiness = num end end def happy? if @happiness > 7 return true else return false end end def get_paid(salary) @bank_account += salary "all about the benjamins" end def take_bath # I peeked at the solution to verify my approach to # building this method. Here's what I learned: #To call an instance method inside of another instance method, # we use the "self" keyword. In this method, "self" refers to #the instance of person the method is being called on. # My original thought was to pass the instance variable @hygiene # as the argument to my hygiene= method, but now I see the flaw # in my logic. hygiene= is not a regular method we can just call whenever # we want. It is an intance method. To call an instance method # one must have an explicit receiver. Now that I have corrected my approach # the instance of self will explicitly receive the #hygiene method self.hygiene += 4 '♪ Rub-a-dub just relaxing in the tub ♫' end def work_out self.hygiene -= 3 # self.hygiene = self.hygiene - 3 #if we are calling the hygiene instance method on self, why don't we have to pass it # an argument to satisfy the num parameter? self.happiness += 2 '♪ another one bites the dust ♫' end def call_friend(person) person.happiness += 3 self.happiness += 3 "Hi #{person.name}! It's #{self.name}. How are you?" end def start_conversation(person, topic) if topic == "politics" # be careful during the code challenge. # Look out for careless mistakes like # forgetting to put wrap politics in # quotes. person.happiness -= 2 self.happiness -= 2 "blah blah partisan blah lobbyist" elsif topic == "weather" person.happiness += 1 self.happiness += 1 "blah blah sun blah rain" else "blah blah blah blah blah" end end end
class Robot attr_reader :name, :city, :state, :birthdate, :date_hired, :department, :id, :photo def initialize(robot) @id = robot[:id] @name = robot[:name] @city = robot[:city] @state = robot[:state] @birthdate = robot[:birthdate] @date_hired = robot[:date_hired] @department = robot[:department] @photo = robot[:photo] end end
def script_tag(index) yield $script_tags_run[index] if block_given? $script_tags_run[index] end def have_run lambda { |obj| !obj.nil? } end def inline lambda { |obj| obj.has_key?(:inline) && obj[:inline] } end def deferred lambda { |obj| obj.has_key?(:defer) && obj[:defer] } end def in_order lambda { |obj| obj == obj.sort } end def typed lambda { |obj| obj.has_key?(:typed) && obj[:typed] } end def get_script(id) System::Windows::Browser:: HtmlPage.document.get_element_by_id(id).get_property('innerHTML').to_s end describe "DLR-based script tags: end-to-end" do it 'runs inline application/ruby tags' do script_tag('inline-ruby') do |obj| obj.should have_run obj.should.be inline obj.should.not.be deferred obj.should.be typed end end it 'runs external script-tags' do script_tag('ext-nodefer') do |obj| obj.should have_run obj.should.not.be inline obj.should.not.be deferred obj.should.be typed end end it 'runs external script-tags without type' do script_tag('ext-notype') do |obj| obj.should have_run obj.should.not.be inline obj.should.not.be deferred obj.should.not.be typed end end it 'runs inline application/x-ruby tags' do script_tag('inline-xruby') do |obj| obj.should have_run obj.should.be inline obj.should.not.be deferred obj.should.be typed end end it 'runs inline text/ruby tags' do script_tag('inline-text-ruby') do |obj| obj.should have_run obj.should.be inline obj.should.not.be deferred obj.should.be typed end end it 'can require external script files with defer=true' do script_tag('ext-defer') do |obj| obj.should have_run obj.should.not.be inline obj.should.be deferred end end it 'run inline script-tags with defer=true on-demand, not at startup' do script_tag('inline-ruby-deferred').should.not have_run eval get_script('deferredInline') script_tag('inline-ruby-deferred') do |obj| obj.should have_run obj.should.be inline obj.should.be deferred end end it 'can call methods defined in other script-tags' do script_tag('method-call-across-tags').should have_run end it 'will not run script tags with a random prefix' do script_tag('random-prefix').should.not have_run end it 'runs scripts in order' do script_tag('in-order-execution').should.be in_order end it 'runs python tags' do script_tag('python') do |obj| obj.should have_run obj.should.be inline obj.should.not.be deferred obj.should.be typed end end end dst = Microsoft::Scripting::Silverlight::DynamicScriptTags describe 'DynamicScriptTags.RemoveMargin' do it 'should not remove any spaces' do test = "a = 1\nb = 2\n" dst.RemoveMargin(test).should == test end it 'does not remove beginning blank lines' do test = "\n\n\n\n\n\na = 1\nb = 2\n" result = "\n\n\n\n\n\na = 1\nb = 2\n" dst.RemoveMargin(test).should == result end it 'should always use \'\\n\' to separate lines' do test = "\na = 1\r\nb = 1\r\n" result = "\na = 1\nb = 1\n" dst.RemoveMargin(test).should == result end it 'should remove the margin equally' do test = "\n a = 1\n def foo()\n print 'hi'\n foo()\n" result = "\na = 1\ndef foo()\n print 'hi'\nfoo()\n" dst.RemoveMargin(test).should == result end it 'should bail on indenting lines which have less margin than the first line' do test = "\n a = 1\n b = 1\ndef foo\n puts 'hi'\n" result = "\n a = 1\n b = 1\ndef foo\n puts 'hi'\n" dst.RemoveMargin(test).should == result end it 'should indent lines at a minimum indent' do test = "\n a = 1\n b = 1\n def foo\n puts 'hi'\n" result = "\n a = 1\n b = 1\ndef foo\n puts 'hi'\n" dst.RemoveMargin(test).should == result end it 'should remove any spaces from a last-spaces-only line' do test = "\n a = 1\n b = 1\n def foo\n puts 'hi'\n " result = "\na = 1\nb = 1\ndef foo\n puts 'hi'\n" dst.RemoveMargin(test).should == result end it 'should not take blank lines into account in margin' do test = "\n a = 1\n\n b = 1\n" result = "\na = 1\n\nb = 1\n" dst.RemoveMargin(test).should == result end end
Pod::Spec.new do |s| s.name = 'isar_flutter_libs' s.version = '1.0.0' s.summary = 'Flutter binaries for the Isar Database. Needs to be included for Flutter apps.' s.homepage = 'https://isar.dev' s.license = { :file => '../LICENSE' } s.author = { 'Isar' => 'hello@isar.dev' } s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.public_header_files = 'Classes/**/*.h' s.static_framework = true s.vendored_libraries = '*.a' s.dependency 'Flutter' s.platform = :ios, '8.0' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' } s.swift_version = '5.0' end
require 'rails_helper' RSpec.feature 'User signs in' do scenario 'tries to access admin dashboard and is redirected with error message' do user = create(:user) visit root_path find('#username-sign-in').set(user.username) find('#password-sign-in').set(user.password) click_button 'Submit' visit admin_root_path expect(current_path).to eq(root_path) expect(page).to have_text('You need admin authentication to access that.') end scenario 'is redirected to their homepage, and can sign out if they choose' do user = create(:user) visit root_path find('#username-sign-in').set(user.username) find('#password-sign-in').set(user.password) click_button 'Submit' expect(current_path).to eq(user_path(user)) expect(page).to have_text("#{user.display_name.titleize}'s Page") click_link 'Sign Out' expect(current_path).to eq(root_path) end end
puts "On va compter le nombre d'heures de travail à THP" # On affiche l'intitulé de l'opération, donc la phrase entre guillement "Travail : #{10 * 5 * 11}" # On affiche "travail :" + le nombre d'heures grâce au calcule heures x jours x mois puts "En minutes ça fait : #{10 * 5 * 11 * 60}" #Idem que pour ligne ci-dessus, mais en minutes, donc heures x jours x mois x 60(minutes) puts "Et en secondes ?" # Affiche le tite entre guillemets puts 10 * 5 * 11 * 60 * 60 # idem, calcule pour les secondes heures x jours x mois x minutes x secondes et affichera le résultat puts "Est-ce que c'est vrai que 3 + 2 < 5 - 7 ?" # affiche l'intitulé puts 3 + 2 < 5 - 7 # fait le calcul et affiche qu'il est faux (false), car 5 n'est pas inférieur à -2 puts "Ça fait combien 3 + 2 ? #{3 + 2}" # affiche l'intitulé puis donne le résultat de la variable puts "Ça fait combien 5 - 7 ? #{5 - 7}" 1 # idem puts "Ok, c'est faux alors !" # affiche la phrase entre guillemets qui dit que la formule 3 + 2 < 5 - 7 est effectivement fausse puts "C'est drôle ça, faisons-en plus :" # affiche la phrase entre guillemets puts "Est-ce que 5 est plus grand que -2 ? #{5 > -2}" # pose une question et son calcul dans la variable, puis affiche son résultat, ici vrai car 5 est en effet supérieur à 2 puts "Est-ce que 5 est supérieur ou égal à -2 ? #{5 >= -2}" # pose une question et son calcul dans la variable, puis affiche son résultat, ici vrai car 5 est en effet supérieur à -2 puts "Est-ce que 5 est inférieur ou égal à -2 ? #{5 <= -2}" # pose une question et son calcul dans la variable, puis affiche son résultat, ici vrai car 5 est en effet supérieur à -2 puts "Est-ce que 5 est inférieur ou égal à -2 ? #{5 <= -2}" # pose une question et son calcul dans la variable, puis affiche son résultat, ici faux car 5 n'est pas en inférieur ou égal à -2
Piccy::Application.routes.draw do resources :pictures root :to => 'pictures#index' end
module Aus module Lunh def self.is_number_valid? number ::Luhn.valid?(number) end def self.encode number "#{number}#{::Luhn.control_digit(number)}" end end end
class AddRefreshAndAccessTokenToUser < ActiveRecord::Migration def change add_column :users, :gg_access_token, :string add_column :users, :gg_refresh_token, :string end end
require_relative "../config/environment.rb" require 'active_support/inflector' class Song self.column_names.each do |col_name| attr_accessor col_name.to_sym end def self.table_name self.to_s.downcase.pluralize #Changes Song to songs for use when creating table end def self.column_names DB[:conn].results_as_hash = true #this causes the values returned from the db to be in #a hash instead of an array, The keys will be the attribute names sql = "pragma table_info('#{table_name}')" #SQL Statement to get an array of hashes describing the table table_info = DB[:conn].execute(sql) column_names = [] #This will be the name of each attribute ##EX hash #{"cid"=> 1, "name" => "album", "type" => "text",...} table_info.each do |row| column_names << row["name"] #column_names stores the attributes needed in the attr_accessor end column_names.compact #This gets rid of nil values in the array end def initialize(options={}) options.each do |property, value| self.send("#{property}=", value) end end def save sql = "INSERT INTO #{table_name_for_insert} (#{col_names_for_insert}) VALUES (#{values_for_insert})" DB[:conn].execute(sql) @id = DB[:conn].execute("SELECT last_insert_rowid() FROM #{table_name_for_insert}")[0][0] end def table_name_for_insert self.class.table_name end def values_for_insert values = [] self.class.column_names.each do |col_name| values << "'#{send(col_name)}'" unless send(col_name).nil? end values.join(", ") end def col_names_for_insert self.class.column_names.delete_if {|col| col == "id"}.join(", ") end def self.find_by_name(name) sql = "SELECT * FROM #{self.table_name} WHERE name = '#{name}'" DB[:conn].execute(sql) end end
class AdressesController < ApplicationController def search_postal_code begin address = get_address render :json => address.to_json rescue SocketError,RuntimeError, Timeout::Error address = {'bairro' => '','cep' => '','cidade' => '','logradouro' => '','tipo_logradouro' => '','uf' => '1'} render :json => address.to_json end end def get_address address = {} address_correios = Correios::CEP::AddressFinder.get(params[:postal_code]) return raise RuntimeError if address_correios.nil? or address_correios.blank? address[:cidade_nome] = address_correios[:city] address[:cidade] = City.find_or_create_by_nome(address_correios[:city], address_correios[:state]).id address[:uf] = State.find_by_symbol(address_correios[:state]).id address[:cep] = address_correios[:zipcode] address[:logradouro] = address_correios[:address] address[:bairro] = address_correios[:neighborhood] address end def get_cities_by_symbol cities = City.from_state_state_symbol(params[:symbol]) render :json => cities.collect{|x| "<option value='#{x.id}'>#{x.name}</option>"}.to_json end end
class Patient < ApplicationRecord has_and_belongs_to_many :physicians, through: :appointment end
require 'rails_helper' describe Profiles::PhotosController do context "when user is not logged in" do before :each do login_with nil @user = create(:user) @profile = create(:profile, user_id: @user.id ) @photo = create(:photo, profile_id: @profile.id) end it "redirect to login page " do get :show, profile_id: @profile, id: @photo expect( response ).to redirect_to(new_user_session_path) end end context "when user is logged in" do before(:each) do @user = create(:user) login_with @user @profile = create(:profile, user_id: @user.id ) end describe "GET #index" do end describe "GET #show" do let(:profile) {create(:profile)} let(:photo) {create(:photo)} it "finds the given profile and photo and assign to @profile and @photo variables" do get :show, profile_id: profile, id: photo expect(assigns(:profile)).to eq (profile) expect(assigns(:photo)).to eq (photo) end it "renders the show view" do get :show, profile_id: profile, id: photo expect(response).to render_template(:show) end end describe "GET #edit" do end describe "PUT #update" do end describe "DELETE #destroy" do end end end
source 'https://rubygems.org' ruby '2.1.1' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.1.1' # Use postgresql as the database for Active Record gem 'pg' # Use SCSS for stylesheets gem 'sass-rails', '~> 4.0.3' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .js.coffee assets and views gem 'coffee-rails', '~> 4.0.0' # Use bourbon for mixins gem 'bourbon' # Allow sorting gem 'acts_as_list' gem 'activeadmin-sortable' # Implements singleton in activerecord gem 'acts_as_singleton' # use paperclip and aws for attachments gem 'paperclip' gem 'aws-sdk' # See https://github.com/sstephenson/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.0' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~> 0.4.0', group: :doc # Redcarpet for markdown rendering gem 'redcarpet' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring', group: :development # Use activeadmin for administration gem 'activeadmin', github: 'gregbell/active_admin' gem 'devise' # modernizr for compatability gem 'modernizr-rails' # respond js for ie8 media query support gem 'respond-rails' #use new relic to tune performance gem 'newrelic_rpm' #use dalli for memcache gem 'dalli' gem 'friendly_id' gem 'route_downcaser', git: "https://github.com/l3akage/route_downcaser" # Rails 4.1 activeadmin dependencies gem 'polyamorous', github: 'activerecord-hackery/polyamorous' gem 'ransack', github: 'activerecord-hackery/ransack' gem 'formtastic', github: 'justinfrench/formtastic' # Use unicorn as the app server gem 'unicorn' gem 'rails_12factor' #add sweepers back in gem 'rails-observers' gem 'activerecord-session_store', github: 'rails/activerecord-session_store'
class Chapel < Formula desc "Programming language for productive parallel computing at scale" homepage "https://chapel-lang.org/" url "https://github.com/chapel-lang/chapel/releases/download/1.25.0/chapel-1.25.0.tar.gz" sha256 "39f43fc6de98e3b1dcee9694fdd4abbfb96cc941eff97bbaa86ee8ad88e9349b" license "Apache-2.0" bottle do sha256 big_sur: "beda2be8596ab9a15e88cbd19c5b0289ab15b88d7f63c56d61bb863137276c7a" sha256 catalina: "f4a653976006f3f5c54b57ebada3527f807af9cbc69713591945fa7003a89927" sha256 mojave: "6be57e2cd756b5cb822bf87ab069bea4915b42c141cda9865b6279c45917c6fb" sha256 x86_64_linux: "9b1816e66d41d06e9be28682a8282c12280e228ed631aad2d97e479f2e006779" end depends_on "llvm@11" depends_on "python@3.9" def install libexec.install Dir["*"] # Chapel uses this ENV to work out where to install. ENV["CHPL_HOME"] = libexec # This is for mason ENV["CHPL_RE2"] = "bundled" # Must be built from within CHPL_HOME to prevent build bugs. # https://github.com/Homebrew/legacy-homebrew/pull/35166 cd libexec do system "./util/printchplenv", "--all" system "make" # Need to let chapel choose target compiler with llvm ENV["CHPL_HOST_CC"] = ENV["CC"] ENV["CHPL_HOST_CXX"] = ENV["CXX"] ENV.delete("CC") ENV.delete("CXX") system "./util/printchplenv", "--all" system "make" system "make", "chpldoc" system "make", "mason" system "make", "cleanall" rm_rf("third-party/llvm/llvm-src/") rm_rf("third-party/gasnet/gasnet-src") rm_rf("third-party/libfabric/libfabric-src") rm_rf("third-party/fltk/fltk-1.3.5-source.tar.gz") rm_rf("third-party/libunwind/libunwind-1.1.tar.gz") end prefix.install_metafiles # Install chpl and other binaries (e.g. chpldoc) into bin/ as exec scripts. platform = if OS.mac? "darwin-x86_64" elsif Hardware::CPU.is_64_bit? "linux64-x86_64" else "linux-x86_64" end bin.install Dir[libexec/"bin/#{platform}/*"] bin.env_script_all_files libexec/"bin/#{platform}/", CHPL_HOME: libexec man1.install_symlink Dir["#{libexec}/man/man1/*.1"] end test do ENV["CHPL_HOME"] = libexec cd libexec do system "util/test/checkChplInstall" end end end
class RenameImageUrlInSnapInviteAds < ActiveRecord::Migration def change rename_column :snap_invite_ads, :image_url, :media_url end end
class Room < ApplicationRecord has_many :entries,dependent: :destroy has_many :messages,dependent: :destroy end
class League class Roster < ApplicationRecord include MarkdownRenderCaching belongs_to :team, inverse_of: :rosters belongs_to :division, inverse_of: :rosters delegate :league, to: :division, allow_nil: true has_many :players, -> { order(created_at: :asc) }, dependent: :destroy, inverse_of: :roster has_many :users, through: :players has_many :transfers, -> { order(created_at: :desc) }, dependent: :destroy, inverse_of: :roster has_many :transfer_requests, -> { order(created_at: :desc) }, dependent: :destroy, inverse_of: :roster accepts_nested_attributes_for :players, reject_if: proc { |attrs| attrs['user_id'].blank? } has_many :home_team_matches, class_name: 'Match', foreign_key: 'home_team_id', dependent: :restrict_with_error has_many :away_team_matches, class_name: 'Match', foreign_key: 'away_team_id', dependent: :restrict_with_error has_many :titles, class_name: 'User::Title', dependent: :destroy has_many :comments, class_name: 'Roster::Comment', inverse_of: :roster, dependent: :destroy validates :name, presence: true, uniqueness: { scope: :division_id }, length: { in: 1..64 } validates :description, presence: true, allow_blank: true, length: { in: 0..1_000 } caches_markdown_render_for :description validates :notice, presence: true, allow_blank: true caches_markdown_render_for :notice validates :ranking, numericality: { greater_than: 0 }, allow_nil: true validates :seeding, numericality: { greater_than: 0 }, allow_nil: true validates :approved, inclusion: { in: [true, false] } validates :disbanded, inclusion: { in: [true, false] } validate :within_roster_size_limits, on: :create validate :unique_within_league, on: :create validate :validate_schedule scope :approved, -> { where(approved: true) } scope :active, -> { approved.where(disbanded: false) } scope :for_incomplete_league, lambda { completed = League.statuses[:completed] includes(division: :league).where.not(leagues: { status: completed }) } scope :for_completed_league, lambda { completed = League.statuses[:completed] includes(division: :league).where(leagues: { status: completed }) } scope :ordered, -> { order(placement: :asc, id: :asc) } scope :seeded, -> { order(seeding: :asc, id: :asc) } # rubocop:disable Rails/SkipsModelValidations after_create { League.increment_counter(:rosters_count, league.id) } after_destroy { League.decrement_counter(:rosters_count, league.id) } # rubocop:enable Rails/SkipsModelValidations after_create :trigger_score_update!, if: :approved? after_save do trigger_score_update! if [:ranking, :seeding, :approved, :disbanded].any? { |a| saved_change_to_attribute?(a) } end after_initialize :set_defaults, unless: :persisted? def self.matches Match.for_roster(all.map(&:id)) end def matches Match.for_roster(self) end def disband transaction do if league.forfeit_all_matches_when_roster_disbands? forfeit_all! else forfeit_all_non_confirmed! end transfer_requests.pending.destroy_all update!(disbanded: true) end end def users_off_roster team.users.where.not(id: users) end def add_player!(user) players.create!(user: user) end def remove_player!(user) players.find_by(user: user).destroy! end def on_roster?(user) players.where(user: user).exists? end def tentative_player_count players.size + TransferRequest.joining_roster(self).size - TransferRequest.leaving_roster(self).size end def schedule_data=(data) self[:schedule_data] = league.scheduler&.transform_data(data) end def order_keys_for(league) keys = [ranking || Float::INFINITY, disbanded? ? 1 : 0, -points] keys += league.tiebreakers.map { |tiebreaker| -tiebreaker.value_for(self) } keys.push seeding || Float::INFINITY keys end private def trigger_score_update! Leagues::Rosters::ScoreUpdatingService.call(league, division) end def forfeit_all! matches.find_each do |match| match.forfeit!(self) end end def forfeit_all_non_confirmed! matches.where.not(status: :confirmed).find_each do |match| match.forfeit!(self) end end def set_defaults self.approved = false if approved.blank? self[:schedule_data] = league.scheduler.default_schedule if league.present? && league.scheduler && !schedule_data end def within_roster_size_limits return if league.blank? unless league.valid_roster_size?(players.size) errors.add(:players, "Must have at least #{league.min_players} players" + (league.max_players.positive? ? " and no more than #{league.max_players} players" : '')) end end def unique_within_league return if league.blank? errors.add(:base, 'Can only sign up once') if league.rosters.where(team: team).exists? end def validate_schedule return unless league.present? && league.scheduler if schedule_data.present? league.scheduler.validate_roster(self) else errors.add(:schedule_data, 'Is required') end end end end
class AddGenresDirectorsAndActorsToRatingsTable < ActiveRecord::Migration def change add_column :ratings, :actors, :string add_column :ratings, :directors, :string add_column :ratings, :genres, :string end end
class User < ActiveRecord::Base has_many :spendings, dependent: :destroy has_many :temp_budget_plans, dependent: :destroy before_create{generate_token(:auth_token)} # taken from Michael Hartl's tutorial VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i # the following uses Regex (lookahead assertion) to ensure there is at least a lower case and upper case letter, # a digit, and a special character (non-word character) with at least 7 characters VALID_PASSWORD_REGEX= /\A^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*\W).{7,}$\z/ validates :username, presence: true, uniqueness:{case_sensitive:false} validates :email, presence: true, uniqueness:{case_sensitive:false}, length:{within:7..50}, format: {with:VALID_EMAIL_REGEX} validates :password, presence: true, format: {with:VALID_PASSWORD_REGEX}, on: :create # used for password digest to confirm two passwords entered match has_secure_password #ensure all email address are saved lower case before_save{self.email=email.downcase} #ensure all username address are saved lower case before_save{self.username=username.downcase} def send_email_confirmation generate_token(:email_confirmation_token) self.email_confirmation_sent_at=Time.zone.now save! EmailConfirmationMailer.send_email_confirm(self).deliver end def generate_token(column) begin self[column]=SecureRandom.urlsafe_base64 end while User.exists?(column=>self[column]) end end
class MachinesReadingsController < ApplicationController def index render 'index' end def show params.require(:search).permit(:machine, :option) if params[:search] selected_machine = params[:search][:machine] selected_option = params[:search][:option] last_reading = Reading.where(machine: selected_machine).last last_readings_24h = Reading.where(machine: selected_machine, :time => last_reading.time-1.day..last_reading.time) if selected_option == 'Latest temperature reading' result = last_reading.temperature @show_result = "#{selected_option} measured by #{selected_machine}: #{'%.02f' % result}°C" elsif selected_option == 'Average temperature of the last 24 hours from the latest reading' result = 0 last_readings_24h.each do |read| result += read.temperature end result /= last_readings_24h.size @show_result = "#{selected_option} measured by #{selected_machine}: #{'%.02f' % result}°C" else puts "======================================" puts "Total number of readings is: #{last_readings_24h.size}" puts "======================================" @show_result = String(nil) last_readings_24h.each do |read| @show_result += "#{read.temperature}" end end end @html_search = render_to_string :partial => 'machines_readings/search' render :json => {:success => true, :html_content => @html_search} end end
require 'yaml' require_relative 'player.rb' require_relative 'world.rb' class Game DIRECTIONS = ["north", "east", "south", "west"] attr_reader :world, :player, :current_room def initialize @world = World.new @player = Player.new @current_room end def start_game message('beginning') @world.create_rooms play_game message('end') end def player_input puts 'Which way do you want to go?' gets.chomp! end def player_position "You are at [#{@player.x_position}, #{@player.y_position}]" end private def play_game i = 0 while(i < @world.rooms.length) @current_room = @world.rooms[i] puts @current_room.description if(i == @world.rooms.length - 1) i+=1 else action = player_input take_direction(action) i+=1 end end end def take_direction(direction) if(DIRECTIONS.include?(direction)) if(@current_room.leave_room(direction)) move_player(@player,direction) else puts 'There is no path there' take_direction(gets.chomp!) end else puts 'Please enter a valid direction' take_direction(gets.chomp!) end end def move_player(player,direction) @world.go_north(player) if direction == :north @world.go_south(player) if direction == :south @world.go_east(player) if direction == :east @world.go_west(player) if direction == :west end def message(screen_message) m = YAML.load_file("assets/messages.yml") puts m[screen_message] end end
class CreateBookmarksTagsJoin < ActiveRecord::Migration[5.2] def change create_table :bookmarks_tags, :id => false do |t| t.integer "bookmark_id" t.integer "tag_id" end add_index("bookmarks_tags", ["bookmark_id", "tag_id"]) end end
defaults = [] begin require 'rspec/core/rake_task' RSpec::Core::RakeTask.new :spec do |t| t.rspec_opts = ['--color', '--format progress', '--order rand'] t.ruby_opts = ['-W2'] end defaults << :spec rescue LoadError warn 'RSpec not available, spec task not provided.' end begin require 'cane/rake_task' Cane::RakeTask.new :quality defaults << :quality rescue LoadError warn 'cane not available, quality task not provided.' end task default: defaults task :loc do print ' lib ' puts `zsh -c "grep -vE '^ *#|^$' lib/**/*.rb | wc -l"`.strip print ' spec ' puts `zsh -c "grep -vE '^ *#|^$' spec/**/*.rb | wc -l"`.strip end begin require 'yard' YARD::Rake::YardocTask.new :doc do |t| # t.options = ['--hide-void-return'] t.files = %w[lib/**/*.rb] end rescue LoadError warn 'YARD not available, doc task not provided.' end
require 'spec_helper' describe "Authentication" do subject{page} describe "signin page" do before {visit signin_path} it {should have_content("国科大跳蚤市场")} it {should have_content("主页")} it {should have_content("注册")} it {should have_content("登录")} it {should have_title('登录')} it {should have_content('名字')} it {should have_content('密码')} describe "with invalid information"do before {click_button "登录"} it{should have_title("登录")} it{should have_selector('div.alert.alert-error','text':'用户名和密码不正确')} describe "after visitinng another page"do before{click_link "主页"} it{should_not have_selector("div.alert.alert-error")} end end describe "with valid information" do let(:user){FactoryGirl.create(:user)} before{ fill_in "session_name", with:user.name fill_in "session_password", with:user.password click_button "登录" } it {should have_title(user.name)} it {should have_link("退出"),href:signout_path} it {should_not have_link("登录"),href:signin_path} describe "follow by signout"do before{click_link "退出"} it{should have_link("登录")} end end end end
require_relative 'menumodule' class SetAccountDisplayPreferencesPage include PageObject include MenuPanel include AccountsSubMenu include ServicesSubMenu include MyInfoSubMenu include MessagesAlertsSubMenu include PaymentsSubMenu table(:heading, :id => 'tblMain') button(:updatebutton, :id => 'btnUpdate') span(:message, :id => 'lblErrorMessage') text_field(:nickname, :id => 'ctlAccountsDataGrid_ctl02_txtNickName') def get_object(object) self.send "#{object.downcase.gsub(' ','')}_element" end end
require 'dry-validation' require_relative './oob_dns' require_relative './helpers' require_relative './baseline' require_relative './schema/predicates' require_relative './detect/context' require_relative './detect/payload_check' require_relative './detect/vuln' require_relative './blocks/generate' require_relative './blocks/match' require_relative './blocks/modify' require_relative './blocks/detect' require_relative './blocks/meta_info' require_relative './schema' module FastDsl # This class is running single FAST check class Detect def initialize(hash) Schema.validate!(hash) @match = Blocks::Match.new(hash['match']) @modify = Blocks::Modify.new(hash['modify']) @generate = Blocks::Generate.new(hash['generate']) @detect = Blocks::Detect.new(hash['detect']) @meta_info = Blocks::MetaInfo.new(hash['meta-info']) @all = [@match, @modify, @generate, @detect] end def applicable?(baseline) @all.all? do |block| block.respond_to?(:applicable?) ? block.applicable?(baseline) : true end end def run(baseline) ctx = FastDsl::Detect::Context.new(baseline: baseline) @all.each do |block| next unless block.respond_to?(:run) block.run(ctx) end ctx.meta_info = @meta_info ctx end end end
require 'rails_helper' describe Product do before do @product = FactoryGirl.create(:product) @user = FactoryGirl.create(:user) #here you put your code to generate test content #@product = Product.create!(name: "race bike", description: "Another bike", image_url: "bike.jpg", colour: "purple", price: 135.79) #@user = User.create!(username: "bartman", password: "eatmyshorts") @product.comments.create!(rating: 1, user: @user, body: "Bike is scary! Handlebars came off while doing a wheelie then I lost a pedal and wiped out.") @product.comments.create!(rating: 3, user: @user, body: "They didn't have my color. The bike's nice though.") @product.comments.create!(rating: 5, user: @user, body: "Best bike I've ever owned!") end it "returns the average rating of all comments" do expect(@product.average_rating).to eq 3 end it "is not valid" do expect(Product.new(description: "Nice bike")).not_to be_valid end it "is not a valid string" do expect(Product.new(name: 5)).not_to be_valid end end
require "rails_helper" RSpec.describe Mechanic, type: :model do describe "validations" do it { should validate_presence_of :name} it { should validate_presence_of :years_experience} end describe "relationships" do it { should have_many :mechanic_rides } it { should have_many(:rides).through(:mechanic_rides) } end describe "class methods" do it "can find average years experience for all mechanics" do mechanic_1 = Mechanic.create!( name: "Joe Schmo", years_experience: 2 ) mechanic_2 = Mechanic.create!( name: "Lily Hammersmith", years_experience: 10 ) mechanic_3 = Mechanic.create!( name: "Thor", years_experience: 6 ) expect(Mechanic.average_experience.floor).to eq(6) end describe "instance methods" do it "can sort rides by being open and by most thrilling" do park = AmusementPark.create!( name: "Cedar Point", admissions: 70 ) mechanic_1 = Mechanic.create!( name: "Lily Hammersmith", years_experience: 8 ) phantom = park.rides.create!( name: "The Phantom", thrill_rating: 11, open: true ) lightening = park.rides.create!( name: "Lightning Bolt", thrill_rating: 10, open: true ) pitfall = park.rides.create!( name: "Pitfall", thrill_rating: 9, open: true ) ferris_wheel = park.rides.create!( name: "Ferris Wheel", thrill_rating: 2, open: false ) mechanic_1.rides << [phantom, lightening, pitfall] expect(mechanic_1.open_rides.first).to eq(phantom) end it "can find a ride by id and add it" do park = AmusementPark.create!( name: "Cedar Point", admissions: 70 ) mechanic_1 = Mechanic.create!( name: "Lily Hammersmith", years_experience: 8 ) ferris_wheel = park.rides.create!( name: "Ferris Wheel", thrill_rating: 2, open: false ) expect(mechanic_1.rides).to be_empty mechanic_1.add_ride(ferris_wheel.id) expect(mechanic_1.rides.first.name).to eq(ferris_wheel.name) end end end end
class Watchlist < ApplicationRecord belongs_to :user belongs_to :movie validates_presence_of :user, :movie validates :user_id, numericality: { only_integer: true, message: "Please add a valid Id" } validates :movie_id, numericality: { only_integer: true, message: "Please add a valid Id" } end
module Silence def silence # what happened to ActiveRecord::Base.silence? old_logger = ActiveRecord::Base.logger ActiveRecord::Base.logger = nil begin yield ensure ActiveRecord::Base.logger = old_logger end end end
class Computer #o nome da classe sempre começa com class, o nome dela poderia ser qualquer um, exemplo: cachorro, carro e etc def turn_on 'turn on the computer' end def shutdown 'shutdown the computer' end end computer = Computer.new #'Computer.new' é o objeto da classe puts computer.shutdown
class User include DataMapper::Resource property :id, Serial property :created_at, DateTime property :username, String, key: true property :enabled, Boolean has n, :apps end
#encoding: utf-8 # 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) WorkType.delete_all Employee.where(:stanowisko => "Admin").delete_all Office.delete_all work_types = [ {:nazwa => "Tyczenie obiektów budowlanych"}, {:nazwa => "Pomiary budowlano-montażowe"}, {:nazwa => "Ustalenie objętości mas ziemnych"}, {:nazwa => "Pomiary odkształceń"}, {:nazwa => "Prace na terenach zamkniętych"}, {:nazwa => "Pomiary do orientacji podziemnych wyrobisk górniczych"}, {:nazwa => "Pomiary deformacji powierzchni górotworu"}, {:nazwa => "Pomiary do wyznaczenia zasięgu złóż kopalin"}, {:nazwa => "Pomiary specjalne na terenach kolei, lotnisk oraz dróg lądowych i wodnych"}, {:nazwa => "Pomiary specjalne na terenach leśnych oraz opracowania dla urządzania lasu"}, {:nazwa => "Ustalenie powierzchni zasiewów"}, {:nazwa => "Projektowanie płodozmianów"}, {:nazwa => "Renowacja i konserwacja urządzeń wodno-melioracyjnych"}, {:nazwa => "Reprodukowanie map, materiałów geodezyjnych i kartograficznych"}, {:nazwa => "Kartograficzne opracowania robocze"}, {:nazwa => "Inne"}, ] WorkType.create(work_types) e = Employee.new(:imie => "Marcin", :nazwisko => "Adamczyk", :data_ur => Time.now, :data_zatr => Time.now, :adres => "admin", :nr_upr => 1, :pesel => "123", :stanowisko => "Admin", :telefon => "123", :email => "admin@super.net") e.admin = true e.password = "superadmin" e.password_confirmation = "superadmin" e.save! o = Office.create(:nazwa => "Geotech", :regon => "12312312", :adres => "ul. Szybka 5/9", :telefon => "513 123 123", :email => "mail@geotech.pl", :fax => "(0-33) 513 123 123")
class Seller::ProductsController < ApplicationController def index @stores = Store.where(seller_id: session[:seller_id]) end def show @product = Product.find(params[:id]) @store = Store.find_by(id: @product.store_id) end def edit @product = Product.find(params[:id]) @stores = Store.where(seller_id: session[:seller_id]) end def new @stores = Store.where(seller_id: session[:seller_id]) @product = Product.new end def create @product = Product.new(product_params) begin if @product.save flash[:notice] = "Produto cadastrado." redirect_to seller_products_path else flash[:notice] = "Não foi possível completar o cadastro. Por favor verificar os dados novamente." redirect_to new_seller_product_path end rescue flash[:notice] = "Não foi possível completar o cadastro. Por favor verificar os dados novamente." redirect_to new_seller_product_path end end def update @product = Product.find(params[:id]) @product.update_attributes(product_params) begin if @product.save flash[:notice] = "Dados atualizados." redirect_to seller_products_path else flash[:notice] = "Não foi possível atualizar os dados. Por favor verificar os dados novamente." redirect_to edit_seller_product_path(@product) end rescue flash[:notice] = "Não foi possível atualizar os dados. Por favor verificar os dados novamente." redirect_to edit_seller_product_path(@product) end end def destroy @product = Product.find(params[:id]) @product.destroy redirect_to seller_products_path end private def product_params params.require(:product).permit(:nome, :codigo, :descricao, :preconormal, :precopromocional, :estoqueatual, :estoquemax, :store_id) end end
require 'faker' require "open-uri" def handle_string_io_as_file(io) return io unless io.class == StringIO file = Tempfile.new(["temp",".png"], encoding: 'ascii-8bit') file.binmode file.write io.read file.open end # -------------------------- Destroy --------------------------- # puts 'Destroying all industries' Industry.destroy_all puts 'Creating Industries' industries_array = ["Agriculture", "Computer-science", "Education", "Financial services", "Health services", "Hospitality services", "Industrial Design", "Mechanical and electrical engineering", "Sports", "Web-development"] industries_array.map { |industry_name| puts Industry.create(name: industry_name ) } puts 'Finished creating Industries' puts "Destroying users" User.destroy_all # -------------------------- Mentors --------------------------- # work_experience = [ "Computer science graduate trained in C, C++, Ruby on Rails, HTML, CSS,JavaScript, Python", "Co-Founder of techlab XR - 2006", "Co-Founder of VentGrid - 2001", "Founder of BNB IQ - 2010", "Founder of NOMICS", "CTO Metallar - 2017", "CTO Archtype IT - 2012", "Team manager Techclassy - 2003", "Lead Developer GranFave B.V. - 2013", "Developer Techeme - 2007", "Lead Developer Intech - 2005" ] puts 'Creating Mentor1' mentor1 = User.new( first_name: "Thomas", last_name: "Crane", age: 41, city: "Amsterdam", phone_number: 3053454123, about: "Energetic Adobe Certified Expert (ACE) web designer with 6+ years of experience. Seeking to enhance design excellence at Dujo International. Designed 5 responsive websites per month for Amphimia Global with 99 client satisfaction.", email: "thomas@email.com", password: "123456" ) UserIndustry.create(industry: Industry.last, user: mentor1, work_experience: work_experience ) mentor1.save! puts 'Finished creating Mentor1' puts 'Creating Mentor2' mentor2 = User.new( first_name: "Sascha", last_name: "Akman", age: 35, city: "Haarlem", phone_number: 2233454123, about: "Built and maintained a working customer database, order system, and picking and packing system with MySQL, complete with error handling and data validation.", email: "sascha@email.com", password: "123456" ) UserIndustry.create(industry: Industry.last, user: mentor2, work_experience: work_experience ) mentor2.save! puts 'Finished creating Mentor2' puts 'Creating Mentor3' mentor3 = User.new( first_name: "Brian", last_name: "Lyall", age: 51, city: "Paris", phone_number: 3057624123, about: "Inquisitive, energetic computer science specialist skilled in leadership, with a strong foundation in math, logic, and cross-platform coding. Seeking to leverage solid skills in collaboration.", email: "brianx@email.com", password: "123456" ) UserIndustry.create(industry: Industry.last, user: mentor3, work_experience: work_experience ) mentor3.save! puts 'Finished creating Mentor3' puts 'Creating Mentor4' mentor4 = User.new( first_name: "Miranda", last_name: "Shaffer", age: 45, city: "Berlin", phone_number: 309836123, about: "Energetic Adobe Certified Expert (ACE) web designer with 6+ years of experience. Seeking to enhance design excellence at Dujo International. Designed 5 responsive websites per month for Amphimia Global with 99 client satisfaction.", email: "miranda@email.com", password: "123456" ) UserIndustry.create(industry: Industry.last, user: mentor4, work_experience: work_experience ) mentor4.save! puts 'Finished creating Mentor4' mentors_array = [mentor1, mentor2, mentor3, mentor4] # -------------------------- Mentor avatars --------------------------- # puts "Creating avatars for mentors" puts "Avatar Mentor 1" mentor1 = User.first mentor1.photo.attach(io: File.open('app/assets/images/mentor-thomas-crane.png'), filename: 'mentor-thomas-crane.png', content_type: 'image/png') puts "Avatar Mentor 2" mentor2 = User.second mentor2.photo.attach(io: File.open('app/assets/images/mentor-sascha-akman.png'), filename: 'mentor-sascha-akman.png', content_type: 'image/png') puts "Avatar Mentor 3" mentor3 = User.third mentor3.photo.attach(io: File.open('app/assets/images/mentor-brian-Lyall.png'), filename: 'mentor-brian-Lyall.png', content_type: 'image/png') puts "Avatar Mentor 4" mentor4 = User.fourth mentor4.photo.attach(io: File.open('app/assets/images/mentor-miranda-shaffer.png'), filename: 'mentor-miranda-shaffer.png', content_type: 'image/png') # -------------------------- Bob --------------------------- # puts 'Creating Bob' user_bob = User.new( first_name: "Bob", last_name: Faker::Name.last_name, age: rand(30..50), city: Faker::Address.city, phone_number: Faker::PhoneNumber.cell_phone, about: Faker::Quote.matz, email: "bob@email.com", password: "123456" ) user_bob.photo.attach(io: File.open('app/assets/images/mentoree-illustration-6.png'), filename: 'mentoree-illustration-6.png', content_type: 'image/png') UserIndustry.create(industry: Industry.first, user: user_bob, work_experience: "Skilled" ) user_bob.save! puts 'Finished creating Bob' # -------------------------- Mentorees --------------------------- # puts 'Creating user_chris' user_chris = User.new( first_name: "Chris", last_name: "Ayers", age: 25, city: "Lisboa", phone_number: 3053434523, about: "This is the about info of chris", email: "crhis@email.com", password: "123456" ) user_chris.photo.attach(io: File.open('app/assets/images/mentoree-testimonials-avatar1.png'), filename: 'mentoree-testimonials-avatar1.png', content_type: 'image/png') UserIndustry.create(industry: Industry.all.sample, user: user_chris, work_experience: "This is the work experience of chris." ) user_chris.save! puts 'Finished creating user_chris' puts 'Creating user_taliyah' user_taliyah = User.new( first_name: "Taliyah", last_name: "Sandoval", age: 28, city: "Amsterdam", phone_number: 3053434523, about: "This is the about info of Taliyah", email: "taliyah@email.com", password: "123456" ) user_taliyah.photo.attach(io: File.open('app/assets/images/mentoree-testimonials-avatar2.png'), filename: 'mentoree-testimonials-avatar2.png', content_type: 'image/png') UserIndustry.create(industry: Industry.all.sample, user: user_taliyah, work_experience: "This is the work experience of Taliyah." ) user_taliyah.save! puts 'Finished creating user_taliyah' puts 'Creating user_joshua' user_joshua = User.new( first_name: "Joshua", last_name: "Evans", age: 33, city: "Barcelona", phone_number: 3053434523, about: "This is the about info of joshua", email: "joshua@email.com", password: "123456" ) user_joshua.photo.attach(io: File.open('app/assets/images/mentoree-testimonials-avatar4.png'), filename: 'mentoree-testimonials-avatar4.png', content_type: 'image/png') UserIndustry.create(industry: Industry.all.sample, user: user_joshua, work_experience: "This is the work experience of joshua." ) user_joshua.save! puts 'Finished creating user_joshua' puts 'Creating user_lorena' user_lorena = User.new( first_name: "Lorena", last_name: "Segura", age: 33, city: "Lyon", phone_number: 3053434523, about: "This is the about info of lorena", email: "lorena@email.com", password: "123456" ) user_lorena.photo.attach(io: File.open('app/assets/images/mentoree-testimonials-avatar4.png'), filename: 'mentoree-testimonials-avatar4.png', content_type: 'image/png') UserIndustry.create(industry: Industry.all.sample, user: user_lorena, work_experience: "This is the work experience of lorena." ) user_lorena.save! puts 'Finished creating user_lorena' puts 'Creating user_daniel' # ------------------------------ Daniel ------------------ # user_daniel = User.new( first_name: "Daniel", last_name: "Mendez", age: 31, city: "Amsterdam", phone_number: 3053434523, about: "This is the about info of daniel", email: "daniel@gmail.com", password: "123456" ) user_daniel.photo.attach(io: File.open('app/assets/images/mentoree-daniel.png'), filename: 'mentoree-daniel.png.png', content_type: 'image/png') UserIndustry.create(industry: Industry.all.sample, user: user_daniel, work_experience: "This is the work experience of daniel." ) user_daniel.save! puts 'Finished creating user_daniel' mentoree_array = [user_chris, user_taliyah, user_joshua, user_lorena] # ---------------------- mentor availabilty, past meeting and reviews ----------------------- # puts "Creating reviews array" reviews = ["Extremely happy with my mentor meeting. It gave me a new perspective about my field.", "Meet up was great. Extremely happy with what I've learned.", "Just finished my masters and I had no idea how to approach looking for a job in my field. My mentor gave me some good advice to start replying to openings.", "Glad I could finally have a chat the founder of a tech start-up. Considering doing that myself! Thank you tons.", "Amazing help. Helped me get a clear view on how to proceed with job hunting.", "Really happy with the advice. Now I can continue my careerpath with a clear view of the future."] puts "Creating 3 future availabilities" mentors_array.each do |mentor| 3.times do |index| date = DateTime.now date = date.change(hour: rand(9..18), min: 0)#.to_a.sample) Availability.create( mentor_id: mentor.id, slot: date + rand(1..14) ) end puts "Creating 3 past availabilities + past meeting + reviews" 3.times do availability = Availability.create( mentor_id: mentor.id, slot: Date.today-rand(3) ) past_meeting = Meeting.create(availability: availability, mentoree_id: mentoree_array.sample.id ) Review.create(content: reviews.pop, meeting: past_meeting, rating: true) unless reviews.empty? end end puts "Creating 3 past meeting daniel" past_availability_daniel = Availability.create(mentor_id: mentor1.id, slot: Date.today-rand(3)) past_meeting_daniel = Meeting.create(availability: past_availability_daniel, mentoree_id: user_daniel.id ) # ---------------------- User_industries Work Experience ----------------------- # puts "💫 OMG Finishing seeding! 🌈"