text
stringlengths
10
2.61M
# Palindromic Numbers def palindrome?(input) input.reverse == input end def real_palindrome?(string) palindrome?(string.downcase.gsub(/[^a-z,0-9]/, '')) end def palindromic_number?(number) real_palindrome?(number.to_s) end
class CreateFixityCheckResults < ActiveRecord::Migration[5.1] def change create_table :fixity_check_results do |t| t.references :cfs_file, foreign_key: true t.integer :status, null: false, index: true t.datetime :created_at, null: false, index: true end end end
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :username, unique: true, null: false t.string :geekhack_username, unique: true t.string :email, null: false, unique: true t.string :stripe_customer_id t.string :password_digest, null: false t.string :confirmation_token t.boolean :confirmed, default: false, null: false t.string :password_reset_token t.datetime :password_reset_sent_at t.boolean :admin, default: false, null: false t.timestamps null: false end add_index :users, :email end end
require 'rails_helper' describe "doctors", type: :feature do before do @meredith = Doctor.create({name: "Meredith Grey", department: "Internal Medicine"}) @bart = Patient.create(name: "Bart Simpson", age:10 ) Appointment.create(appointment_datetime: DateTime.new(2016, 01, 11, 20, 20, 0), patient_id: 1, doctor_id: 1) end describe "#show page" do it "shows all of a doctor's appointment times in a human readable format" do visit doctor_path(@meredith) expect(page).to have_content("January 11, 2016 at 20:20") end it "links to the patient's show page by name for each appointment" do visit doctor_path(@meredith) expect(page).to have_link("Bart Simpson", href: patient_path(@bart)) end end end
class FlatironBase attr_accessor :base_uri, :data, :table def initialize(base_uri) @firebase = Firebase::Client.new(base_uri) @table = @firebase.get("").body.keys[0] #defaults to first table in database puts "Database accessed. Defaulted to first table. (#{@table})" end def swap_table(table_name) #swaps between tables in the database @table = table_name puts "Active table is now #{@table}" end def add_table(table_name, hash = {"place" => "holder"}) # Creates a table and autoswaps to that table. Firebase doesn't allow for an empty object, so a placeholder hash is needed. if @firebase.get("").body.keys.include?(table_name) puts "This table already exists. Swapping tables..." swap_table(table_name) else new_table = @firebase.push(table_name, hash) swap_table(table_name) if new_table.success? puts "Table creation success." else puts "Something went wrong." false end end end def add(table, hash) #adds an entry to the database @firebase.push(table, hash) end def get_data #returns an array of all items in the table, defaults to current table in use @data = @firebase.get(@table).body @data.to_a end def print_data #does what it says on the tin puts @data.to_s end def search_by_attribute(attribute, value) @data = @firebase.get(@table).body @data.each do |data_id, data_values| if data_values[attribute] == value @id = data_id end end path = "#{@table}/#{@id}" @firebase.get(path).body end def remove_by_id(id) #removes an entry in the database by the id path = "#{@table}/#{id}" @firebase.delete(path) puts "Removed '#{path}'" end def remove_table(table_name = @table) #drop a table, defaults to current table @firebase.delete(table_name) puts "Table deleted." end end
require File.join(File.dirname(__FILE__), '..', 'spec_helper.rb') describe Attributor::Integer do subject(:type) { Attributor::Integer } context '.example' do context 'when :min and :max are unspecified' do context 'valid cases' do it "returns an Integer in the range [0,#{Attributor::Integer::EXAMPLE_RANGE}]" do 20.times do value = type.example value.should be_a(::Integer) value.should <= Attributor::Integer::EXAMPLE_RANGE value.should >= 0 end end end end context 'when :min is unspecified' do context 'valid cases' do [5, 100000000000000000000, -100000000000000000000].each do |max| it "returns an Integer in the range [,#{max.inspect}]" do 20.times do value = type.example(nil, options: {max: max}) value.should be_a(::Integer) value.should <= max value.should >= max - Attributor::Integer::EXAMPLE_RANGE end end end end context 'invalid cases' do ['invalid', false].each do |max| it "raises for the invalid range [,#{max.inspect}]" do expect { value = type.example(nil, options: {max: max}) value.should be_a(::Integer) }.to raise_error(Attributor::AttributorException, "Invalid range: [, #{max.inspect}]") end end end end context 'when :max is unspecified' do context 'valid cases' do [1, -100000000000000000000, 100000000000000000000].each do |min| it "returns an Integer in the range [#{min.inspect},]" do 20.times do value = type.example(nil, options: {min: min}) value.should be_a(::Integer) value.should <= min + Attributor::Integer::EXAMPLE_RANGE value.should >= min end end end end context 'invalid cases' do ['invalid', false].each do |min| it "raises for the invalid range [#{min.inspect},]" do expect { value = type.example(nil, options: {min: min}) value.should be_a(::Integer) }.to raise_error(Attributor::AttributorException, "Invalid range: [#{min.inspect},]") end end end end context 'when :min and :max are specified' do context 'valid cases' do [ [1,1], [1,5], [-2,-2], [-3,2], [-1000000000000000,1000000000000000] ].each do |min, max| it "returns an Integer in the range [#{min.inspect},#{max.inspect}]" do 20.times do value = type.example(nil, options: {max: max, min: min}) value.should <= max value.should >= min end end end end context 'invalid cases' do [[1,-1], [1,"5"], ["-2",4], [false, false], [true, true]].each do |min, max| it "raises for the invalid range [#{min.inspect}, #{max.inspect}]" do opts = {options: {max: max, min: min}} expect { type.example(nil, opts) }.to raise_error(Attributor::AttributorException, "Invalid range: [#{min.inspect}, #{max.inspect}]") end end end end end context '.load' do let(:value) { nil } it 'returns nil for nil' do type.load(nil).should be(nil) end context 'for incoming integer values' do let(:value) { 1 } it 'returns the incoming value' do type.load(value).should be(value) end end context 'for incoming string values' do context 'that are valid integers' do let(:value) { '1024' } it 'decodes it if the string represents an integer' do type.load(value).should == 1024 end end context 'that are not valid integers' do context 'with simple alphanumeric text' do let(:value) { 'not an integer' } it 'raises an error' do expect { type.load(value) }.to raise_error(/invalid value/) end end context 'with a floating point value' do let(:value) { '98.76' } it 'raises an error' do expect { type.load(value) }.to raise_error(/invalid value/) end end end end end end
module ClientAuth class Signer attr_reader :client_name, :payload def initialize(method, path, params = {}) @method = method.upcase @path = path @payload = params end attr_writer :payload def headers raise NotImplementedError, 'Client name not configured' unless client_name { 'X-Client' => client_name, 'X-Timestamp' => timestamp, 'X-Signature' => signature } end def configure(client_key, client_name) @client_key = client_key @client_name = client_name end private def timestamp @timestamp ||= Time.now.to_i.to_s end def signature raise NotImplementedError, 'Client key not configured' unless @client_key key.sign(OpenSSL::Digest::SHA256.new, secret_string).unpack('H*').first end def key @key ||= OpenSSL::PKey::RSA.new(@client_key) end def secret_string [ client_name, @method, fullpath, request_body, timestamp ].join(ClientAuth::Authenticator::DELIMITER) end def request_body return if @method == 'GET' payload end def fullpath fullpath = [safe_path] fullpath.push(payload.to_query) if @method == 'GET' && payload.present? fullpath.join('?') end def safe_path '/' + URI.encode(@path).gsub(%r{\A\/}, '') end end end
require 'rails_helper' RSpec.describe Category, type: :model do before { @category = build(:category) } subject { @category } it { should respond_to(:category_name) } it { should be_valid } describe 'when category name is not present' do before { @category.category_name = ' ' } it { should_not be_valid } end describe 'when category name is too long' do before { @category.category_name = 'a' * 21 } it { should_not be_valid } end describe 'when category name is too short' do before { @category.category_name = 'a' } it { should_not be_valid } end describe 'when category name is already taken' do before do category_with_same_name = @category.dup category_with_same_name.category_name = @category.category_name.upcase category_with_same_name.save end it { should_not be_valid } end end
module Rack module DevMark module Theme class Base def initialize(options = {}) raise RuntimeError, 'Abstract class can not be instantiated' if self.class == Rack::DevMark::Theme::Base @options = options end def insert_into(html, env, params = {}) end private def stylesheet_link_tag(path) %Q~<style>#{::File.open(::File.join(::File.dirname(__FILE__), '../../../../vendor/assets/stylesheets', path)).read}</style>~ end def gsub_tag_content(html, name, &block) String.new(html).gsub(%r{(<#{name}\s*[^>]*>)([^<]*)(</#{name}>)}im) do "#{$1}#{block.call($2)}#{$3}" end end def gsub_tag_attribute(html, name, attr, &block) String.new(html).gsub %r{(<#{name}\s*)([^>]*)(>)}im do s1, s2, s3 = $1, $2, $3 s2.gsub! %r{(#{attr}=')([^']*)(')} do "#{$1}#{block.call($2)}#{$3}" end s2.gsub! %r{(#{attr}=")([^"]*)(")} do "#{$1}#{block.call($2)}#{$3}" end "#{s1}#{s2}#{s3}" end end end end end end
require_relative 'oystercard' class Journey PENALTY_FARE = 6 def fare PENALTY_FARE end def entry_station(station) station end def exit_station(station) station end def complete? false end end
RSpec::Matchers.define :be_a_migration do match do |file_path| dirname, file_name = File.dirname(file_path), File.basename(file_path) if file_name =~ /\d+_.*\.rb/ migration_file_path = file_path else migration_file_path = Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}$/).first end migration_file_path && File.exist?(migration_file_path) end end
class User < ActiveRecord::Base require 'digest' include BCrypt # Remember to create a migration! has_many :whispers has_many :stalker_relationships, class_name: "Stalking", foreign_key: "stalkee_id" has_many :stalkee_relationships, class_name: "Stalking", foreign_key: "stalker_id" has_many :stalkers, through: :stalker_relationships, source: "stalker" has_many :stalkees, through: :stalkee_relationships, source: "stalkee" validates :username, :email, presence: true def password @password ||= Password.new(password_hash) end def password=(new_password) @password = Password.create(new_password) self.password_hash = @password end def stalking?(user) stalkees.include?(user) end def stalked_by?(user) stalkers.include?(user) end def stalk(user_to_stalk) if self.stalking?(user_to_stalk) p "you're already stalking #{user_to_stalk.username}!" else Stalking.create(stalker_id: self.id, stalkee_id: user_to_stalk.id) end end def unstalk(user_to_unstalk) if Stalking.where(stalker_id: self.id, stalkee_id: user_to_unstalk.id).first.destroy else p "failed to unstalk" end end def feed whisper_array = [] self.stalkees.each do |stalkee| whisper_array << stalkee.whispers end whisper_array.flatten! whisper_array = whisper_array.sort_by {|whispers| whispers.created_at} whisper_array.reverse! # return whisper_array # binding.pry end def gravatar_url md5_hash = Digest::MD5.new md5_hash.update self.email return "http://www.gravatar.com/avatar/#{md5_hash}?d=http://cbsnews2.cbsistatic.com/hub/i/r/2002/08/05/da62eade-a642-11e2-a3f0-029118418759/thumbnail/620x350/d58085faadcad60fea4c167fee36a99a/image517488x.jpg" end end
class AddScrubsAndFilenameToListPulls < ActiveRecord::Migration def self.up add_column :list_pulls, :scrubs, :text add_column :list_pulls, :filename, :string end def self.down remove_column :list_pulls, :scrubs remove_column :list_pulls, :filename end end
require 'RESTClient' require 'date' module GithubManager include RESTClient @@current_organization = {} RESTClient.set_base_url("https://api.github.com") def current_organization @@current_organization end def create_org(name) response = RESTClient.make_request('GET', "/orgs/#{name}") if response parsed_response = JSON.parse response.body @@current_organization = Organization.new(parsed_response['login'], parsed_response['avatar_url'], parsed_response['repos_url'].split('com')[1]) else raise "Couldn't find a organization with the provided name" end end def get_contributions_history(days_ago) @@current_organization.top_five_collaborators days_ago end module_function :create_org, :current_organization, :get_contributions_history end
require 'rails_helper' RSpec.configure do |c| c.include Features::ControllerMacros end xdescribe PaymentsController do describe '#create' do it 'calls pay_order on the order model and returns success' do login order = create(:order) allow(Order).to receive(:find). with(order.id.to_s). and_return(order) allow(order).to receive(:pay_order).and_return({status: :success}) expect(order).to receive(:pay_order) post :create, payment_token: 'JFLKSANFKL', amount: '5.00', id: order.id, access_token: @user.access_token parsed_body = JSON.parse(response.body) expect(parsed_body['status']).to eq('success') end end end
# encoding: utf-8 require "spec_helper" describe Refinery do describe "OurOffices" do describe "Admin" do describe "pcares_events", type: :feature do refinery_login_with :refinery_user describe "pcares_events list" do before do FactoryGirl.create(:pcares_event, :category => "UniqueTitleOne") FactoryGirl.create(:pcares_event, :category => "UniqueTitleTwo") end it "shows two items" do visit refinery.our_offices_admin_pcares_events_path expect(page).to have_content("UniqueTitleOne") expect(page).to have_content("UniqueTitleTwo") end end describe "create" do before do visit refinery.our_offices_admin_pcares_events_path click_link "Add New Pcares Event" end context "valid data" do it "should succeed" do fill_in "Category", :with => "This is a test of the first string field" expect { click_button "Save" }.to change(Refinery::OurOffices::PcaresEvent, :count).from(0).to(1) expect(page).to have_content("'This is a test of the first string field' was successfully added.") end end context "invalid data" do it "should fail" do expect { click_button "Save" }.not_to change(Refinery::OurOffices::PcaresEvent, :count) expect(page).to have_content("Category can't be blank") end end context "duplicate" do before { FactoryGirl.create(:pcares_event, :category => "UniqueTitle") } it "should fail" do visit refinery.our_offices_admin_pcares_events_path click_link "Add New Pcares Event" fill_in "Category", :with => "UniqueTitle" expect { click_button "Save" }.not_to change(Refinery::OurOffices::PcaresEvent, :count) expect(page).to have_content("There were problems") end end end describe "edit" do before { FactoryGirl.create(:pcares_event, :category => "A category") } it "should succeed" do visit refinery.our_offices_admin_pcares_events_path within ".actions" do click_link "Edit this pcares event" end fill_in "Category", :with => "A different category" click_button "Save" expect(page).to have_content("'A different category' was successfully updated.") expect(page).not_to have_content("A category") end end describe "destroy" do before { FactoryGirl.create(:pcares_event, :category => "UniqueTitleOne") } it "should succeed" do visit refinery.our_offices_admin_pcares_events_path click_link "Remove this pcares event forever" expect(page).to have_content("'UniqueTitleOne' was successfully removed.") expect(Refinery::OurOffices::PcaresEvent.count).to eq(0) end end end end end end
#!/usr/bin/env ruby # Assign variables which change per project or in testing # @irc_channel=ENV['IRC_CHANNEL'] github_project_url = "https://github.com/user/repo" # Assign variables which are the same for every project # @project=ENV['JOB_NAME'] @build=ENV['BUILD_NUMBER'] @url=ENV['BUILD_URL'] @commit=ENV['GIT_COMMIT'] || "thereisnowaythisstringwillmatchanything" @committer = %x(git log -1 --format=format:%an).chomp def github_url_shortener(url) curl_form_result = %x( curl -s -i http://git.io -F "url=#{url}/commit/#{@commit}" | awk '/Location/ {print $2}' ).chomp case curl_form_result when /http:\/\/git.io/ @commit_url = curl_form_result else @commit_url = "#{url}/commit/#{@commit}" end end github_url_shortener(github_project_url) def post_to_irc(test_status) message_started = "Jenkins started #{@project} build #{@build} #{@commit_url}" message_broken = "#{@committer}: Something went wrong with #{@project} build #{@build} #{@test_results} #{@url}console" message_failed = "#{@committer}: #{@project} build #{@build} FAILED: #{@test_results}. #{@url}console" message_passed = "#{@project} build #{@build} PASSED: #{@test_results}. #{@url}console Cheers #{@committer}!" def curl_post(message) %x(curl -X POST 174.127.47.95/#{@irc_channel} -d '#{message}') end case test_status when "test_started" curl_post(message_started) when "test_broken" curl_post(message_broken) when "test_failed" curl_post(message_failed) when "test_passed" curl_post(message_passed) end end post_to_irc("test_started") (failure, success) = nil test_output = `cake test; exit 0;` test_output = %x( ssh user@system " killall java node cd /srv/repo/ git stash git pull rm -rf /srv/repo/node_modules/ npm install npm link --unsafe-perm cake test exit 0" ) test_exit_status=$?.success? puts "Test exit status: #{test_exit_status}" puts puts "Test output:" puts test_output test_output.split("\n").each do |line| if line =~ /(\d+)\s(errored)/ failure = $2 @test_results = "#{$1} errored" elsif line =~ /(\d+)\s(honored)/ success = $2 @test_results = "#{$1} honored" end end if (@test_results) if failure post_to_irc("test_failed") exit 1 elsif success post_to_irc("test_passed") exit 0 end else post_to_irc("test_broken") exit 1 end
# frozen_string_literal: true # Category model Class class Category < ApplicationRecord has_many :category_jimen, dependent: :destroy has_many :jimen, through: :category_jimen end
class AddColumnTypeConceptToConcept < ActiveRecord::Migration def change add_column :concepts, :type_concept, :string add_column :concepts, :status, :integer end end
class RenameTokenSecretToSecret < ActiveRecord::Migration[5.0] def change rename_column :users, :token_secret, :secret end end
class RenameFriendsInFriendships < ActiveRecord::Migration[5.1] def change rename_column :friendships, :friends_id, :friend_id end end
class Bid < ApplicationRecord belongs_to :bidder, class_name: "User", foreign_key: :user_id belongs_to :card end
class CreateMaintasks < ActiveRecord::Migration def change create_table :maintasks do |t| t.references :equipment, index: true t.string :task t.integer :period t.string :unit t.timestamps end end end
source 'https://rubygems.org' gem 'rails', '3.2.13' gem 'jquery-rails' gem 'pg' gem 'devise' gem 'omniauth-twitter' gem 'omniauth-facebook' gem 'twitter' gem 'subdomainbox' gem 'uuidtools' # Gems used only for assets and not required # in production environments by default. group :assets do gem 'coffee-rails' gem 'uglifier' gem 'therubyracer', :require => 'v8' gem 'less-rails-bootstrap' end group :development, :test, :staging do gem 'pry' gem 'pry-nav' gem 'pry-stack_explorer' end group :development, :test do gem 'rspec-rails', '2.10.1' gem 'jasmine' gem 'jasminerice' gem 'awesome_print' end group :test do gem 'launchy' gem 'spork', '>= 0.9.2' # Factory Girl 2.4.1 was creating duplicates, so when we did # 3.times { Factory(:document, :asset_library => @library) } # expecting the library to have 3 documents, we actually ended up with 6 gem 'factory_girl', '2.2.0' gem 'factory_girl_rails' gem 'fuubar' gem 'capybara', '1.1.2' gem 'database_cleaner' end
class AddTempleToCar < ActiveRecord::Migration def change add_reference :cars, :temple, index: true, foreign_key: true end end
class CountriesDatatable delegate :params, :h, :link_to, to: :@view include Rails.application.routes.url_helpers include ActionView::Helpers::OutputSafetyHelper def initialize(view) @view = view end def as_json(options = {}) { sEcho: params[:sEcho].to_i, iTotalRecords: Country.count, iTotalDisplayRecords: countries.total_entries, aaData: data } end private def data countries.map do |country| [ (country.id.present? ? country.id : ''), (country.name.present? ? country.name : ''), link_to('Delete', admin_country_path(country), method: :delete, data: { confirm: '¿Are you sure want to delete this country ?' }, class: 'btn btn-xs btn-danger')+" "+ link_to('Show', admin_country_path(country), class: 'btn btn-xs btn-success')+" "+ link_to('Edit', edit_admin_country_path(country), class: 'btn btn-xs btn-warning') ] end end def countries @countries ||= fetch_countries end def fetch_countries countries = Country.all.order("#{sort_column} #{sort_direction}") countries = countries.page(page).per_page(per_page) if params[:sSearch].present? countries = countries.where("countries.name LIKE :search OR CONVERT(countries.id, CHAR(20)) LIKE :search", search: "%#{params[:sSearch]}%") end countries end def page params[:iDisplayStart].to_i / per_page + 1 end def per_page params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10 end def sort_column columns = [ 'countries.id', 'countries.name', ''] columns[params[:iSortCol_0].to_i] end def sort_direction params[:sSortDir_0] == 'desc' ? 'desc' : 'asc' end end
require 'rails_helper' RSpec.describe ClientPayment, :ledgers do it 'creates years' do Timecop.travel('2014-6-1') do payment = described_class.query expect(payment.years).to eq %w[2014 2013 2012 2011 2010] end end describe '#accounts_with_period' do it 'selects account that have charges within a quarter month' do client = client_create( properties: [property_new( account: account_create( charges: [charge_new( cycle: cycle_new(name: 'Mar-due-on', due_ons: [DueOn.new(month: 3, day: 4), DueOn.new(month: 9, day: 4)]) )] ) )] ) batch_month = BatchMonths.make month: BatchMonths::MAR expect(described_class.query(client_id: client.id) .accounts_with_period(batch_months: batch_month)) .to match_array [client.properties.first.account] end it 'rejects account that belong to another client' do client_create(human_ref: 1, properties: [property_new( account: account_create( charges: [charge_new( cycle: cycle_new(name: 'Mar-due-on', due_ons: [DueOn.new(month: 3, day: 4), DueOn.new(month: 9, day: 4)]) )] ) )]) batch_month = BatchMonths.make month: BatchMonths::MAR other_client = client_create(human_ref: 2) expect(described_class.query(client_id: other_client.id) .accounts_with_period(batch_months: batch_month)) .to match_array [] end it 'rejects account that only have charges outside a quarter month' do client = client_create( properties: [property_new( account: account_create( charges: [charge_new( cycle: cycle_new(name: 'Feb-due-on', due_ons: [DueOn.new(month: 2, day: 4), DueOn.new(month: 9, day: 4)]) )] ) )] ) batch_month = BatchMonths.make month: BatchMonths::MAR expect(described_class.query(client_id: client.id) .accounts_with_period(batch_months: batch_month)) .to match_array [] end it 'rejects account that are flats' do client = client_create( properties: [property_new(human_ref: Property::MAX_HOUSE_HUMAN_REF + 1, account: account_create( charges: [charge_new( cycle: cycle_new(name: 'Feb-due-on', due_ons: [DueOn.new(month: 3, day: 4), DueOn.new(month: 9, day: 4)]) )] ))] ) batch_month = BatchMonths.make month: BatchMonths::MAR expect(described_class.query(client_id: client.id) .accounts_with_period(batch_months: batch_month)) .to match_array [] end end end
require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "git-ticket" gem.summary = %Q{Checkout, create, delete or list ticket branches} gem.description = gem.summary gem.email = "reinh@reinh.com" gem.homepage = "http://github.com/reinh/git-ticket" gem.authors = ["Rein Henrichs"] gem.add_dependency 'commandant' end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end task :default => :build
# Write your code here. katz_deli = [] def line(current_line) index = 0 line_message = "" if current_line == [] line_message = "The line is currently empty." puts line_message return end while index < current_line.length do if index == 0 message = "The line is currently: " + (index + 1).to_s + ". " + current_line[index] else message = message + (index + 1).to_s + ". " + current_line[index] end if (index + 1) < current_line.length message = message + " " end index += 1 end puts message end def take_a_number(current_line, name) line_number = (current_line.length + 1).to_s if current_line == [] puts "Welcome, " + name + ". You are number 1 in line." else puts "Welcome, " + name + ". You are number " + line_number + " in line." end current_line.push(name) return current_line end def now_serving(current_line) if current_line == [] puts "There is nobody waiting to be served!" else message = "Currently serving " + current_line[0] + "." puts message current_line.shift end end
helper = Module.new do def current_account current_user.account end def current_user # HACK: I can't access session variables easily, but there are other ways how to get what I want :) begin # provider side username = find(:css, '#user_widget .username', visible: :all).text(:all).strip rescue Capybara::ElementNotFound # buyer side username = find('#sign-out-button')[:title].gsub('Sign Out','').strip end assert username, "could not find username in the ui" current_domain = URI.parse(current_url).host site_account = Account.find_by_domain(current_domain) site_account ||= (p = Account.find_by_self_domain!(current_domain)) && p.provider_account site_account.buyer_users.find_by_username!(username) end end World(helper)
require "global/globalDef" require "global/tagAttribute" module Jabverwock using StringExtension using ArrayExtension using SymbolExtension #this class manage html tag class TagManager attr_accessor :name, :tagAttribute, :isSingleTag, :closeStringNotRequire, :tempOpenString, :tempCloseString attr_accessor :withBreak attr_accessor :comment def initialize resetTags end # initialize tags def resetTags @tempOpenString, @tempCloseString, @name, @attributeString = "","", "", "" @doctype = "" #DOCTYPE only use @tagAttribute = TagAttribute.new @isSingleTag, @closeStringNotRequire, @withBreak = false, false, false @comment = "" end # add attribute # @param [String] tag tag name # @param [String] val value def tagAttr (tag, val) eval"@tagAttribute.add_#{tag}(val)" self end # add attribute string def addAttribute if !@tagAttribute.aString.empty? KString.isString?(@attributeString) @attributeString = KString.addSpace(@tagAttribute.aString) end end # set doc type # @param [String] str doc type def setDocType(str) @doctype = str end # whether @name is Hr tag # @return [Bool] def isHrTag @name == "hr" ? true : false end # whether @name is Br tag # @return [Bool] def isBrTag @name == "br" ? true : false end # whether @name is doctype tag # @return [Bool] def isDocType @name == "doctype"? true: false end # whether @name is script tag # @return [Bool] def isScriptTag @name == "script" ? true : false end def isComment @name == "comment"? true: false end # #### open and close string ################### # TODO refactoring with openStringReplace and closeStringReplace # # @example # tm = TagManager.new # tm.tempOpenString = "aaa" # tm.openStringReplace("a","b") # expect(tm.tempOpenString).to eq "bbb" def openStringReplace(of,with) @tempOpenString = KString.reprace(str: @tempOpenString, of: of, with: with) end # @example # tm = TagManager.new # tm.tempCloseString = "aaa" # tm.closeStringReplace("a","b") # expect(tm.tempCloseString).to eq "bbb" def closeStringReplace(of, with) @tempCloseString = KString.reprace(str: @tempCloseString, of: of, with: with) end # make doctype tag # default value is "html", if you want to change , set @doctype def openStringDocType if @doctype.empty? @doctype = "html" #default html5 end addAttribute @tempOpenString = "<" + "!DOCTYPE" + $SPC + @doctype + @attributeString + ">" end def commentTag @tempOpenString = "<!-- #{@comment} -->" end # make open string, open string is like <p> and <html> def openString nameCheck return openStringDocType if isDocType return commentTag if isComment if isHrTag || isBrTag return "" end addAttribute @tempOpenString = "<" + @name + @attributeString + ">" end # whether name is empty? def nameCheck if @name.empty? assert_raise{ p ">>> call no name" } end end # TODO add test and refactoring closeStringHrTag and breakTreat def closeStringHrTag @tempCloseString = "<#{@name}>" breakTreat # if @withBreak # @tempCloseString << $BR # end # @tempCloseString end # insert br tag if you want, set by @withBreak def breakTreat if @withBreak @tempCloseString << $BR end @tempCloseString end # make close string like, </p> and </html> def closeString # closeStringNotRequire => bool値に変更する # // not require # /// meta, img if @name.empty? || isDocType || isSingleTag || closeStringNotRequire || isComment return @tempCloseString = "" end if isHrTag return closeStringHrTag end if isBrTag return @tempCloseString = "<#{@name}>" end @tempCloseString = "</#{@name}>" breakTreat end end end __END__
require 'test_helper' class ProductTest < ActiveSupport::TestCase ## Validation tests test "product attributes must not be empty" do product = Product.new assert product.invalid? assert product.errors[:title].any? assert product.errors[:description].any? assert product.errors[:price].any? assert product.errors[:image_url].any? end test "product price must be positive" do product = Product.new(title: 'Nokia', description: 'Connecting people.', image_url: 'xxxxxxx.jpg') product.price = -1 assert product.invalid? assert_equal ["must be greater than or equal to 0.01"], product.errors[:price] product.price = 0 assert product.invalid? assert_equal ["must be greater than or equal to 0.01"], product.errors[:price] product.price = 1 assert product.valid? end # Testing for image format validation def new_product(image_url) Product.new(title: 'Nokia', description: 'Connecting people.', price: 1, image_url: image_url) end test "image url" do ok = %w{ htc.gif htc.jpg htc.png HTC.JPG HTC.Jpg http://a.b.c/x/y/z/htc.gif } bad = %w{ htc.doc htc.gif/more htc.gif.more } ok.each do |name| assert new_product(name).valid?, "#{name} shouldn't be invalid" end bad.each do |name| assert new_product(name).invalid?, "#{name} shouldn't be valid" end end test "product is not valid without a unique title" do product = Product.new(title: products(:xiaomi).title, description: "Podroba", price: 1, image_url: "refurbished.gif") assert product.invalid? assert_equal ["has already been taken"], product.errors[:title] end end
dir = File.dirname(__FILE__) $: << File.expand_path("#{dir}") require "json" require "util" class Schema def initialize(h={}) @schema=Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) } @schema.merge! JSON.parse(h.to_json) # ensures consistent string keys @values = [] @keys = [] end def extractor(obj) @keys.concat Util.json_keys(obj) @values.concat Util.json_values(obj) end def values_for(key) r = [] matches = @values.find_all { |v| v.has_key?(key) } matches.each { |v| r << v[key] } r.uniq end def all_keys @keys.uniq.sort end def all_values @values.uniq end def fetch_key(key, hsh=@schema) if hsh.respond_to?(:key?) && hsh.key?(key) return hsh[key].is_a?(Hash) ? Schema.new(hsh[key]) : hsh[key] elsif hsh.respond_to?(:each) r = nil hsh.find do |*a| r=fetch_key(key, a.last) end return r.is_a?(Hash) ? Schema.new(r) : r end end def set_key(key, value, hsh=@schema) if hsh.respond_to?(:key?) && hsh.key?(key) hsh[key] = value elsif hsh.respond_to?(:each) r = nil hsh.find do |*a| r=fetch_key(key, a.last) end r = value end end def has_key?(path) return nil if !path *parent, key = path.split('.') obj = (parent==[]) ? @schema: retrieve(parent.join('.')) return false if obj == nil return false if obj.class != Hash obj.has_key? key end def retrieve(path) result = path.split('.').inject(@schema) { |m,o| m[o] if m.class==Hash } return (result == {}) ? nil : result end def insert(path, value) *parent, last = path.split('.') insert_key last, value, parent.join('.') end def insert_key(key, value, path=nil) if path == [] || path == nil @schema[key] = value else levels = path.split('.') levels.inject(@schema) { |h, k| h[k] }[key] = value end end def to_s @schema.inspect end def to_json @schema.to_json end def summary_report(filename) opfile = File.new(filename,"w") obj = {} obj['schema'] = JSON.parse(@schema.to_json) obj['values'] = {} last = nil all_keys.each do |key| values_for(key).each do |value| obj['values'][key] = [] if last.nil? || last != key obj['values'][key] << value last = key end end opfile.puts "#{obj.to_json}" Util.log "schema doc can be viewed using Docson in the browser at #{filename}" end end
require_relative 'command_line_helpers' class Recluse < BasicObject def initialize(message) @message = message end def inspect "Recluse.new(#{@message.inspect})" end def method_missing(name, *) ::Kernel.raise "Tried to invoke the method `#{name}`. #@message" end end CommandLineHelpers.make_proving_grounds Before do @last_invocation = Recluse.new "Should have executed something on the command line before trying to access methods on the @last_invocation" CommandLineHelpers.set_proving_grounds_as_home CommandLineHelpers.kill_config_file CommandLineHelpers.kill_mustache_file end module GeneralHelpers def strip_leading(string) leading_size = string.scan(/^\s*/).map(&:size).max string.gsub /^\s{#{leading_size}}/, '' end end World GeneralHelpers
require 'm2r/request' module M2R # Mongrel2 Request Parser # @api public class Parser # Parse Mongrel2 request received via ZMQ message # # @param [String] msg Monrel2 Request message formatted according to rules # of creating it described it m2 manual. # @return [Request] # # @api public # @threadsafe true def parse(msg) sender, conn_id, path, rest = msg.split(' ', 4) headers, rest = TNetstring.parse(rest) body, _ = TNetstring.parse(rest) headers = JSON.load(headers) headers, mong = split_headers(headers) headers = Headers.new headers, true mong = Headers.new mong, true Request.new(sender, conn_id, path, headers, mong, body) end private def split_headers(headers) http = {} mongrel = {} headers.each do |header, value| if Request::MONGREL2_HEADERS.include?(header) mongrel[header.downcase] = value else http[header] = value end end return http, mongrel end end end
class CreateMessages < ActiveRecord::Migration[6.1] def change create_table :messages do |t| t.string :sender_type t.integer :sender_id t.string :receiver_type t.integer :receiver_id t.text :content t.references :conversation, null: false, foreign_key: true t.timestamps end add_index :messages, [:sender_type, :sender_id] add_index :messages, [:receiver_type, :receiver_id] end end
class PresentationTrack < Track after_create { |t| app_session.complete if complete? } def file_extension 'mp4' end def upload local_file storage.upload local_file end def thumbnail @thumbnail ||= Thumbnail.new "#{filename}.thumbnail.jpg" end def exists? storage.exists? end def complete? exists? && thumbnail.exists? end def to_json super.merge! thumbnail_url: thumbnail.presigned_read_uri.to_s end end class Thumbnail < S3Storage end
class Mailer < ActionMailer::Base default from: "from@example.com" # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.mailer.send_email.subject # def send_new_entry(entry, current_user) @greeting = "Hi" #@current_user = current_user.entries @entry = entry mail to: 'adam.overstreet@gmail.com', from: current_user.email, subject: 'Door-to-Door Donations Confirmation' end end
class Notification < ApplicationRecord enum tag: [ :job, :other ] belongs_to :administrator validates :title, :content, :tag, presence: true validates :title, length: { maximum: 30 } validates :content, length: { maximum: 500 } validates :tag, correct_tag: true class << self def select_notifications(user) where_val = [] notification = user.user_detail.user_notification tags.each_key do |k| where_val << k if notification[k] end where_val end def search_notifications(tags, q) return none if tags.blank? q.result(distinct: true).where(tag: tags).order(id: "DESC") end end end
class LostFound < ActionMailer::Base default from: "sunny1304.ad@gmail.com" def find_notification(found_item) @found_item = found_item mail(:to => @found_item.email, :subject => "found item notification") end def lost_notification(lost_item) @lost_item = lost_item mail(:to => @lost_item.email, :subject => "lost item notification") end end
class CreateExpenseProducts < ActiveRecord::Migration def change create_table :expense_products do |t| t.string :name t.float :unit_cost_price t.integer :quantity t.references :expense, index: true, foreign_key: true t.timestamps null: false end end end
class Writer < ActiveRecord::Base has_many :characters, dependent: :destroy has_many :locations, dependent: :destroy validates_uniqueness_of :handle, :password, :icon end
# frozen_string_literal: true require 'rake/extensiontask' require 'rspec/core/rake_task' spec = Gem::Specification.load('aes256gcm_decrypt.gemspec') Rake::ExtensionTask.new('aes256gcm_decrypt', spec) desc '' RSpec::Core::RakeTask.new(:spec) do |task| task.pattern = './spec/**/*_spec.rb' end desc 'Compile extension and run specs' task test: %i[compile spec]
require "mongoid_sortable_tree/engine" module MongoidSortableTree module Tree extend ActiveSupport::Concern included do include Mongoid::Tree include Mongoid::Tree::Ordering include Mongoid::Tree::Traversal field :text, :type => String field :icon, :type => String field :li_attr, :type => String field :a_attr, :type => String index :text => 1 end ## # This module implements class methods that will be available # on the document that includes MongoidSortableTree::Tree module ClassMethods def build_materialized_path(tailored_hierarchy_data: [], from_root: false, category_hierarchy: nil, klass: nil) target = from_root ? (klass.nil? ? self.roots : klass.classify.constantize.roots) : category_hierarchy.children target.each do |data| custom_display_data = { :id => data.id.to_s, :text => data.text, :icon => data.icon, :li_attr => data.li_attr, :a_attr => data.a_attr, :klass => klass, :children => build_materialized_path(category_hierarchy: data, klass: klass) } tailored_hierarchy_data << custom_display_data end tailored_hierarchy_data end def build_tree_from_root(options={}) build_materialized_path(from_root: true, klass: options[:klass]) end def build_tree_from_node(node,options={}) return_array = [] custom_display_data = { :id => node.id.to_s, :text => node.text, :icon => node.icon, :li_attr => node.li_attr, :a_attr => node.a_attr, :klass => options[:klass], :children => build_materialized_path(category_hierarchy: node, klass: options[:klass]) } return_array << custom_display_data end end end end
require 'rails_helper' RSpec.describe "cards/show", :type => :view do before(:each) do @card = assign(:card, Card.create!( :fname => "Fname", :lname => "Lname", :card_number => 1 )) end it "renders attributes in <p>" do render expect(rendered).to match(/Fname/) expect(rendered).to match(/Lname/) expect(rendered).to match(/1/) end end
class Bicycle def initialize( color, tire_size = nil) @color = color @tire_size = tire_size end def to_s "Color : #{@color} | Object_id : #{self.object_id}" end def color @color end def tire_size @tire_size end end raise StandardError.new("Bikes should have colors") unless Bicycle.new('Red').color == 'Red' raise StandardError.new("Bikes should have tire sizes") unless Bicycle.new('Red', 50).tire_size == 50
require "./workers/update_all" require 'pry' if ENV["RACK_ENV"] == "development" require 'sinatra' require "rack/cors" use Rack::Cors do |config| config.allow do |allow| allow.origins '*' allow.resource '*', :headers => :any end end def lookup(name, ref="master") Sidekiq.redis do |redis| if url = redis.get("distri/#{name}:#{ref}") redirect "#{url}?#{request.query_string}", 302 else 404 end end end get '/hi' do "Hello World!" end # TODO: Package index get '/packages.json' do 418 end get '/packages/:name.json' do lookup(params[:name]) end # Redirect to the S3 Bucket containing the package json # We transparently pass along the query string because S3's # cross origin resource sharing is shitty and doesn't properly # vary the accept origin header. # This way domains can add ?#{document.domain} and work around that get '/packages/:name/:ref.json' do lookup(params[:name], params[:ref]) end get "/test" do UpdateAll.perform_async end
#encoding: utf-8 module OrdersHelper def convert_status(status) result = "" case status when "unpay" result = "未付款" when "payed" result = "已付款" when "checked" result = "已入住" when "canceled" result = "已取消" else result = "未知" end result end end
class ReferralType < ActiveRecord::Base belongs_to :company serialize :referral_sub_category , Array scope :specific_attributes , ->{ select("id, referral_source, referral_sub_category")} scope :active_referral_type, ->{ where(status: true)} validates :referral_source , presence: true validates_each :referral_sub_category do |record, attr, value| record.errors.add(attr, 'can not be blank') if value.nil? || value.blank? end end
# input: integer # output: integer (next featured number that is greater than input) # rules: # featured number is odd number that is multiple of 7, whose digits occur once each (133 is invalid because 3 appears twice) # return next featured number that is greater than input integer # has to satisfy 3 conditions for it to be a valid featured number # return error message if there is no next featured number # data structure: integer # algorithm: # set loop # if integer is odd and is divisible by 7 and the string equivalent split into an array has same size after uniq is called on it then return the number # else return error message def featured(integer) featured = integer loop do featured += 1 if featured.odd? && featured % 7 == 0 && featured.to_s.chars.uniq.size == featured.to_s.size return featured elsif featured > 9_999_999_999 return 'There is no possible number that fulfills those requirements' end end end # or def featured(number) number += 1 number += 1 until number.odd? && number % 7 == 0 loop do number_chars = number.to_s.split('') return number if number_chars.uniq == number_chars number += 14 break if number >= 9_876_543_210 end 'There is no possible number that fulfills those requirements.' end
class Ability include CanCan::Ability def initialize(user) user ||= User.new unless user.id.nil? can :create, Event end can :read, Event can [:update, :destroy, :create_shift], Event, user: {id: user.id} can :read, Shift can [:create, :update, :destroy, :view_volunteers], Shift, user: {id: user.id} end end
# frozen_string_literal: true require "uri" module Sentry class DSN PORT_MAP = { 'http' => 80, 'https' => 443 }.freeze REQUIRED_ATTRIBUTES = %w(host path public_key project_id).freeze attr_reader :scheme, :secret_key, :port, *REQUIRED_ATTRIBUTES def initialize(dsn_string) @raw_value = dsn_string uri = URI.parse(dsn_string) uri_path = uri.path.split('/') if uri.user # DSN-style string @project_id = uri_path.pop @public_key = uri.user @secret_key = !(uri.password.nil? || uri.password.empty?) ? uri.password : nil end @scheme = uri.scheme @host = uri.host @port = uri.port if uri.port @path = uri_path.join('/') end def valid? REQUIRED_ATTRIBUTES.all? { |k| public_send(k) } end def to_s @raw_value end def server server = "#{scheme}://#{host}" server += ":#{port}" unless port == PORT_MAP[scheme] server end def csp_report_uri "#{server}/api/#{project_id}/security/?sentry_key=#{public_key}" end def envelope_endpoint "#{path}/api/#{project_id}/envelope/" end end end
require 'spec_helper' describe 'line_items', :type => :request do before (:each) do user = User.create(:email => "email@example.com", :password => "my_secure_password") visit "/users/sign_in" fill_in "Email", :with => user.email fill_in "Password", :with => user.password click_button "Sign in" end context "Import line items button" do it "goes to add line items page" do page.should have_content "Line items" click_link "Import line items" page.should have_content "Cancel" end end end
class League < ActiveRecord::Base has_many :user_leagues has_many :requests has_many :users, through: :user_leagues validates :name, presence: true ,:uniqueness => true after_create :join_url def join_url self.url = rand(36**5).to_s(36)+self.id.to_s self.save end def self.search(search) if search where('LOWER(name) LIKE ?', "%#{search.downcase}%") else all end end def request_placed(user) reqs = Request.where("league_id = ? AND user_id = ?", self.id,user.id) reqs.empty? end def users_count users = self.users return users.length end def self.sort_by_user(page,search) Kaminari.paginate_array(self.search(search).sort_by(&:users_count).reverse).page(page).per(10) end def my_pos(user) u = self.users.order("coins DESC") u.index(user)+1 end end
# encoding: UTF-8 class BillsController < ApplicationController include BillsHelper # Filter before_filter :authenticate_user! # before_filter :add_breadcrumb_index load_and_authorize_resource def index @customers = Customer.where(:user_id => current_user.id) params[:search] ||= {} @bills = Bill.search(params[:search], current_user).page(params[:page]) @active_menu = "bill" @search_bar = true respond_to do |format| format.html end end def show @bill = Bill.find(params[:id]) customers = current_user.customers my_bills = Bill.where(:customer_id => customers) if my_bills.include?(@bill) @active_menu = "bill" else not_own_object_redirection end respond_to do |format| format.html # show.html.erb format.json { render json: @bill } end end def new @bill = Bill.new :number => Bill.generate_bill_number, :date => Date.today, :year => get_current_year @customers = current_user.customers redirect_to controller: :customers, action: :new, alert: t("activerecord.attributes.customer.dependency") and return if @customers.empty? @active_menu = "bill" add_breadcrumb t("labels.actions.new"), new_bill_path respond_to do |format| format.html end end def edit @bill = Bill.find(params[:id]) @customers = current_user.customers my_bills = Bill.where(:customer_id => @customers) if my_bills.include?(@bill) @bill.year = @bill.year.to_s[0..-1] @active_menu = "bill" add_breadcrumb t("labels.actions.edit"), edit_bill_path(@bill.id) else not_own_object_redirection end end def create @bill = Bill.new(bill_params) respond_to do |format| if @bill.save format.html { redirect_to @bill, notice: t("confirmations.messages.saved") } else @customers = current_user.customers format.html { render action: "new" } end end end def update @bill = Bill.find(params[:id]) respond_to do |format| if @bill.update_attributes(bill_params) format.html { redirect_to @bill, notice: t("confirmations.messages.saved") } else @customers = current_user.customers format.html { render action: "edit" } end end end def destroy @bill = Bill.find(params[:id]) @active_menu = "project" @bill.destroy respond_to do |format| format.html { redirect_to bills_url } end end ####################################################################### private def add_breadcrumb_index add_breadcrumb t("labels.breadcrumbs.index"), customers_path, :title => t("labels.breadcrumbs.index_title") end def bill_params params.require(:bill).permit(:amount, :comment, :customer_id, :date, :month, :number, :paid, :year) end end
class DataSetSource < ApplicationRecord validates_presence_of :name validates_uniqueness_of :name has_many :data_sets def to_s name end end
class Topic < ActiveRecord::Base acts_as_taggable_on :keyword acts_as_votable belongs_to :user belongs_to :board has_many :comments , dependent: :destroy default_scope -> { order('updated_at DESC') } validates :title, presence: true, length: { maximum: 150 } validates :user_id, presence: true validates :board_id, presence: true validates :subtitle, presence: true def self.search(search) if search where('title LIKE ?', "%#{search}%") else scoped end end end
require 'spec_helper' describe 'wlp::server', :type => :define do let(:pre_condition) { 'class {"::wlp": install_src => "/tmp/wlp-javaee7-16.0.0.2.zip"}' } context 'supported operating systems' do on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) do facts end let :title do 'testserver' end context "wlp::server class with user and base dir set" do it { is_expected.to compile.with_all_deps } it { is_expected.to contain_wlp_server('testserver').with({ :base_path => '/opt/ibm/wlp', :ensure => 'present' }) } it { is_expected.to contain_wlp_server_control('testserver').with({ :base_path => '/opt/ibm/wlp', :ensure => 'running' }) } end context "wlp::server class with user and base dir set; but disabled" do let(:params) { { :enable => false } } it { is_expected.to compile.with_all_deps } it { is_expected.to contain_wlp_server('testserver').with({ :base_path => '/opt/ibm/wlp', :ensure => 'present' }) } it { is_expected.to contain_wlp_server_control('testserver').with({ :base_path => '/opt/ibm/wlp', :ensure => 'stopped' }) } end context "wlp::server class with user and base dir set; but configured to absent" do let(:params) { { :ensure => 'absent' } } it { is_expected.to compile.with_all_deps } it { is_expected.to contain_wlp_server('testserver').with({ :base_path => '/opt/ibm/wlp', :ensure => 'absent' }) } it { should_not contain_wlp_server_control('testserver') } end end end end end
class AddAttendeeTypeFields < ActiveRecord::Migration def self.up add_column :attendee_types, :type, :string add_column :attendee_types, :type_description, :text end def self.down drop_column :attendee_types, :type, :string drop_column :attendee_types, :type_description, :text end end
require 'baby_squeel/resolver' require 'baby_squeel/join' require 'baby_squeel/join_dependency' module BabySqueel class Table attr_accessor :_on, :_table attr_writer :_join def initialize(arel_table) @_table = arel_table end # See Arel::Table#[] def [](key) Nodes::Attribute.new(self, key) end def _join @_join ||= Arel::Nodes::InnerJoin end def as(alias_name) self.alias(alias_name) end # Alias a table. This is only possible when joining # an association explicitly. def alias(alias_name) clone.alias! alias_name end def alias!(alias_name) # :nodoc: self._table = _table.alias(alias_name) self end def alias? _table.kind_of? Arel::Nodes::TableAlias end # Instruct the table to be joined with a LEFT OUTER JOIN. def outer clone.outer! end def outer! # :nodoc: self._join = Arel::Nodes::OuterJoin self end # Instruct the table to be joined with an INNER JOIN. def inner clone.inner! end def inner! # :nodoc: self._join = Arel::Nodes::InnerJoin self end # Specify an explicit join. def on(node = nil, &block) clone.on!(node, &block) end def on!(node = nil, &block) # :nodoc: self._on = node || evaluate(&block) self end # Evaluates a DSL block. If arity is given, this method # `yield` itself, rather than `instance_eval`. def evaluate(&block) if block.arity.zero? instance_eval(&block) else yield(self) end end # When referencing a joined table, the tables that # attributes reference can change (due to aliasing). # This method allows BabySqueel::Nodes::Attribute # instances to find what their alias will be. def find_alias(associations = []) rel = _scope.joins _arel(associations) builder = JoinDependency::Builder.new(rel) builder.find_alias(associations) end # This method will be invoked by BabySqueel::Nodes::unwrap. When called, # there are three possible outcomes: # # 1. Join explicitly using an on clause. Just return Arel. # 2. Implicit join without using an outer join. In this case, we'll just # give a hash to Active Record, and join the normal way. # 3. Implicit join using an outer join. In this case, we need to use # Polyamorous to build the join. We'll return a Join. # def _arel(associations = []) if _on _join.new(_table, Arel::Nodes::On.new(_on)) elsif associations.any?(&:needs_polyamorous?) Join.new(associations) elsif associations.any? associations.reverse.inject({}) do |names, assoc| { assoc._reflection.name => names } end end end private def resolver @resolver ||= Resolver.new(self, [:attribute]) end def respond_to_missing?(name, *) resolver.resolves?(name) || super end def method_missing(*args, &block) resolver.resolve!(*args, &block) || super end end end
require 'test_helper' class Asciibook::Converter::InlineImageTest < Asciibook::Test def test_convert_inline_image doc = <<~EOF image:http://example.com/logo.png[] EOF html = <<~EOF <p><img src="http://example.com/logo.png" alt="logo" /></p> EOF assert_convert_body html, doc end def test_convert_inline_image_with_title doc = <<~EOF image:http://example.com/logo.png[alt, title="title"] EOF html = <<~EOF <p><img src="http://example.com/logo.png" alt="alt" title="title" /></p> EOF assert_convert_body html, doc end def test_convert_inline_image_with_imagesdir doc = <<~EOF :imagesdir: images image:logo.png[alt, title="title"] EOF html = <<~EOF <p><img src="images/logo.png" alt="alt" title="title" /></p> EOF assert_convert_body html, doc end def test_convert_image_with_size_and_link doc = <<~EOF image:http://example.com/logo.png[logo, 400, 300] EOF html = <<~EOF <p><img src="http://example.com/logo.png" alt="logo" width="400" height="300" /></p> EOF assert_convert_body html, doc end end
require 'ostruct' require 'optics-agent/instrumenters/field' require 'graphql' include OpticsAgent describe "connection" do it 'collects the correct query stats' do person_type = GraphQL::ObjectType.define do name "Person" field :firstName do type types.String resolve -> (obj, args, ctx) { sleep(0.100); return 'Tom' } end field :lastName do type types.String resolve -> (obj, args, ctx) { sleep(0.100); return 'Coleman' } end end query_type = GraphQL::ObjectType.define do name 'Query' field :person do type person_type resolve -> (obj, args, ctx) { sleep(0.050); return {} } end connection :people do type person_type.connection_type resolve -> (obj, args, ctx) { ["a", "b", "c"] } end end instrumenter = Instrumenters::Field.new instrumenter.agent = true schema = GraphQL::Schema.define do query query_type instrument :field, instrumenter end query = spy("query") allow(query).to receive(:duration_so_far).and_return(1.0) result = schema.execute('{ people(first: 2) { edges { node { firstName lastName } } } }', { context: { optics_agent: OpenStruct.new(query: query) } }) expect(result).not_to have_key("errors") expect(result).to have_key("data") expect(query).to have_received(:report_field).exactly(1 + 1 + 2 * 1 + 2 * 2).times expect(query).to have_received(:report_field) .with('Query', 'people', be_instance_of(Float), be_instance_of(Float)) expect(query).to have_received(:report_field) .exactly(2).times .with('Person', 'firstName', be_instance_of(Float), be_instance_of(Float)) expect(query).to have_received(:report_field) .exactly(2).times .with('Person', 'lastName', be_instance_of(Float), be_instance_of(Float)) end end
#!/usr/bin/env ruby require 'slack-notifier' # # author: Kei Sugano <tobasojyo@gmail.com> # # YOU NEED TO GENERATE WEBHOOK URL WITH THE FOLLOWING INSTRUCTION: # https://get.slack.help/hc/en-us/articles/115005265063-Incoming-WebHooks-for-Slack # CONFIG_PATH = "slacker/config" def guide_config(config) unless File.exist?(config) File.open(config, "w") do |f| f.puts("webhook_url=[your webhook url]") end abort("\nYou need to edit file: #{config}\n\n") end end def parse_config(config) guide_config(CONFIG_PATH) array = File.read(config).split("\n").map { |line| line.split("=") }.flatten Hash[*array] end config_hash = parse_config(CONFIG_PATH) notifier = Slack::Notifier.new(config_hash["webhook_url"]) message = "charge.created" notifier.ping message
# Represents a book of monsters class Bestiary < ActiveRecord::Base validates :name, presence: true has_many :monsters end
# Continue on Advance Classes in Ruby # Basic Class class Class_one end ## Creating objects for the class object_one = Class_one.new object_two = Class_one.new ## Comparing two objects puts object_one.object_id puts object_two.object_id puts object_one == object_two puts object_one.object_id == object_two.object_id # Creating an Alias for an object object_three = object_one ## Comparing the two puts object_one.object_id puts object_three.object_id puts object_one.object_id == object_three.object_id puts object_one == object_three # Class with the Initialize method class Class_two # Defining the initialize def initialize @username = "User #{rand(1..100)}" @password = "topsecret" @production_number = "#{("a".."z").to_a.sample}-#{rand(1..999)}" end # Instance method def info "Class_two #{@production_number} has the username #{@username}" end end ## creating objects from the class and output the initialize method object_four = Class_two.new object_five = Class_two.new ## outout the objects p object_four p object_five puts ## output instance variables of the objects p object_four.instance_variables p object_five.instance_variables puts ## output instance method puts object_four.info puts object_five.info ## You can see that the info method is added to the objects of the class here print object_four.methods.sort puts puts puts object_four.methods - Object.methods # You can override methods by defining them in the class # Example override the .to_s method class Class_three def initialize @name = "Ahmed" @age = 30 end def to_s "Hello #{@name}" end end # output object_six = Class_three.new puts object_six.to_s
class HabitDescriptionSerializer < ActiveModel::Serializer include Pundit attributes :id, :name, :summary, :description, :tag_list, :can_update, :can_delete def can_update policy(object).update? end def can_delete policy(object).destroy? end def pundit_user scope end end
MAIN_CLASS = "main" BASE_DIR = File.dirname(__FILE__) + "/" BIN_DIR = BASE_DIR + "bin" SRC_DIR = BASE_DIR + "src" TEST_DIR = BASE_DIR + "test" LIB_DIR = BASE_DIR + "libs" CLASSPATH = (Dir["#{LIB_DIR}/**/*.jar"] + [BIN_DIR, LIB_DIR]).join(":") task :compile do Dir.mkdir BIN_DIR unless File.exist? BIN_DIR #sources = Dir["#{SRC_DIR}/**/*.java"] #sources += Dir["#{TEST_DIR}/**/*.java"] #res = system "javac", "-d", BIN_DIR, "-classpath", CLASSPATH, *sources sources = Dir["#{SRC_DIR}/**/*.scala"] sources += Dir["#{TEST_DIR}/**/*.scala"] res = system "scalac", "-d", BIN_DIR, "-classpath", CLASSPATH, *sources if res puts "SUCCESS!!!" else puts "Failure on compilation. Check logs!" exit 1 end end task :run => :compile do res = system "scala", "-classpath", CLASSPATH, MAIN_CLASS end task :clean do system "rm -R bin" end
require 'rubygems' require 'digest/md5' require 'dm-core' require 'dm-timestamps' require 'dm-types' require 'dm-validations' require 'hpricot' DataMapper.setup(:default, { :adapter => 'mysql', :database => 'vcd', :username => 'root', :password => '', :host => 'localhost' }) class Vessel include DataMapper::Resource property :id, Serial property :created_at, DateTime property :ip, IPAddress property :cfe, Text, :lazy => false property :data, Text, :lazy => false has n, :vessel_clicks has n, :vessel_pilot_clicks validates_present :cfe, :data class <<self def parse(data) matched = (data =~ /<tt style=\"background-color: rgb\(0,0,0\)\">(.+)<\/tt><br\/><a href=\"http:\/\/www\.captainforever\.com\/captainsuccessor\.php\?cfe=([a-z0-9]+)\">Pilot this vessel<\/a>/m) return nil if matched == nil cfe = $2 data = Hpricot($1.gsub(/&lt([^;])/, '&lt;\1')) data.search('*').each do |node| if node.elem? case node.name.downcase when 'br', 'span' if node.attributes.respond_to? :delete_if node.attributes.delete_if { |k,v| k.downcase != 'style' } end else node.parent.children.delete(node) end elsif node.comment? node.parent.children.delete(node) end end data = data.to_s return {:cfe=>cfe, :data=>data} end end def data_trimmed data.split('<br/>').find_all do |line| line.gsub(/&nbsp;/, '') != '' end.join('<br/>') end def href "/vessels/#{id}" end def md5 return '&lt;null&gt;' if ip.nil? Digest::MD5.hexdigest(ip.to_s) end def pilot_href(track=false) return "/vessels/#{id}/pilot" if track "http://www.captainforever.com/captainsuccessor.php?cfe=#{cfe}" end end class VesselClick include DataMapper::Resource property :id, Serial property :created_at, DateTime property :ip, IPAddress property :referrer, URI, :length => 1024 belongs_to :vessel end class VesselPilotClick include DataMapper::Resource property :id, Serial property :created_at, DateTime property :ip, IPAddress property :referrer, URI, :length => 1024 belongs_to :vessel end
class User < ActiveRecord::Base require 'bcrypt' attr_accessible :email, :password, :password_confirmation, :first_name, :last_name has_secure_password has_many :list_shares has_many :lists, :through => :list_shares validates_presence_of :password, :on => :create validates_presence_of :email end
require 'spreadsheet/workbook' require 'spreadsheet/excel/offset' require 'spreadsheet/excel/writer' require 'ole/storage' module Spreadsheet module Excel ## # Excel-specific Workbook methods. These are mostly pertinent to the Excel # reader. You should have no reason to use any of these. class Workbook < Spreadsheet::Workbook include Spreadsheet::Encodings include Spreadsheet::Excel::Offset BIFF_VERSIONS = { 0x000 => 2, 0x007 => 2, 0x200 => 2, 0x300 => 3, 0x400 => 4, 0x500 => 5, 0x600 => 8, } VERSION_STRINGS = { 0x600 => 'Microsoft Excel 97/2000/XP', 0x500 => 'Microsoft Excel 95', } offset :encoding, :boundsheets, :sst attr_accessor :bof, :ole attr_writer :date_base def Workbook.open io, opts = {} Reader.new(opts).read(io) end def initialize *args super enc = 'UTF-16LE' if RUBY_VERSION >= '1.9' enc = Encoding.find enc end @encoding = enc @version = 0x600 @sst = [] end def add_shared_string str @sst.push str end def add_worksheet worksheet @changes.store :boundsheets, true super end def biff_version case @bof when 0x009 2 when 0x209 3 when 0x409 4 else BIFF_VERSIONS.fetch(@version) { raise "Unkown BIFF_VERSION '#@version'" } end end def date_base @date_base ||= DateTime.new 1899, 12, 31 end def inspect self.worksheets end def shared_string idx @sst[idx.to_i].content end def sst_size @sst.size end def uninspect_variables super.push '@sst', '@offsets', '@changes' end def version_string client VERSION_STRINGS.fetch(@version, "Unknown"), 'UTF-8' end end end end
class CartController < ApplicationController before_action :setup_cart_item!, only: [:add_item, :update_item] def show @cart = current_cart end def add_item if @cart_item.blank? @cart_item = current_cart.cart_items.build(item_id: params[:item_id]) end @cart_item.quantity += params[:quantity].to_i @cart_item.save redirect_to current_cart end def update_item @cart_item.update(quantity: params[:quantity].to_i) redirect_to current_cart end private def setup_cart_item! @cart_item = current_cart.cart_items.find_by(item_id: params[:item_id]) end end
class Conference < ActiveRecord::Base attr_accessible :name, :start, :end, :description, :pin, :open_for_anybody, :max_members, :announce_new_member_by_name, :announce_left_member_by_name belongs_to :conferenceable, :polymorphic => true, :touch => true has_many :conference_invitees, :dependent => :destroy has_many :phone_numbers, :as => :phone_numberable, :dependent => :destroy before_validation { if !self.pin.blank? self.pin = self.pin.to_s.gsub(/[^0-9]/, '') end } validates_presence_of :conferenceable_type, :conferenceable_id validates_presence_of :conferenceable validates_presence_of :name validates_presence_of :start, :if => Proc.new { |conference| !conference.end.blank? } validates_presence_of :end, :if => Proc.new { |conference| !conference.start.blank? } validates_presence_of :max_members validates_numericality_of :max_members, :only_integer => true, :greater_than => 0, :less_than => ((GsParameter.get('MAXIMUM_NUMBER_OF_PEOPLE_IN_A_CONFERENCE').nil? ? 10 : GsParameter.get('MAXIMUM_NUMBER_OF_PEOPLE_IN_A_CONFERENCE')) + 1), :allow_nil => false, :allow_blank => false validates_inclusion_of :open_for_anybody, :in => [true, false] validates_length_of :pin, :minimum => (GsParameter.get('MINIMUM_PIN_LENGTH').nil? ? 4 : GsParameter.get('MINIMUM_PIN_LENGTH')), :allow_nil => true, :allow_blank => true validate :start_and_end_dates_must_make_sense, :if => Proc.new { |conference| !conference.start.blank? && !conference.end.blank? } before_save :send_pin_email_when_pin_has_changed default_scope where(:state => 'active').order(:start) # State Machine stuff state_machine :initial => :active do end def sip_domain self.conferenceable.try(:sip_domain) end def to_s name end def list_conference require 'freeswitch_event' result = FreeswitchAPI.api_result(FreeswitchAPI.api('conference', "conference#{self.id}", 'xml_list')) if result =~ /^\<\?xml/ data = Hash.from_xml(result) if data return data.fetch('conferences',{}).fetch('conference',{}) end end return nil end def list_members(data=self.list_conference()) if data.blank? return {} end members = data.fetch('members',{}).fetch('member',{}) if members.class != Array members = [members] end members.each_with_index do |member, index| members[index][:call] = Call.where(:uuid => member['uuid']).first if !members[index][:call] members[index][:call] = Call.where(:b_uuid => member['uuid']).first if members[index][:call] members[index][:call_bleg] = true; end end end return members; end private def start_and_end_dates_must_make_sense errors.add(:end, 'must be later than the start') if self.end < self.start end def send_pin_email_when_pin_has_changed if !self.new_record? && self.conferenceable.class == User && self.pin_changed? Notifications.new_pin(self).deliver end end end
class SpecialistGroup < ActiveRecord::Base has_many :specialists has_many :portfolio_items, through: :specialists has_one :avatar, as: :imageable_single, class_name: 'Photo' has_many :received_messages, as: :recipient, class_name: 'Message' has_many :orders, as: :executor def messages; received_messages; end scope :by_specialization, ->(specialization) do # includes, not joins because otherwise each group will be repeated several times for each specialist specialization.match(/^all$/i) ? includes(:specialists) : includes(:specialists).where(specialists: {specialization: specialization }) end def positive_feedback; specialists.map(&:positive_feedback).inject(0,&:+); end def negative_feedback; specialists.map(&:negative_feedback).inject(0,&:+); end def neutral_feedback; specialists.map(&:neutral_feedback).inject(0,&:+); end def number_of_completed_orders; specialists.map(&:number_of_completed_orders).inject(0,&:+); end # TODO - fix this stubs with real db data def rating; "Д/379 (stub)"; end def description; "Опыт работы: 5 лет (stub)"; end def to_s; name; end def status; :free; end # STUB! def free?; status == :free ? 'Свободен' : 'Занят'; end def specialization; specialists.first.specialization; end # ALL specialists MUST be of the same type (specialization) end
class CreateInventories < ActiveRecord::Migration[5.1] def change create_table :inventories do |t| t.integer :character_id t.integer :equipment_id end end end
class RatingsController < ApplicationController ##################################################### FILTERS ##################################################### # Requires users to sign in before accessing action # before_filter :authenticate_user! ##################################################### SWAGGER ##################################################### # Swagger documentation swagger_controller :ratings, "Rating operations" ##################################################### RESOURCES ##################################################### # Shows a list of ratings swagger_api :index do summary "Shows a list of ratings" param :path, :id, :integer, :required, "Rating ID" param :query, :page, :integer, :optional, "Page Number" end def index @ratings = Rating.all.order("created_at desc").paginate(per_page: 5, page: params[:page]) # JRespond to JSON render json: @ratings end # Shows an individual rating swagger_api :show do summary "Show indivdual rating" param :path, :id, :integer, :required, "Rating ID" end def show if @rating = Rating.find_by(id: params[:id]) # Respond to different formats respond_to do |format| format.html # show.html.erb format.json { render json: @rating } end else # Respond to different formats respond_to do |format| format.html { redirect_to :back } format.json { render json: { message: "Rating does not exist" } } end end end # Creates a new rating swagger_api :create do summary "Creates a new rating" param :path, :id, :integer, :required, "Lender ID" param :query, :author_id, :integer, :required, "Author ID" param :form, 'rating[stars]', :integer, :required, "Stars" end def create @lender = User.find_by(id: params[:id]) @author = User.find_by(id: params[:author_id]) if @rating = @author.rate!(@lender, rating_params) flash[:success] = "Thanks for your feedback!" # Respond to different formats respond_to do |format| format.html { redirect_to checklist_users_path } format.json { render json: @rating } end else flash[:error] = @rating.errors.full_messages # Respond to different formats respond_to do |format| format.html { redirect_to checklist_users_path } format.json { render json: { message: "Unable to create rating", error: flash[:error] } } end end end # Destroy an existing rating swagger_api :destroy do summary "Destroy an existing rating" param :path, :id, :integer, :required, 'Rating ID' end def destroy if @rating = Rating.find_by(id: params[:id]) render json: @rating.destroy else render json: { message: "Rating Not Found" } end end ##################################################### PRIVATE ##################################################### private # Strong parameters def rating_params params.require(:rating).permit(:stars) end end
template '/etc/ssh/ssh-banner' do source 'ssh-banner.erb' mode '0600' owner 'root' group 'root' end case node["platform"] when "debian", "ubuntu" #do debian/ubuntu things when "redhat", "centos", "fedora" if node['platform_version'].to_f >= 7 template '/etc/ssh/sshd_config' do source 'sshd7.conf.erb' mode '0600' owner 'root' group 'root' variables( users: node['ssh']['allowed-users'] ) notifies :restart, 'service[sshd]', :immediately end else template '/etc/ssh/sshd_config' do source 'sshd.conf.erb' mode '0600' owner 'root' group 'root' variables( users: node['ssh']['allowed-users'] ) notifies :restart, 'service[sshd]', :immediately end end end service 'sshd' do supports [:start, :restart, :reload, :status] action [:enable, :start] end
class Members::AccountsController < Devise::RegistrationsController prepend_before_filter :authenticate_member_2!, :except => [:new, :create, :load_current_member] before_filter :load_surveys, :only => [:new, :create] layout Proc.new { |controller| %w{new create}.include?(controller.action_name) ? 'two_column' : (controller.request.xhr? ? 'ajax' : 'one_column') } def create super unless @member.new_record? session[:omniauth] = nil session[:omniauth_user_hash] = nil end unless cookies.encrypted[:collaborator_key].blank? if collaborator = Collaborator.find_by_key(cookies.encrypted[:collaborator_key]) @member.apply_collaborator(collaborator) cookies.encrypted[:collaborator_key] = nil end end if session[:survey_ids] and not session[:survey_ids].empty? Survey.where('id in (?) and (member_id = 0 or member_id is null)', session[:survey_ids]). update_all "member_id = #{@member.id}" session[:survey_ids] = nil end end def update if resource.update_attributes(params[resource_name]) set_flash_message :notice, :updated redirect_to edit_member_registration_path else clean_up_passwords(resource) render_with_scope :edit end end def change_password @member = current_member end def update_password @member = current_member if @member.update_attributes(params[:member]) set_flash_message :notice, :updated if is_navigational_format? sign_in :member, @member, :bypass => true respond_with @member, :location => member_change_password_path else clean_up_passwords(@member) render :action => 'change_password' end end def subscriptions @member = current_member end def update_subscriptions @member = current_member if @member.update_attributes params[:member] flash[:notice] = "Subscriptions successfully changed" redirect_to member_subscriptions_path else render :action => 'subscriptions' end end def privacy @member = current_member end def update_privacy @member = current_member if @member.update_attributes params[:member] flash[:notice] = "Privacy successfully changed" redirect_to member_privacy_path else render :action => 'subscriptions' end end def follow_toggle case params[:followable_type] when 'Survey' then @followable = Survey.find(params[:followable_id]) when 'Chart' then @followable = Chart.find(params[:followable_id]) when 'Member' then @followable = Member.find(params[:followable_id]) when 'Petition' then @followable = Petition.find(params[:followable_id]) else @followable = nil end if @followable if current_member.may_follow?(@followable) flash[:alert] = 'You cannot follow yourself.' else @following = current_member.follow_toggle!(@followable) end redirect_to params[:redirect_to_url] end end private def build_resource(*args) super if session[:omniauth] @member.apply_omniauth(session[:omniauth], session[:omniauth_user_hash]) end if session[:omniauth] @member.valid? end end def redirect_location(resource_name, resource) member_return_to end def load_surveys if session[:survey_ids] and session[:survey_ids].length > 0 @surveys = Survey.where('id in (?) and (member_id = 0 or member_id is null)', session[:survey_ids]).limit(3) end end end
class GraphWidget attr_reader :data_points, :title, :template def initialize(data_points, title) @data_points = data_points @title = title @template = :"widgets/graph" end end
require 'douban_api' require 'hashie' require 'hashie/mash' require FreeKindleCN::CONFIG_PATH + "/douban" class DoubanHelper class << self def auth_url Douban.authorize_url(:redirect_uri => DOUBAN_CALLBACK, :scope => DOUBAN_SCOPE) end # code is from param[:code] def handle_callback(code) resp = Douban.get_access_token(code, :redirect_uri => DOUBAN_CALLBACK) save_config(resp) end def client @client ||= Douban.client(YAML::load_file(config_file)) end def lookup(isbn) if isbn.to_s.empty? logger.info "Douban: invalid ISBN" false else client.isbn(isbn) end rescue Douban::Error => e if e.code == 6000 # book_not_found logger.info "Douban: cannot find ISBN #{isbn}" false elsif e.code == 106 # access_token_has_expired refresh_client logger.info "Douban: token has been refreshed, retry..." # try again lookup(isbn) else raise end end def refresh_client resp = client.refresh save_config(resp) client end private def config_file FreeKindleCN::CONFIG_PATH + "/douban.yml" end def save_config(resp) # save douban config to yml File.open(config_file, 'w') do |f| YAML.dump(resp, f) end end end end
# frozen_string_literal: true ActiveAdmin.register School do menu :priority => 5 sidebar :versions, :partial => "admin/version", :only => :show controller do def create PaperTrail.enabled = false super PaperTrail.enabled = true end end actions :all, except: [:destroy, :new] #just show filter :name filter :active index do column :name column(:active, sortable: :active) do |school| render(partial: 'schools/activation_links_container', locals: { school: school, action: 'index' }) end actions end # This method creates a link that we refer to in _version.html.erb this way: history_admin_school_path(resource) member_action :history do @versioned_object = School.find(params[:id]) @versions = PaperTrail::Version.where(item_type: 'School', item_id: @versioned_object.id).order('created_at ASC') render partial: 'admin/history' end member_action :activate, method: :put do school = School.find(params[:id]) school.active = true school.save if request.format == :html redirect_to admin_school_path(school) else render js: "activateSchool(#{school.id}, true);" end end member_action :inactivate, method: :put do school = School.find(params[:id]) school.active = false school.save if request.format == :html redirect_to admin_school_path(school) else render js: "activateSchool(#{school.id}, false);" end end show name: proc { school = School.includes(versions: :item).find(params[:id]) school_version = school.versions[(params[:version].to_i - 1).to_i].reify # if there's a bug with turning the paper trail into an object (with reify) then display the school instead of a school version school_version = (school_version || school) school_version.name } do |school| return if params[:version] == '0' # choose which version's data to display if params[:version] school_with_versions = School.includes(versions: :item).find(params[:id]) school_with_version = school_with_versions.versions[(params[:version].to_i - 1).to_i].reify else school_with_version = school end attributes_table do row 'Name' do school_with_version.name end row 'Code' do school_with_version.code end row 'Borough' do school_with_version.borough end end end controller do #Setting up Strong Parameters #You must specify permitted_params within your users ActiveAdmin resource which reflects a users's expected params. def permitted_params params.permit school: [:name, :code, :active, :address_line_1, :address_line_2, :state, :postal_code, :phone_number, :borough] end end end
class AddColumnChipTweets < ActiveRecord::Migration[5.2] def change add_column :chip_tweets, :tweet_id, :string add_column :chip_tweets, :user_id, :string add_column :chip_tweets, :category, :string add_column :chip_tweets, :chip_on, :date add_column :chip_tweets, :command, :string add_column :chip_tweets, :chip_to, :string add_column :chip_tweets, :amount, :float add_column :chip_tweets, :text, :string end end
# == Schema Information # # Table name: abuse_reports # # id :integer not null, primary key # reporter_id :integer # user_id :integer # message :text # created_at :datetime # updated_at :datetime # FactoryGirl.define do factory :abuse_report do reporter factory: :user user message 'User sends spam' end end
require 'spec_helper' require 'support/hydra_spec_helper' include HydraSpecHelper describe GamesController do render_views before do @game = FactoryGirl.build(:game) stub_hydra stub_for_show_game(@game) end after { clear_get_stubs } describe "GET 'index'" do context "when not passing optional params for a particular week" do before do stub_for_game_index([@game]) get :index end it "should be successful" do response.should be_success end it "should assign @schedule" do assigns(:schedule).should be_an(Array) assigns(:schedule).should_not be_empty assigns(:schedule).first.should be_a(Wildcat::Game) assigns(:schedule).first.id.should eq @game.id (1..17).to_a.should include assigns(:schedule).sample.week end it "should render 'games/index'" do response.should render_template('games/index') end end context "when passing optional params for a particular week" do before do @game = FactoryGirl.build(:game, week: 1) stub_for_game_index([@game], week: 1) get :index, week: 1 end it "should be successful" do response.should be_success end it "should assign @schedule" do assigns(:schedule).should be_an(Array) assigns(:schedule).should_not be_empty assigns(:schedule).first.should be_a(Wildcat::Game) assigns(:schedule).first.id.should eq @game.id assigns(:schedule).sample.week.should be(1) end it "should render 'games/index'" do response.should render_template('games/index') end end end describe "GET 'show'" do before { get :show, id: @game.id } it "should be successful" do response.should be_success end it "should assign @game" do assigns(:game).should_not be_nil assigns(:game).should be_a(Wildcat::Game) assigns(:game).id.should eq @game.id end it "should render 'games/show'" do response.should render_template('games/show') end end end
class CreateHttpRequestLoggers < ActiveRecord::Migration def change create_table :http_request_loggers do |t| t.string :caller t.string :uri t.string :request t.text :response t.timestamps end end end
#!/usr/bin/env ruby # Tag both semver and ruby format version ver = ARGV[0] || begin require File.expand_path('../lib/bootstrap-sass/version.rb', File.dirname(__FILE__)) Bootstrap::VERSION end ver = "v#{ver}" unless ver.start_with?('v') sem_ver = ver.reverse.split('.', 2).join('-').reverse system <<-SH set -x git tag -a -m #{ver} #{ver} git tag -a -m #{sem_ver} #{sem_ver} SH
require 'active_support/concern' module HasImage extend ActiveSupport::Concern module ClassMethods def max_size self.get_max_size({ env: ENV['MAX_UPLOAD_SIZE'], config: CheckConfig.get('uploaded_file_max_size', nil, :integer), default: 1.megabyte }) end end included do include HasFile mount_uploader :file, ImageUploader validates :file, size: true, file_size: { less_than: UploadedImage.max_size, message: :image_too_large, max_size: UploadedImage.max_size_readable }, allow_blank: true end def thumbnail_path self.image_path('thumbnail') end def should_generate_thumbnail? true end end
require 'builder' # schema is described here: http://www.openmarine.org/schema.aspx credentials admin/admin module Rightboat module Exports class OpenmarineExporter < ExporterBase def do_export @x = Builder::XmlMarkup.new(target: @file, indent: 1) @x.instruct! :xml, version: '1.0' @x.open_marine(version: '1.7', 'xmlns:rb' => 'rightboat.com', language: 'en', origin: 'rightboat.com', date: Time.current.iso8601) { @x.broker(code: @user.id) { # actually here could be many broker tags but for our purpose there is always 1 broker @x.broker_details { @x.company_name @user.company_name.titleize } add_offices add_boats } } end def add_offices log 'export offices' offices = @user.offices.includes(address: :country) @x.offices { offices.each do |office| @x.office(id: office.id) { @x.office_name office.name @x.email office.email @x.name { title, forename, surname = office.contact_name_parts # TODO: make these tree model fields in db @x.title title @x.forename forename @x.surname surname } @x.address office.address.all_lines @x.town office.address.town_city @x.county office.address.county @x.country office.address.country.name @x.postcode office.address.zip @x.daytime_phone office.daytime_phone @x.evening_phone office.evening_phone @x.fax office.fax @x.mobile office.mobile @x.website office.website } end } end def add_boats log 'export boats' boats = @user.boats.not_deleted.includes(:manufacturer, :model, :currency, :country, :vat_rate, :boat_images, :fuel_type, :engine_manufacturer, :drive_type, :boat_type, :category) @x.adverts { boats.each do |boat| log "export boat_id=#{boat.id}" specs = boat.boat_specifications.specs_hash @x.advert(ref: boat.id, office_id: boat.office_id, status: boat.offer_status.camelize) { @x.advert_media { primary = 'true' boat.boat_images.each do |image| next if image.deleted? || !image.file_exists? @x.media image.file.url, type: image.content_type, caption: image.caption, primary: primary, 'rb:file_mtime' => image.downloaded_at.iso8601 primary = 'false' end } @x.advert_features { @x.boat_type boat.boat_type&.name_stripped&.capitalize @x.boat_category boat.category&.name @x.new_or_used case boat.new_boat when true then 'New' when false then 'Used' end @x.vessel_lying boat.location, country: boat.country&.iso @x.asking_price boat.price.to_i, poa: boat.poa, currency: boat.currency&.name, vat_included: boat.vat_rate.try(:tax_paid?) @x.marketing_descs { @x.marketing_desc(language: 'en') { @x.cdata! boat.extra.description.to_s } } @x.manufacturer boat.manufacturer.name @x.model boat.model.name @x.other { @x.item "https://www.rightboat.com/boats-for-sale/#{boat.slug}", name: 'external_url', label: boat.display_name } } @x.boat_features { spec_item boat.name, 'name' spec_item boat.extra.owners_comment, 'owners_comment' spec_item specs.delete(:reg_details), 'reg_details' spec_item specs.delete(:known_defects), 'known_defects' spec_item specs.delete(:engine_range_nautical_miles), 'range' spec_item specs.delete(:last_serviced), 'last_serviced' spec_item specs.delete(:passengers_count), 'passenger_capacity' @x.dimensions { spec_item specs.delete(:beam_m), 'beam', unit: 'metres' spec_item specs.delete(:draft_m), 'draft', unit: 'metres' spec_item boat.length_m, 'loa', unit: 'metres' spec_item specs.delete(:lwl_m), 'lwl', unit: 'metres' spec_item specs.delete(:air_draft_m), 'air_draft', unit: 'metres' } @x.build { spec_item specs.delete(:designer), 'designer' spec_item specs.delete(:builder), 'builder' spec_item specs.delete(:where_built), 'where' spec_item boat.year_built, 'year' spec_item specs.delete(:hull_color), 'hull_colour' spec_item specs.delete(:hull_construction), 'hull_construction' spec_item specs.delete(:hull_number), 'hull_number' spec_item specs.delete(:hull_type), 'hull_type' spec_item specs.delete(:super_structure_colour), 'super_structure_colour' spec_item specs.delete(:super_structure_construction), 'super_structure_construction' spec_item specs.delete(:deck_colour), 'deck_colour' spec_item specs.delete(:deck_construction), 'deck_construction' spec_item specs.delete(:cockpit_type), 'cockpit_type' spec_item specs.delete(:control_type), 'control_type' spec_item specs.delete(:flybridge), 'flybridge', with_description: true spec_item specs.delete(:keel_type), 'keel_type' spec_item specs.delete(:ballast_kgs), 'ballast', unit: 'kgs' # TODO: check if unit is included in ballast spec_item specs.delete(:displacement_kgs), 'displacement', unit: 'kgs' } @x.galley { spec_item specs.delete(:oven), 'oven', with_description: true spec_item specs.delete(:microwave), 'microwave', with_description: true spec_item specs.delete(:fridge), 'fridge', with_description: true spec_item specs.delete(:freezer), 'freezer', with_description: true spec_item specs.delete(:heating), 'heating', type: specs.delete(:heating_type), with_description: true spec_item specs.delete(:air_conditioning), 'air_conditioning', with_description: true rb_spec_item specs, :dishwasher, with_description: true # rb_spec_item specs, :galley_hob, with_description: true # rb_spec_item specs, :sink_drainer, with_description: true # rb_spec_item specs, :washer_dryer, with_description: true # rb_spec_item specs, :overhead_lowlevel_courtesy_lighting, with_description: true # rb_spec_item specs, :hot_cold_water_system, with_description: true } @x.engine { spec_item specs.delete(:stern_thruster), 'stern_thruster', with_description: true spec_item specs.delete(:bow_thruster), 'bow_thruster', with_description: true spec_item boat.fuel_type&.name, 'fuel' spec_item specs.delete(:engine_hours), 'hours' spec_unit_item specs.delete(:cruising_speed), 'cruising_speed' spec_item specs.delete(:max_speed_knots), 'max_speed', unit: 'knots' spec_item specs.delete(:engine_horse_power), 'horse_power' # TODO: check importers - should be HP of a single engine spec_item boat.engine_manufacturer&.name, 'engine_manufacturer' spec_item specs.delete(:engine_count), 'engine_quantity' spec_unit_item specs.delete(:engine_tankage), 'tankage' spec_item specs.delete(:gallons_per_hour), 'gallons_per_hour' spec_item specs.delete(:litres_per_hour), 'litres_per_hour' spec_item specs.delete(:engine_location), 'engine_location' spec_item specs.delete(:gearbox), 'gearbox' spec_item specs.delete(:cylinders_count), 'cylinders' spec_item specs.delete(:propeller_type), 'propeller_type' spec_item specs.delete(:starting_type), 'starting_type' spec_item boat.drive_type&.name, 'drive_type' spec_item specs.delete(:cooling_system), 'cooling_system', type: specs.delete(:cooling_system_type), with_description: true } @x.navigation { spec_item specs.delete(:navigation_lights), 'navigation_lights', with_description: true spec_item specs.delete(:compass), 'compass', with_description: true spec_item specs.delete(:depth_instrument), 'depth_instrument', with_description: true spec_item specs.delete(:wind_instrument), 'wind_instrument', with_description: true spec_item specs.delete(:autopilot), 'autopilot', with_description: true spec_item specs.delete(:gps), 'gps', with_description: true spec_item specs.delete(:vhf), 'vhf', with_description: true spec_item specs.delete(:plotter), 'plotter', with_description: true spec_item specs.delete(:speed_instrument), 'speed_instrument', with_description: true spec_item specs.delete(:radar), 'radar', with_description: true } @x.accommodation { spec_item specs.delete(:cabins_count), 'cabins' spec_item specs.delete(:berths_count), 'berths' spec_item specs.delete(:toilet), 'toilet', with_description: true spec_item specs.delete(:shower), 'shower', with_description: true spec_item specs.delete(:bath), 'bath', with_description: true } @x.safety_equipment { spec_item specs.delete(:life_raft), 'life_raft', capacity: specs.delete(:life_raft_capacity), with_description: true spec_item specs.delete(:epirb), 'epirb', with_description: true spec_item specs.delete(:bilge_pump), 'bilge_pump', with_description: true spec_item specs.delete(:fire_extinguisher), 'fire_extinguisher', type: specs.delete(:fire_extinguisher_type), with_description: true spec_item specs.delete(:mob_system), 'mob_system', type: specs.delete(:mob_system_type), with_description: true } @x.rig_sails { spec_item specs.delete(:genoa), 'genoa', material: specs.delete(:genoa_material), furling: specs.delete(:genoa_furling), with_description: true spec_item specs.delete(:spinnaker), 'spinnaker', material: specs.delete(:spinnaker_material), with_description: true spec_item specs.delete(:tri_sail), 'tri_sail', material: specs.delete(:tri_sail_material), with_description: true spec_item specs.delete(:storm_jib), 'storm_jib', material: specs.delete(:storm_jib_material), with_description: true spec_item specs.delete(:mainsail), 'main_sail', material: specs.delete(:mainsail_material), with_description: true spec_item specs.delete(:winches_count), 'winches' } @x.electronics { spec_item specs.delete(:battery), 'battery', with_description: true spec_item specs.delete(:battery_charger), 'battery_charger', with_description: true spec_item specs.delete(:generator), 'generator', with_description: true spec_item specs.delete(:inverter), 'inverter', with_description: true } @x.general { spec_item specs.delete(:tv), 'television', with_description: true spec_item specs.delete(:cd_player), 'cd_player', with_description: true spec_item specs.delete(:dvd_player), 'dvd_player', with_description: true #rb_spec_item specs, :surround_sound_system, with_description: true #rb_spec_item specs, :satellite_tv, with_description: true #rb_spec_item specs, :satellite_phone, with_description: true } @x.equipment { spec_item specs.delete(:anchor), 'anchor', with_description: true spec_item specs.delete(:spray_hood), 'spray_hood', with_description: true spec_item specs.delete(:bimini), 'bimini', with_description: true spec_item specs.delete(:fenders), 'fenders', with_description: true spec_item specs.delete(:shore_power), 'shorepower', with_description: true } if specs.any? @x.rb(:additional) { # rb_spec_item specs, :water_heater, with_description: true # rb_spec_item specs, :vacuum_toilets, with_description: true # rb_spec_item specs, :holding_tanks, with_description: true # rb_spec_item specs, :anchor_winch, with_description: true # rb_spec_item specs, :covers, with_description: true # rb_spec_item specs, :bathing_platform, with_description: true # rb_spec_item specs, :hydraulic_passarelle, with_description: true # rb_spec_item specs, :garage, with_description: true # rb_spec_item specs, :tender, with_description: true # rb_spec_item specs, :stern_docking_winches, with_description: true # rb_spec_item specs, :underwater_lighting, with_description: true # rb_spec_item specs, :teak_laid_cockpit, with_description: true # rb_spec_item specs, :teak_laid_flybridge, with_description: true # rb_spec_item specs, :teak_laid_side_decks, with_description: true # rb_spec_item specs, :wetbar, with_description: true # rb_spec_item specs, :sunbather, with_description: true # rb_spec_item specs, :stainless_steel_sliding_door_to_aft_cockpit, with_description: true # rb_spec_item specs, :hydraulic_trim_tabs, with_description: true # rb_spec_item specs, :hot_cold_swimming_shower, with_description: true # rb_spec_item specs, :freshwater_capacity, :unit => specs.freshwater_capacity_units specs.keys.each { |name| rb_spec_item specs, name } } end } } end } log "exported #{boats.size} boats" end def spec_item(spec_value, spec_name, options = {}) if spec_value.present? attributes = {name: spec_name} if options.delete(:with_description) attributes['rb:description'] = spec_value if spec_value.to_s !~ /true|1|yes/i spec_value = 'True' end if options.delete(:rb_item) @x.rb :item, spec_value, attributes.merge!(options) else @x.item spec_value, attributes.merge!(options) end end end def rb_spec_item(specs, spec_name, options = {}) spec_item(specs.delete(spec_name), spec_name, options.merge!(rb_item: true)) end def spec_unit_item(spec_value, spec_name, options = {}) value, unit = extract_unit(spec_value) unit = 'litres' if unit == 'liters' spec_item value, spec_name, options.merge(unit: unit) end def extract_unit(spec_value) if spec_value.present? && spec_value =~ /([\d.]+) ([\w ]+)/ [$1, $2] else spec_value end end end end end
class MembersController < ApplicationController def index @card = Card.find_by_id(params[:card_id]) respond_to do |format| if @card format.json { render json: @card.members } else format.json { render nothing: true, status: 404 } end end end def create @board = Board.find_by_id(params[:board_id]) @card = Card.find_by_id(params[:card_id]) @member = User.find_by_id(params[:_json]) respond_to do |format| if @card.save @card.members << @member @member.boards << @board @card.activities.create(content: "#{current_user.email} added #{@member.email} to this card on #{@member.created_at.strftime('%b %-d, %Y')}") format.json { render json: @card.members } else format.json { render nothing: true, status: 404 } end end end def destroy @card = Card.find_by_id(params[:card_id]) @member = @card.members.find_by_id(params[:id]) respond_to do |format| if @member.destroy @card.activities.create(content: "#{current_user.email} removed #{@member.email} from this card on #{Time.now.strftime('%b %-d, %Y')}") format.json { render json: @card.members } else format.json { render nothing: true, status: 404 } end end end end
class SkillsController < ApplicationController def index render json: Skill.all end def update @skill = Skill.find(params[:id]) @skill.update_attributes(skill_params) render json: @skill end def skill_params params.require(:skill).permit(:active) end end
class DaysController < ApplicationController def index day = Date.today.beginning_of_month @days = current_user.days # @days = Day.all all_days = @days.map(&:date) while day <= Date.today.end_of_month if !all_days.include? day # # This allows us to build a new day modal new_day=Day.new(date: day) new_day.blurbs.build # # new_day.blurbs.build # #new_day.events.build # # new_day.image_videos.build new_day.image_videos.build @days << new_day # puts ENV['GOOGLE_API_KEY'] end day = day.next end end def new @user_id = current_user.id @day = Day.new(day_params) create end def create @user_id = current_user.id @day = Day.new(day_params) if @day.save redirect_to days_path(@days) else raise @day.errors.inspect redirect_to new_session_path # redirect_to :back end end def edit @day = Day.find(params[:id]) end def update @day = Day.find(params[:id]) if @day.update(day_params) redirect_to :back else render 'edit' end end def destroy @day = Day.find(params[:day]) @day.destroy redirect_to(:back) end private def day_params params.require(:day).permit(:id, :user_id, :date, :events_attributes => [:id, :title, :text, :start_time, :end_time], :blurbs_attributes => [:id, :text], :image_videos_attributes => [:id, :day_id, :user_id, :media, :caption]) end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception # before_action do # resource = controller_path.singularize.gsub('/', '_').to_sym # method = "#{resource}_params" # params[resource] &&= send(method) if respond_to?(method, true) # end rescue_from CanCan::AccessDenied do |exception| flash[:alert] = I18n.t(:not_authorize) redirect_to root_path end before_action :set_locale def set_locale if !params[:locale].nil? I18n.locale = params[:locale] end end protected def self.permission self.name.gsub('Controller','').singularize.split('::').last.constantize.name rescue nil end def current_ability @current_ability ||= Ability.new(current_user) end def load_permissions @current_permissions = current_user.roles.each do |role| role.permissions.collect{|i| [i.subject_class, i.action]} end end def set_user @user = User.find_by(id: ActionController::Parameters.new(id: params[:id]).permit(:id)[:id]) end def user_params params.require(:user).permit(:name, :username, :email, :password, :locked, :store_id, :cellphone, :role_id)#, rol_ids: []) end def params_id ActionController::Parameters.new(id: params[:id]).permit(:id)[:id] end end
require 'world' require 'pattern' require 'patternmaker' class Swarm < Processing::App load_library "control_panel" # how many runs of the world to try @@runs_limit = 1000 # how many steps to try before giving up and resetting @@ticks_limit = 10000 def setup size 400, 400 smooth color_mode RGB, 1.0 frame_rate 60 text_font(create_font("Helvetica", 16)); if ARGV.size > 0 @mode = :cli @pattern = ARGV[0] else @mode = :gui @stage = :pattern_maker end if @mode == :cli filename = "logs/#{@pattern}/#{Time.new.strftime "%Y-%m-%d-%H%M"}.log" unless File.exists? 'logs' Dir.mkdir 'logs' end unless File.exists? "logs/#{@pattern}" Dir.mkdir "logs/#{@pattern}" end @pattern = Pattern.new "data/patterns/#{@pattern}.ptn" @log = File.open filename, 'w' @runs = 0 reset! else @pattern_maker = PatternMaker.new control_panel do |c| c.slider(:hertz, 1..100, 10) { frame_rate @hertz.to_i } c.slider(:num_drones, 10..100, 30) { @num_drones = @num_drones.to_i } c.button :new_pattern c.button :start! c.button :reset end end end def new_pattern unless @stage == :running return end @pattern_maker = PatternMaker.new @stage = :pattern_maker end # called when the "reset" button is pressed. # sets the @should_reset semaphore, which is checked at the end of each frame. # this way, we don't reset in the middle of a step and muck everything up def reset if @stage == :running @should_reset = true end end def start! if @stage == :pattern_maker # we do not allow the empty pattern if @pattern_maker.data.select{|c| !! c}.size > 0 @pattern = Pattern.new(@pattern_maker.width, @pattern_maker.height, @pattern_maker.data) reset! end end end def reset! if @mode == :cli @num_drones = new_drone_count end @world = World.new 20, 20 (0 ... @num_drones).each do |n| @world.spawn_drone end @world.pattern = @pattern @stage = :running end def new_drone_count (rand(18) + 2) * 5 end ### DRAW (AKA MAIN) ########################################################## def draw background 1.0 if @mode == :gui if @stage == :running @world.tick @world.draw if @should_reset @should_reset = false reset! end else # if not running, display an interface for the user to create a pattern @pattern_maker.draw end end if @mode == :cli # if we're being run from the command line, don't display anything, just # keep advancing the simulation until the pattern is created or we give up while not (@world.pattern? or @world.ticks >= @@ticks_limit) @world.tick end if @world.pattern? # yay, the pattern was created! log the drone count and tick number. @log.puts "#{@num_drones}, #{@world.ticks}" # flash a green frame background 0.0, 1.0, 0.0 else # boo, we've run this for a while and the pattern hasn't shown up. # log the drone count and failure. @log.puts "#{@num_drones}, failure" # flash a red frame background 1.0, 0.0, 0.0 end @runs += 1 if @runs >= @@runs_limit @log.close exit end reset! end end ### EVENT HANDLERS ########################################################### def mouse_pressed if @stage == :pattern_maker and @pattern_maker @pattern_maker.mouse_pressed end end def key_pressed if @stage == :pattern_maker and @pattern_maker # 65535 means the key is coded, so we should send the key code if key == 65535 @pattern_maker.key_pressed key_code else @pattern_maker.key_pressed key end end end end Swarm.new :title => "Swarm"
require 'test_helper' class PracticasControllerTest < ActionController::TestCase setup do @practica = practicas(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:practicas) end test "should get new" do get :new assert_response :success end test "should create practica" do assert_difference('Practica.count') do post :create, :practica => @practica.attributes end assert_redirected_to practica_path(assigns(:practica)) end test "should show practica" do get :show, :id => @practica.to_param assert_response :success end test "should get edit" do get :edit, :id => @practica.to_param assert_response :success end test "should update practica" do put :update, :id => @practica.to_param, :practica => @practica.attributes assert_redirected_to practica_path(assigns(:practica)) end test "should destroy practica" do assert_difference('Practica.count', -1) do delete :destroy, :id => @practica.to_param end assert_redirected_to practicas_path end end
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe Mongo::Operation::Insert do require_no_multi_mongos require_no_required_api_version let(:context) { Mongo::Operation::Context.new } before do begin authorized_collection.delete_many rescue Mongo::Error::OperationFailure end begin authorized_collection.indexes.drop_all rescue Mongo::Error::OperationFailure end end let(:documents) do [{ :name => 'test' }] end let(:write_concern) do Mongo::WriteConcern.get(w: :majority) end let(:spec) do { documents: documents, db_name: authorized_collection.database.name, coll_name: authorized_collection.name, write_concern: write_concern } end let(:op) do described_class.new(spec) end after do authorized_collection.delete_many end describe '#initialize' do context 'spec' do it 'sets the spec' do expect(op.spec).to eq(spec) end end end describe '#==' do context 'spec' do context 'when two inserts have the same specs' do let(:other) do described_class.new(spec) end it 'returns true' do expect(op).to eq(other) end end context 'when two inserts have different specs' do let(:other_docs) do [{ :bar => 1 }] end let(:other_spec) do { :documents => other_docs, :db_name => 'test', :coll_name => 'coll_name', :write_concern => { 'w' => 1 }, :ordered => true } end let(:other) do described_class.new(other_spec) end it 'returns false' do expect(op).not_to eq(other) end end end end describe 'document ids' do context 'when documents do not contain an id' do let(:documents) do [{ 'field' => 'test' }, { 'field' => 'test' }] end let(:inserted_ids) do authorized_primary.with_connection do |connection| op.bulk_execute(connection, context: context).inserted_ids end end let(:collection_ids) do authorized_collection.find(field: 'test').collect { |d| d['_id'] } end it 'adds an id to the documents' do expect(inserted_ids).to eq(collection_ids) end end end describe '#bulk_execute' do before do authorized_collection.indexes.create_one({ name: 1 }, { unique: true }) end after do authorized_collection.delete_many authorized_collection.indexes.drop_one('name_1') end context 'when inserting a single document' do context 'when the insert succeeds' do let(:response) do authorized_primary.with_connection do |connection| op.bulk_execute(connection, context: context) end end it 'inserts the documents into the database' do expect(response.written_count).to eq(1) end end end context 'when inserting multiple documents' do context 'when the insert succeeds' do let(:documents) do [{ name: 'test1' }, { name: 'test2' }] end let(:response) do authorized_primary.with_connection do |connection| op.bulk_execute(connection, context: context) end end it 'inserts the documents into the database' do expect(response.written_count).to eq(2) end end end context 'when the inserts are ordered' do let(:documents) do [{ name: 'test' }, { name: 'test' }, { name: 'test1' }] end let(:spec) do { documents: documents, db_name: authorized_collection.database.name, coll_name: authorized_collection.name, write_concern: write_concern, ordered: true } end let(:failing_insert) do described_class.new(spec) end context 'when write concern is acknowledged' do let(:write_concern) do Mongo::WriteConcern.get(w: 1) end context 'when the insert fails' do it 'aborts after first error' do authorized_primary.with_connection do |connection| failing_insert.bulk_execute(connection, context: context) end expect(authorized_collection.find.count).to eq(1) end end end context 'when write concern is unacknowledged' do let(:write_concern) do Mongo::WriteConcern.get(w: 0) end context 'when the insert fails' do it 'aborts after first error' do authorized_primary.with_connection do |connection| failing_insert.bulk_execute(connection, context: context) end expect(authorized_collection.find.count).to eq(1) end end end end context 'when the inserts are unordered' do let(:documents) do [{ name: 'test' }, { name: 'test' }, { name: 'test1' }] end let(:spec) do { documents: documents, db_name: authorized_collection.database.name, coll_name: authorized_collection.name, write_concern: write_concern, ordered: false } end let(:failing_insert) do described_class.new(spec) end context 'when write concern is acknowledged' do context 'when the insert fails' do it 'does not abort after first error' do authorized_primary.with_connection do |connection| failing_insert.bulk_execute(connection, context: context) end expect(authorized_collection.find.count).to eq(2) end end end context 'when write concern is unacknowledged' do let(:write_concern) do Mongo::WriteConcern.get(w: 0) end context 'when the insert fails' do it 'does not after first error' do authorized_primary.with_connection do |connection| failing_insert.bulk_execute(connection, context: context) end expect(authorized_collection.find.count).to eq(2) end end end end end end
Pod::Spec.new do |s| s.name = 'TestPod' s.version = '1.0.0' s.summary = 'TestPod summary' s.license = 'MIT' s.authors = { 'test' => 'test@test.com' } s.homepage = 'https://www.example.com' s.source = { :git => 'https://test@test.git', :tag => '#{s.version}' } s.platform = :ios s.ios.deployment_target = '9.0' s.requires_arc = true s.public_header_files = 'Classes/Public/**/*.h' s.source_files = 'Classes/Sources/**/*.{h,m,swift,mm}' s.subspec 'SubSpecA' do |ss| ss.private_header_files = 'Classes/A/Private/**/*.{swift,h,m,mm}' ss.source_files = [ 'Classes/A/API/**/*.{swift,h,m,c,mm}', 'Classes/A/Private/DebugUI/*.{swift,h,m,c,mm}', 'Classes/A/Private/Tab/**/*.{swift,h,m,c,mm}', 'Resources/**/*.{h,m}', ] ss.resource = [ 'Resources/**/*.strings', 'Resources/**/*.bundle' ] ss.dependency 'Masonry' ss.dependency 'ReactiveObjC' ss.dependency 'SDWebImage' end s.subspec 'SubSpecB' do |ss| ss.private_header_files = 'Classes/B/Private/**/*.{h,m,mm}' ss.source_files = [ 'Classes/B/**/*.{swift,h,m,c,mm}', 'Resources/B/**/*.{h,m}', ] ss.resource = ['Resources/B/**/*.strings','Resources/B/**/*.bundle'] ss.dependency 'TestPod/A' ss.dependency 'Masonry' ss.dependency 'ReactiveObjC' end s.subspec 'SubSpecC' do |ss| ss.private_header_files = 'Classes/C/Basic/C.h' ss.source_files = [ 'Classes/C/**/*.{swift,h,m,c,mm}', 'Resources/C/**/*.{h,m}', ] ss.resource = ['Resources/C/**/*.strings','Resources/C/**/*.bundle'] ss.dependency 'TestPod/A' ss.dependency 'Masonry' ss.dependency 'ReactiveObjC' end end
require 'test_helper' class ReplyReviewsControllerTest < ActionController::TestCase setup do @reply_review = reply_reviews(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:reply_reviews) end test "should get new" do get :new assert_response :success end test "should create reply_review" do assert_difference('ReplyReview.count') do post :create, reply_review: { content: @reply_review.content, review_id: @reply_review.review_id, user_id: @reply_review.user_id } end assert_redirected_to reply_review_path(assigns(:reply_review)) end test "should show reply_review" do get :show, id: @reply_review assert_response :success end test "should get edit" do get :edit, id: @reply_review assert_response :success end test "should update reply_review" do put :update, id: @reply_review, reply_review: { content: @reply_review.content, review_id: @reply_review.review_id, user_id: @reply_review.user_id } assert_redirected_to reply_review_path(assigns(:reply_review)) end test "should destroy reply_review" do assert_difference('ReplyReview.count', -1) do delete :destroy, id: @reply_review end assert_redirected_to reply_reviews_path end end
module KMP3D class KMP3DTest def initialize(*_args) puts "------------------------------------" Data.signal_reload Data.reload(self) Data.load_kmp3d_model @passed = 0 @total = 0 end def print_results puts "------------------" puts "Passed: #{@passed}" puts "Failed: #{@total - @passed}" puts "Total: #{@total}" puts "" end def assert(value, msg) @total += 1 if value @passed += 1 else puts "* Assertion failed: #{msg}" end end def assert_euler_equal(euler1, euler2, msg) matrix1 = KMP3D::KMPMath.euler_to_matrix(*euler1) matrix2 = KMP3D::KMPMath.euler_to_matrix(*euler2) match = matrix1.zip(matrix2).all? { |e1, e2| (e1 - e2).abs < 1e-5 } # approximate for better readability euler1.map! { |o| o.radians.to_i } euler2.map! { |n| n.radians.to_i } assert(match, "#{msg} Rotation mismatch: #{euler1} != #{euler2}") end def assert_equal(v1, v2, msg) match = (v1 == v2) || \ (v1.is_a?(Float) || v2.is_a?(Float)) && (v1 - v2).abs < 1e-5 assert(match, msg + " mismatch: #{v1} != #{v2}") end end end
require 'rails_helper' RSpec.describe Localization, type: :model do before :each do @user = create(:user) @localization = create(:localization, name: 'First Localization', user: @user, main: true) @macro = create(:actor_macro, user_id: @user.id, localizations: [@localization]) end it 'Create Relation actor localization' do expect(@macro.name).to eq('Organization one') expect(@localization.name).to eq('First Localization') expect(Localization.count).to eq(1) expect(@macro.localizations.count).to eq(1) expect(@macro.main_location_name).to eq('First Localization') expect(@localization.localizable_type).to eq('Actor') end it 'Delete Relation macro localization' do @macro.destroy expect(Localization.count).to eq(0) end context 'For main localizations' do before :each do expect(@macro.localizations.count).to eq(1) @localization_new = create(:localization, name: 'Main Localization', user: @user, localizable: @macro) end it 'Set other location for actor macro as main location' do @localization_new.update_attributes(main: true) expect(@macro.localizations.count).to eq(2) expect(@macro.main_location_name).to eq('Main Localization') end end end
#!/usr/bin/env rake # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) Mizatron::Application.load_tasks namespace :lp do desc "Generate config file for lamepress" task :config do file = File.expand_path(File.dirname(__FILE__)) lamepress = File.new("#{file}/config/lamepress.yml", "w") lamepress.write("domain: \"http://www.mydomain.com\"\ntitle: \"lamepress\"\nlayout: \"demo\"") lamepress.close end end
module Refinery module WineGroups class WineGroup < Refinery::Core::BaseModel self.table_name = 'refinery_wine_groups' attr_accessible :name, :judge_id, :position acts_as_indexed :fields => [:name] validates :name, :presence => true, :uniqueness => true end end end