Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Remove exlibris-aleph requirement since it's no longer a dependency
require 'authpds' require 'exlibris-aleph' require 'require_all' require_all "#{File.dirname(__FILE__)}/authpds-nyu/" Authlogic::Session::Base.send(:include, AuthpdsNyu::Session)
require 'authpds' require 'require_all' require_all "#{File.dirname(__FILE__)}/authpds-nyu/" Authlogic::Session::Base.send(:include, AuthpdsNyu::Session)
Use read instead of readchar
require 'stringio' module OTNetstring def self.parse(io) io = StringIO.new(io) if io.respond_to? :to_str length, byte = "", "0" while byte =~ /\d/ length << byte byte = io.readchar end length = length.to_i case byte when '#' then Integer io.read(length) when ',' then io.read(length) when '~' then nil when '!' then io.read(length) == 'true' when '[', '{' array = [] start = io.pos array << parse(io) while io.pos - start < length byte == "{" ? Hash[*array] : array end end def self.encode(obj, string_sep = ',') case obj when String then "#{obj.length}#{string_sep}#{obj}" when Integer then encode(obj.inspect, '#') when NilClass then "0~" when Array then encode(obj.map { |e| encode(e) }.join, '[') when Hash then encode(obj.map { |a,b| encode(a)+encode(b) }.join, '{') when FalseClass, TrueClass then encode(obj.inspect, '!') else fail 'cannot encode %p' % obj end end end
require 'stringio' module OTNetstring def self.parse(io) io = StringIO.new(io) if io.respond_to? :to_str length, byte = "", "0" while byte =~ /\d/ length << byte byte = io.read(1) end length = length.to_i case byte when '#' then Integer io.read(length) when ',' then io.read(length) when '~' then nil when '!' then io.read(length) == 'true' when '[', '{' array = [] start = io.pos array << parse(io) while io.pos - start < length byte == "{" ? Hash[*array] : array end end def self.encode(obj, string_sep = ',') case obj when String then "#{obj.length}#{string_sep}#{obj}" when Integer then encode(obj.inspect, '#') when NilClass then "0~" when Array then encode(obj.map { |e| encode(e) }.join, '[') when Hash then encode(obj.map { |a,b| encode(a)+encode(b) }.join, '{') when FalseClass, TrueClass then encode(obj.inspect, '!') else fail 'cannot encode %p' % obj end end end
Determine Regtest version and add it to development dependencies only if it is not yet set in Rakefile.
# -- encoding: utf-8 -- require 'regtest/task' class Rim # ALL regtest files incl. sample files, results files # and maybe other files (default: <tt>REGTEST_FILES</tt>) attr_accessor :regtest_files # Sample files (Ruby files) for regtest (default: <tt>REGTEST_FILES_RB</tt>) attr_accessor :regtest_files_rb end Rim.defaults do regtest_files_rb ::REGTEST_FILES_RB regtest_files ::REGTEST_FILES end Rim.after_setup do if feature_loaded? 'rim/gem' self.gem_files += regtest_files development_dependencies << %w(regtest ~>1.0) end if regtest_files_rb != REGTEST_FILES_RB (::REGTEST_FILES_RB.clear << regtest_files_rb).flatten! end if regtest_files != REGTEST_FILES (::REGTEST_FILES.clear << regtest_files).flatten! end end
# -- encoding: utf-8 -- require 'regtest/task' class Rim # ALL regtest files incl. sample files, results files # and maybe other files (default: <tt>REGTEST_FILES</tt>) attr_accessor :regtest_files # Sample files (Ruby files) for regtest (default: <tt>REGTEST_FILES_RB</tt>) attr_accessor :regtest_files_rb end Rim.defaults do regtest_files_rb ::REGTEST_FILES_RB regtest_files ::REGTEST_FILES end Rim.after_setup do if feature_loaded? 'rim/gem' self.gem_files += regtest_files unless development_dependencies.flatten.include? 'regtest' begin require 'regtest/version' v = Regtest::VERSION.sub(/\.\d+(?:\.?\w+)?$/, '') development_dependencies << %W(regtest ~>#{v}) rescue LoadError development_dependencies << %w(regtest ~>1.0) end end end if regtest_files_rb != REGTEST_FILES_RB (::REGTEST_FILES_RB.clear << regtest_files_rb).flatten! end if regtest_files != REGTEST_FILES (::REGTEST_FILES.clear << regtest_files).flatten! end end
Add parent_url no parent test.
require 'spec_helper' require 'compo' # Mock implementation of UrlReferenceable. class MockUrlReferenceable include Compo::UrlReferenceable end describe MockUrlReferenceable do before(:each) { allow(subject).to receive(:parent).and_return(parent) } describe '#url' do context 'when the UrlReferenceable has no parent' do let(:parent) { nil } it 'returns the empty string' do expect(subject.url).to eq('') end end context 'when the UrlReferenceable has a parent' do let(:parent) { double(:parent) } end end describe '#parent_url' do context 'when the UrlReferenceable has no parent' do let(:parent) { nil } end context 'when the UrlReferenceable has a parent' do let(:parent) { double(:parent) } end end end
require 'spec_helper' require 'compo' # Mock implementation of UrlReferenceable. class MockUrlReferenceable include Compo::UrlReferenceable end describe MockUrlReferenceable do before(:each) { allow(subject).to receive(:parent).and_return(parent) } describe '#url' do context 'when the UrlReferenceable has no parent' do let(:parent) { nil } it 'returns the empty string' do expect(subject.url).to eq('') end end context 'when the UrlReferenceable has a parent' do let(:parent) { double(:parent) } end end describe '#parent_url' do context 'when the UrlReferenceable has no parent' do let(:parent) { nil } specify { expect(subject.parent_url).to be_nil } end context 'when the UrlReferenceable has a parent' do let(:parent) { double(:parent) } end end end
Add reference to schools field
class CreatePrograms < ActiveRecord::Migration def change create_table :programs do |t| t.string :program_code t.string :program_name t.string :dbn t.string :printed_school_name t.string :interest_area t.string :selection_method t.string :selection_method_abbrevi t.string :directory_page_ t.string :borough t.string :urls t.timestamps end end end
class CreatePrograms < ActiveRecord::Migration def change create_table :programs do |t| t.string :program_code t.string :program_name t.string :dbn t.string :printed_school_name t.string :interest_area t.string :selection_method t.string :selection_method_abbrevi t.string :directory_page_ t.string :borough t.string :urls t.references :school t.timestamps end end end
Document can be 100% Loofah
require 'action_view/helpers' if defined?(Rails) require 'action_view/context' if defined?(Rails) require 'nokogiri' require 'loofah' module InlineSvg module ActionView module Helpers def inline_svg(filename, options={}) file = File.read(Rails.root.join('app', 'assets', 'images', filename)) doc = Nokogiri::HTML::DocumentFragment.parse file # remove comments from svg file if options[:nocomment].present? doc = Loofah.fragment(doc.to_s).scrub!(:strip) end svg = doc.at_css 'svg' if options[:class] svg['class'] = options[:class] end %i(title desc).each do |child| if options[child].present? node = Nokogiri::XML::Node.new(child.to_s, doc) node.content = options[child] svg.add_child node end end doc.to_html.html_safe end end end end
require 'action_view/helpers' if defined?(Rails) require 'action_view/context' if defined?(Rails) require 'nokogiri' require 'loofah' module InlineSvg module ActionView module Helpers def inline_svg(filename, options={}) file = File.read(Rails.root.join('app', 'assets', 'images', filename)) doc = Loofah::HTML::DocumentFragment.parse file # remove comments from svg file if options[:nocomment].present? doc.scrub!(:strip) end svg = doc.at_css 'svg' if options[:class] svg['class'] = options[:class] end %i(title desc).each do |child| if options[child].present? node = Nokogiri::XML::Node.new(child.to_s, doc) node.content = options[child] svg.add_child node end end doc.to_html.html_safe end end end end
Revert "Marks 'should show the courses tray upon clicking' as pending"
require File.expand_path(File.dirname(__FILE__) + '/common') describe 'Global Navigation' do include_examples 'in-process server selenium tests' context 'As a Teacher' do before do course_with_teacher_logged_in Account.default.enable_feature! :use_new_styles end describe 'Courses Link' do it 'should show the courses tray upon clicking' do pending 'https://gerrit.instructure.com/#/c/56046/9 needs merging first' get "/" f('#global_nav_courses_link').click wait_for_ajaximations expect(f('.ReactTray__primary-content')).to be_displayed end end describe 'LTI Tools' do it 'should show the Commons logo/link if it is enabled' do Account.default.enable_feature! :lor_for_account @teacher.enable_feature! :lor_for_user @tool = Account.default.context_external_tools.new({ :name => "Commons", :domain => "canvaslms.com", :consumer_key => '12345', :shared_secret => 'secret' }) @tool.set_extension_setting(:global_navigation, { :url => "canvaslms.com", :visibility => "admins", :display_type => "full_width", :text => "Commons" }) @tool.save! get "/" expect(f('.ic-icon-svg--commons')).to be_displayed end end end end
require File.expand_path(File.dirname(__FILE__) + '/common') describe 'Global Navigation' do include_examples 'in-process server selenium tests' context 'As a Teacher' do before do course_with_teacher_logged_in Account.default.enable_feature! :use_new_styles end describe 'Courses Link' do it 'should show the courses tray upon clicking' do get "/" f('#global_nav_courses_link').click wait_for_ajaximations expect(f('.ReactTray__primary-content')).to be_displayed end end describe 'LTI Tools' do it 'should show the Commons logo/link if it is enabled' do Account.default.enable_feature! :lor_for_account @teacher.enable_feature! :lor_for_user @tool = Account.default.context_external_tools.new({ :name => "Commons", :domain => "canvaslms.com", :consumer_key => '12345', :shared_secret => 'secret' }) @tool.set_extension_setting(:global_navigation, { :url => "canvaslms.com", :visibility => "admins", :display_type => "full_width", :text => "Commons" }) @tool.save! get "/" expect(f('.ic-icon-svg--commons')).to be_displayed end end end end
Make sure assets compile for heroku
require_relative 'boot' require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" require "action_cable/engine" require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module SorryYouFeelThatWay class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.1 # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Don't generate system test files. config.generators.system_tests = nil #let Heroku serve assets config.serve_static_assets = true end end
require_relative 'boot' require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" require "action_cable/engine" require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module SorryYouFeelThatWay class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.1 # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Don't generate system test files. config.generators.system_tests = nil #let Heroku serve assets config.assets.compile = true config.serve_static_assets = true end end
Fix sqlite3 version to 1.3.x
# frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'flog/version' Gem::Specification.new do |spec| spec.name = 'rails-flog' spec.version = Flog::VERSION spec.authors = ['pinzolo'] spec.email = ['pinzolo@gmail.com'] spec.description = 'This formats parameters and sql in rails log.' spec.summary = 'Rails log formatter for parameters and sql' spec.homepage = 'https://github.com/pinzolo/rails-flog' spec.license = 'MIT' spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_development_dependency 'bundler' spec.add_development_dependency 'coveralls' spec.add_development_dependency 'minitest' spec.add_development_dependency 'rake' spec.add_development_dependency 'rubocop' spec.add_development_dependency 'sqlite3' spec.add_dependency 'anbt-sql-formatter', '>=0.0.7' spec.add_dependency 'awesome_print' spec.add_dependency 'rails', '>=4.2.0' end
# frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'flog/version' Gem::Specification.new do |spec| spec.name = 'rails-flog' spec.version = Flog::VERSION spec.authors = ['pinzolo'] spec.email = ['pinzolo@gmail.com'] spec.description = 'This formats parameters and sql in rails log.' spec.summary = 'Rails log formatter for parameters and sql' spec.homepage = 'https://github.com/pinzolo/rails-flog' spec.license = 'MIT' spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_development_dependency 'bundler' spec.add_development_dependency 'coveralls' spec.add_development_dependency 'minitest' spec.add_development_dependency 'rake' spec.add_development_dependency 'rubocop' spec.add_development_dependency 'sqlite3', '~> 1.3.0' spec.add_dependency 'anbt-sql-formatter', '>=0.0.7' spec.add_dependency 'awesome_print' spec.add_dependency 'rails', '>=4.2.0' end
Add restart timeout so that we don't wait forever for an app restart
execute "gem uninstall puma" do only_if "gem list | grep puma" end include_recipe "nginx" directory "/etc/nginx/shared" directory "/etc/nginx/http" directory "/etc/nginx/ssl" node[:deploy].each do |application, deploy| puma_config application do directory deploy[:deploy_to] environment deploy[:rails_env] logrotate deploy[:puma][:logrotate] thread_min deploy[:puma][:thread_min] thread_max deploy[:puma][:thread_max] workers deploy[:puma][:workers] worker_timeout deploy[:puma][:worker_timeout] end end
execute "gem uninstall puma" do only_if "gem list | grep puma" end include_recipe "nginx" directory "/etc/nginx/shared" directory "/etc/nginx/http" directory "/etc/nginx/ssl" node[:deploy].each do |application, deploy| puma_config application do directory deploy[:deploy_to] environment deploy[:rails_env] logrotate deploy[:puma][:logrotate] thread_min deploy[:puma][:thread_min] thread_max deploy[:puma][:thread_max] workers deploy[:puma][:workers] worker_timeout deploy[:puma][:worker_timeout] restart_timeout deploy[:puma][:restart_timeout] || 120 end end
Use condition variable to be notified of RPC responses
#!/usr/bin/env ruby # encoding: utf-8 require "bunny" conn = Bunny.new(:automatically_recover => false) conn.start ch = conn.create_channel class FibonacciClient attr_reader :reply_queue def initialize(ch, server_queue) @ch = ch @x = ch.default_exchange @server_queue = server_queue @reply_queue = ch.queue("", :exclusive => true) end def call(n) correlation_id = self.generate_uuid @x.publish(n.to_s, :routing_key => @server_queue, :correlation_id => correlation_id, :reply_to => @reply_queue.name) response = nil @reply_queue.subscribe(:block => true) do |delivery_info, properties, payload| if properties[:correlation_id] == correlation_id response = payload.to_i delivery_info.consumer.cancel end end response end protected def generate_uuid # very naive but good enough for code # examples "#{rand}#{rand}#{rand}" end end client = FibonacciClient.new(ch, "rpc_queue") puts " [x] Requesting fib(30)" response = client.call(30) puts " [.] Got #{response}" ch.close conn.close
#!/usr/bin/env ruby # encoding: utf-8 require "bunny" require "thread" conn = Bunny.new(:automatically_recover => false) conn.start ch = conn.create_channel class FibonacciClient attr_reader :reply_queue attr_accessor :response, :call_id attr_reader :lock, :condition def initialize(ch, server_queue) @ch = ch @x = ch.default_exchange @server_queue = server_queue @reply_queue = ch.queue("", :exclusive => true) @lock = Mutex.new @condition = ConditionVariable.new that = self @reply_queue.subscribe do |delivery_info, properties, payload| if properties[:correlation_id] == that.call_id that.response = payload.to_i that.lock.synchronize{that.condition.signal} end end end def call(n) self.call_id = self.generate_uuid @x.publish(n.to_s, :routing_key => @server_queue, :correlation_id => call_id, :reply_to => @reply_queue.name) lock.synchronize{condition.wait(lock)} response end protected def generate_uuid # very naive but good enough for code # examples "#{rand}#{rand}#{rand}" end end client = FibonacciClient.new(ch, "rpc_queue") puts " [x] Requesting fib(30)" response = client.call(30) puts " [.] Got #{response}" ch.close conn.close
Use iter[] instead of get_value/set_value methods
#!/usr/bin/env ruby =begin combobox_from_cellrender.rb - Ruby/GTK sample script Copyright (c) 2002-2015 Ruby-GNOME2 Project Team This program is licenced under the same licence as Ruby-GNOME2. =end require "gtk3" window = Gtk::Window.new "Combobox with CellRender" lstore = Gtk::ListStore.new(TrueClass, String) (1..5).each do |i| lstore.append.set_values([false, "item#{i}"]) end combobox = Gtk::ComboBox.new(:model => lstore, :entry => true) toggle = Gtk::CellRendererToggle.new toggle.signal_connect "toggled" do |widget, path| puts widget.class puts path.class end combobox.pack_start(toggle, true) combobox.add_attribute(toggle, "active", 0) combobox.set_entry_text_column(1) window.add combobox combobox.signal_connect("changed") do |widget| list = widget.model list.each do |model, _path, iter| model.set_value(iter, 0, false) end iter = widget.active_iter puts iter.inspect puts "#{list.get_value(iter, 0)} #{list.get_value(iter, 1)}" list.set_value(iter, 0, true) end window.signal_connect("destroy") { Gtk.main_quit } window.show_all Gtk.main
#!/usr/bin/env ruby =begin combobox_from_cellrender.rb - Ruby/GTK sample script Copyright (c) 2002-2015 Ruby-GNOME2 Project Team This program is licenced under the same licence as Ruby-GNOME2. =end require "gtk3" window = Gtk::Window.new "Combobox with CellRender" lstore = Gtk::ListStore.new(TrueClass, String) (1..5).each do |i| lstore.append.set_values([false, "item#{i}"]) end combobox = Gtk::ComboBox.new(:model => lstore, :entry => true) toggle = Gtk::CellRendererToggle.new toggle.signal_connect "toggled" do |widget, path| puts widget.class puts path.class end combobox.pack_start(toggle, true) combobox.add_attribute(toggle, "active", 0) combobox.set_entry_text_column(1) window.add combobox combobox.signal_connect("changed") do |widget| list = widget.model list.each do |_model, _path, iter| iter[0] = false end iter = widget.active_iter puts iter.inspect puts "#{iter[0]} #{iter[1]}" iter[0] = true end window.signal_connect("destroy") { Gtk.main_quit } window.show_all Gtk.main
Install thoughtbot's `gitsh` with git cookbook
# # Cookbook Name:: git # Recipe:: default # # Copyright (C) 2013 Logan Koester # # All rights reserved - Do Not Redistribute # include_recipe 'pacman' package('git') { action :install } git "#{Chef::Config[:file_cache_path]}/git-extras" do repository 'git://github.com/visionmedia/git-extras.git' reference 'master' action :sync end bash "compile and install git-extras" do cwd "#{Chef::Config[:file_cache_path]}/git-extras" code 'sudo make install' end %w{ autoconf automake bison flex xclip }.each do |pkg| package(pkg) { action :install } end %w{ codesearch jq gist gister }.each do |pkg| pacman_aur(pkg){ action :build } pacman_aur(pkg){ action :install } end
# # Cookbook Name:: git # Recipe:: default # # Copyright (C) 2013 Logan Koester # # All rights reserved - Do Not Redistribute # include_recipe 'pacman' package('git') { action :install } git "#{Chef::Config[:file_cache_path]}/git-extras" do repository 'git://github.com/visionmedia/git-extras.git' reference 'master' action :sync end bash "compile and install git-extras" do cwd "#{Chef::Config[:file_cache_path]}/git-extras" code 'sudo make install' end %w{ autoconf automake bison flex xclip }.each do |pkg| package(pkg) { action :install } end %w{ codesearch jq gist gister }.each do |pkg| pacman_aur(pkg){ action [:build, :install] } end pacman_aur('gitsh'){ action [:build, :install] }
Add ability to write to a file
#!/usr/bin/ruby $KCODE = 'UTF8' require 'yaml' require 'set' tranzlator = YAML::load_file('tranzlator.yml') def yaml_quote(string) quote = false booleans = Set.new ['yes', 'true', 'no', 'false'] if string !~ /^[a-zA-Z]+$/ quote = true elsif booleans.member?(string) quote = true end if quote return "\"#{string}\"" else return string end end tranzlator.keys.sort.each do |key| value = tranzlator[key] key = yaml_quote(key) value = yaml_quote(value) puts "#{key}: #{value}" end
#!/usr/bin/ruby $KCODE = 'UTF8' require 'yaml' require 'set' tranzlator = YAML::load_file('tranzlator.yml') def yaml_quote(string) quote = false booleans = Set.new ['yes', 'true', 'no', 'false'] if string !~ /^[a-zA-Z]+$/ quote = true elsif booleans.member?(string) quote = true end if quote return "\"#{string}\"" else return string end end output = STDOUT if ARGV.length == 1 output = File.open(ARGV[0], 'w') end tranzlator.keys.sort.each do |key| value = tranzlator[key] key = yaml_quote(key) value = yaml_quote(value) output.puts "#{key}: #{value}" end
Rename usage of certain accounts due to some accounts being removed from nomenclature
class RenameUsagesOfAccountsRemovedInNomenclature < ActiveRecord::Migration REMOVED_USAGES = %w{others_taxes interests_expenses tax_depreciation_revenues} def change reversible do |d| d.up do REMOVED_USAGES.each do |usage| execute <<-SQL UPDATE accounts AS ac SET usages = (SELECT usages FROM accounts WHERE number = ac.number) WHERE usages = '#{usage}' SQL end end d.down do # NOOP end end end end
Set the vm_ems_ref key on the event for DB lookup of the VM.
module ManageIQ::Providers::Azure::CloudManager::EventParser extend ManageIQ::Providers::Azure::EventCatcherMixin def self.event_to_hash(event, ems_id) log_header = "ems_id: [#{ems_id}] " unless ems_id.nil? event_type = parse_event_type(event) _log.debug("#{log_header}event: [#{event_type}]") { :source => "AZURE", :timestamp => event["eventTimestamp"], :message => event["description"].blank? ? nil : event["description"], :ems_id => ems_id, :event_type => event_type, :full_data => event } end end
module ManageIQ::Providers::Azure::CloudManager::EventParser extend ManageIQ::Providers::Azure::EventCatcherMixin INSTANCE_TYPE = "microsoft.compute/virtualmachines".freeze def self.event_to_hash(event, ems_id) log_header = "ems_id: [#{ems_id}] " unless ems_id.nil? event_type = parse_event_type(event) _log.debug("#{log_header}event: [#{event_type}]") event_hash = { :source => "AZURE", :timestamp => event["eventTimestamp"], :message => event["description"].blank? ? nil : event["description"], :ems_id => ems_id, :event_type => event_type, :full_data => event } resource_type = event["resourceType"]["value"].downcase event_hash[:vm_ems_ref] = parse_vm_ref(event) if resource_type == INSTANCE_TYPE event_hash end end
Update tests to match HTTPMethod/Status KV change
require 'minitest_helper' require 'net/http' describe Oboe::Inst do before do clear_all_traces end it 'Net::HTTP should be defined and ready' do defined?(::Net::HTTP).wont_match nil end it 'Net::HTTP should have oboe methods defined' do [ :request_with_oboe ].each do |m| ::Net::HTTP.method_defined?(m).must_equal true end end it "should trace a Net::HTTP request" do Oboe::API.start_trace('net-http_test', '', {}) do uri = URI('https://www.google.com') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.get('/?q=test').read_body end traces = get_all_traces traces.count.must_equal 5 traces.first['Layer'].must_equal 'net-http_test' traces.first['Label'].must_equal 'entry' traces[1]['Layer'].must_equal 'net-http' traces[2]['IsService'].must_equal "1" traces[2]['RemoteProtocol'].must_equal "HTTPS" traces[2]['RemoteHost'].must_equal "www.google.com" traces[2]['ServiceArg'].must_equal "/?q=test" traces[2]['Method'].must_equal "GET" traces.last['Layer'].must_equal 'net-http_test' traces.last['Label'].must_equal 'exit' end end
require 'minitest_helper' require 'net/http' describe Oboe::Inst do before do clear_all_traces end it 'Net::HTTP should be defined and ready' do defined?(::Net::HTTP).wont_match nil end it 'Net::HTTP should have oboe methods defined' do [ :request_with_oboe ].each do |m| ::Net::HTTP.method_defined?(m).must_equal true end end it "should trace a Net::HTTP request" do Oboe::API.start_trace('net-http_test', '', {}) do uri = URI('https://www.appneta.com') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.get('/?q=test').read_body end traces = get_all_traces traces.count.must_equal 5 traces.first['Layer'].must_equal 'net-http_test' traces.first['Label'].must_equal 'entry' traces[1]['Layer'].must_equal 'net-http' traces[2]['IsService'].must_equal "1" traces[2]['RemoteProtocol'].must_equal "HTTPS" traces[2]['RemoteHost'].must_equal "www.appneta.com" traces[2]['ServiceArg'].must_equal "/?q=test" traces[2]['HTTPMethod'].must_equal "GET" traces[2]['HTTPStatus'].must_equal "200" traces.last['Layer'].must_equal 'net-http_test' traces.last['Label'].must_equal 'exit' end end
Make the specs actually do something
require 'spec_helper' describe 'Default recipe on MAC_OS_X: 10.9.2' do let(:runner) { ChefSpec::ServerRunner.new(platform: 'mac_os_x', version: '10.9.2') } it 'converges successfully' do expect { :chef_run }.to_not raise_error end end
require 'spec_helper' describe 'plist_file on macOS' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'mac_os_x', version: '10.13', step_into: ['mac_os_x_plist_file']).converge('test::plist_file') end it 'deletes the lockfile' do expect(chef_run).to delete_file('/Users/vagrant/Library/Preferences/us.zoom.xos.plist.lockfile') end it 'creates the plist file' do expect(chef_run).to create_cookbook_file('/Users/vagrant/Library/Preferences/us.zoom.xos.plist') end end
Add description and license to gemspec.
# -*- mode: ruby; encoding: utf-8 -*- # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command lib = File.expand_path('../lib/', __FILE__) $:.unshift lib unless $:.include?(lib) require 'capistrano-offroad/version' Gem::Specification.new do |s| s.name = "capistrano-offroad" s.version = CapistranoOffroad::VERSION::STRING s.summary = "Capistrano add-ons and recipes for non-rails projects" s.description = "Capistrano add-ons and recipes for non-rails projects" # FIXME s.authors = ["Maciej Pasternacki"] s.email = "maciej@pasternacki.net" s.homepage = "http://github.com/mpasternacki/capistrano-offroad" s.add_dependency "capistrano", ">= 2.5.8" s.required_rubygems_version = ">= 1.3.6" s.files = Dir.glob("lib/**/*.rb") + %w(README LICENSE) s.require_paths = ["lib"] end
# -*- mode: ruby; encoding: utf-8 -*- # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command lib = File.expand_path('../lib/', __FILE__) $:.unshift lib unless $:.include?(lib) require 'capistrano-offroad/version' Gem::Specification.new do |s| s.name = "capistrano-offroad" s.version = CapistranoOffroad::VERSION::STRING s.summary = "Capistrano add-ons and recipes for non-rails projects" s.description = <<EOF Capistrano-offroad is a support package for using Capistrano with non-rails projects. It contains basic reset of Rails-specific tasks, a handful of utility functions, and modules with recipes. EOF s.authors = ["Maciej Pasternacki"] s.email = "maciej@pasternacki.net" s.homepage = "http://github.com/mpasternacki/capistrano-offroad" s.licenses = ['BSD'] s.add_dependency "capistrano", ">= 2.5.8" s.required_rubygems_version = ">= 1.3.6" s.files = Dir.glob("lib/**/*.rb") + %w(README LICENSE) s.require_paths = ["lib"] end
Add updated gps because of branch conflict
# Your Names # 1) Katie Meyer # 2) nil # I spent 1.5 hours on this challenge. # Bakery Serving Size portion calculator. def serving_size_calc(item_to_make, num_of_ingredients) # what is expected for arguments library = {"cookie" => 1, "cake" => 5, "pie" => 7} # what the required ingredient amount is for each item unless library.key?(item_to_make) # this statement asks if that is not true (the item passed is in the library), then do the following raise ArgumentError.new("#{item_to_make} is not a valid input") # to notify user that the item entered does not exist in the library end serving_size = library[item_to_make] # the serving size variable is created to access the value of the ingredient needed to make item_to_make as stated in the library remaining_ingredients = num_of_ingredients % serving_size # finding remainder of ingredients case remaining_ingredients when 0 # when there is no remainder return "Calculations complete: Make #{num_of_ingredients / serving_size} of #{item_to_make}" # Print to the screen how many of that item you can make else return "Calculations complete: Make #{num_of_ingredients / serving_size} of #{item_to_make}, you have #{remaining_ingredients} leftover ingredients. Suggested baking items: Make #{remaining_ingredients} of cookie." # Print to the screen how many of that item you can make and suggest what to do with what is leftover. end end p serving_size_calc("pie", 7) p serving_size_calc("pie", 8) p serving_size_calc("cake", 5) p serving_size_calc("cake", 7) p serving_size_calc("cookie", 1) p serving_size_calc("cookie", 10) p serving_size_calc("THIS IS AN ERROR", 5) # Reflection =begin What did you learn about making code readable by working on this challenge? - The error_counter was pretty confusing. It makes sense to raise on error if the argument does not match what is in the library, but why count? The variable name error_counter is misleading. It wasn't counting errors, but was was counting down when as item matched an item on the list. It still confuses me. Did you learn any new methods? What did you learn about them? - .key? wasn't new, but it was something I forgot about. It helped reduce 9 lines of code to 3! What did you learn about accessing data in hashes? - This was good practice because it is not automatic for me yet. I learned that the [0] on the end of this method .values_at(item_to_make)[0] is referring to the index for the array that would be in the parentheses (in this case there is no array and is therefore not necessary). What concepts were solidified when working through this challenge? - accessing hash keys and values; raising an argument error; relevant use of the modulus =end
Add well_connected and importance stats to country_statistics
class AddWellConnectedAndImportanceToCountryStatistic < ActiveRecord::Migration def change add_column :country_statistics, :well_connected, :float add_column :country_statistics, :importance, :float end end
Use constants for role names
unless Role.count > 0 Role.create!(:name => "Administrator", :kind => Role::KIND_ADMIN) Role.create!(:name => "Committer", :kind => Role::KIND_MEMBER) end
unless Role.count > 0 Role.create!(:name => Role::ADMIN, :kind => Role::KIND_ADMIN) Role.create!(:name => Role::MEMBER, :kind => Role::KIND_MEMBER) end
Remove upper limit for actionpack
Gem::Specification.new do |gem| gem.name = "actionpack-action_caching" gem.version = "1.2.0" gem.author = "David Heinemeier Hansson" gem.email = "david@loudthinking.com" gem.description = "Action caching for Action Pack (removed from core in Rails 4.0)" gem.summary = "Action caching for Action Pack (removed from core in Rails 4.0)" gem.homepage = "https://github.com/rails/actionpack-action_caching" gem.required_ruby_version = ">= 1.9.3" gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map { |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.license = "MIT" gem.add_dependency "actionpack", ">= 4.0.0", "< 7" gem.add_development_dependency "mocha" gem.add_development_dependency "activerecord", ">= 4.0.0", "< 7" end
Gem::Specification.new do |gem| gem.name = "actionpack-action_caching" gem.version = "1.2.0" gem.author = "David Heinemeier Hansson" gem.email = "david@loudthinking.com" gem.description = "Action caching for Action Pack (removed from core in Rails 4.0)" gem.summary = "Action caching for Action Pack (removed from core in Rails 4.0)" gem.homepage = "https://github.com/rails/actionpack-action_caching" gem.required_ruby_version = ">= 1.9.3" gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map { |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.license = "MIT" gem.add_dependency "actionpack", ">= 4.0.0" gem.add_development_dependency "mocha" gem.add_development_dependency "activerecord", ">= 4.0.0", "< 7" end
Update webhook when a project is updated
class ProjectsController < WebController def index @projects = Project.all_sorted end def edit @project = Project.find(params[:id]) end def update project = Project.find(params[:id]) if project.update_attributes(project_params) redirect_to root_path, notice: "Project updated." else @project = project render :edit end end def destroy Project.find(params[:id]).destroy redirect_to root_path, notice: "Project removed." end private def project_params params.require(:project).permit(:name, :repository, :mappings, :position) end def setup_menu active_menu_item_name :projects end end
class ProjectsController < WebController def index @projects = Project.all_sorted end def edit @project = Project.find(params[:id]) end def update project = Project.find(params[:id]) if project.update_attributes(project_params) PostStatusToWebhook.call(project) redirect_to root_path, notice: "Project updated." else @project = project render :edit end end def destroy Project.find(params[:id]).destroy redirect_to root_path, notice: "Project removed." end private def project_params params.require(:project).permit(:name, :repository, :mappings, :position) end def setup_menu active_menu_item_name :projects end end
Exclude staging and other teams and make it more general
class DataObservatoryMailer < ActionMailer::Base CARTO_REQUEST_RECIPIENT = 'dataobservatory@carto.com'.freeze TEAM_ORG = 'team'.freeze default from: Cartodb.get_config(:mailer, 'from') layout 'mail' def user_request(user, dataset_id, dataset_name) subject = 'Your dataset request to CARTO' @user_name = user.name @dataset_id = dataset_id @dataset_name = dataset_name mail to: user.email, subject: subject end def carto_request(user, dataset_id, delivery_days) subject = 'Dataset request' @user_name = user.name @user_email = user.email @dataset_id = dataset_id @delivery_days = delivery_days unless user.organization&.name == TEAM_ORG mail to: CARTO_REQUEST_RECIPIENT, subject: subject end end end
class DataObservatoryMailer < ActionMailer::Base CARTO_REQUEST_RECIPIENT = 'dataobservatory@carto.com'.freeze EXCLUDED_ORGS = %w(team solutionscdb).freeze default from: Cartodb.get_config(:mailer, 'from') layout 'mail' def user_request(user, dataset_id, dataset_name) subject = 'Your dataset request to CARTO' @user_name = user.name @dataset_id = dataset_id @dataset_name = dataset_name mail to: user.email, subject: subject end def carto_request(user, dataset_id, delivery_days) subject = 'Dataset request' @user_name = user.name @user_email = user.email @dataset_id = dataset_id @delivery_days = delivery_days unless Rails.env.staging? || EXCLUDED_ORGS.include?(user.organization&.name) mail to: CARTO_REQUEST_RECIPIENT, subject: subject end end end
Implement show posts for tag route & tags index ordered by number of posts
class TagsController < ApplicationController def index end def show end end
class TagsController < ApplicationController def index @tags = Tag.most_popular end def show @tag = Tag.find_by(id: params[:id]) end end
Fix some markdown rendering issues
module ApplicationHelper def extract_timeframe start_date = params[:start] end_date = params[:end] [start_date, end_date] end def display_country?(country) if(!defined?(@current_country)) @first_country = true else @first_country = false end if(!defined?(@current_country) || country != @current_country) @current_country = country end end def funding_amount_for(winner_count) number_with_delimiter(winner_count * 1000, :delimiter => I18n.t("number.delimiter"), :separator => I18n.t("number.separator")) end def markdown(text, renderer_options = {}) markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML.new(renderer_options), :autolink => true, :space_after_headers => true) markdown.render(text).html_safe unless text.nil? end def image_url(image) (URI.parse(root_url) + image_path(image)).to_s end def meta_tag(tag_name, content, options = {}) content_tag = "meta_#{tag_name}".to_sym tag :meta, options.merge(:content => content_for?(content_tag) ? content_for(content_tag) : content) end end
module ApplicationHelper def extract_timeframe start_date = params[:start] end_date = params[:end] [start_date, end_date] end def display_country?(country) if(!defined?(@current_country)) @first_country = true else @first_country = false end if(!defined?(@current_country) || country != @current_country) @current_country = country end end def funding_amount_for(winner_count) number_with_delimiter(winner_count * 1000, :delimiter => I18n.t("number.delimiter"), :separator => I18n.t("number.separator")) end def markdown(text, renderer_options = {}) markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML.new(renderer_options), :autolink => true, :space_after_headers => true, :disable_indented_code_blocks => true, :fenced_code_blocks => true, :no_intra_emphasis => true) markdown.render(text).html_safe unless text.nil? end def image_url(image) (URI.parse(root_url) + image_path(image)).to_s end def meta_tag(tag_name, content, options = {}) content_tag = "meta_#{tag_name}".to_sym tag :meta, options.merge(:content => content_for?(content_tag) ? content_for(content_tag) : content) end end
Designate more Order attributes as readonly
require 'ordoro/record/base' module Ordoro module Record class Order < Base attribute :_link, String, readonly: true attribute :billing_address, Ordoro::Record::Address attribute :cart, Integer attribute :cart_name, String attribute :cart_order_id, String attribute :cart_shipment_id, String attribute :comments, Array[Ordoro::Record::Comment] attribute :company_id, Integer, readonly: true attribute :credit_card_issuer, String attribute :discount_amount, BigDecimal attribute :grand_total, BigDecimal attribute :lines, Array[Ordoro::Record::OrderLineItem] attribute :manually_edited, Boolean, readonly: true attribute :notes_from_customer, String attribute :order_date, DateTime attribute :order_id, String attribute :product_amount, BigDecimal attribute :shipments, Array[Ordoro::Record::Shipment] attribute :shippability, String, readonly: true attribute :shipping_address, Address attribute :shipping_amount, BigDecimal attribute :shipping_type, String attribute :status, String, readonly: true attribute :tag_ids, Array[Integer] attribute :tags, Array[Ordoro::Record::Tag] attribute :tax_amount, BigDecimal attribute :tax_lines, Array[Ordoro::Record::TaxLineItem] attribute :total_price, BigDecimal def initialize(attributes={}) self.order_id = attributes.delete('id_token') super(attributes) end def persisted? order_id end end end end
require 'ordoro/record/base' module Ordoro module Record class Order < Base attribute :_link, String, readonly: true attribute :billing_address, Ordoro::Record::Address, readonly: true attribute :cart, Integer, readonly: true attribute :cart_name, String, readonly: true attribute :cart_order_id, String attribute :cart_shipment_id, String attribute :comments, Array[Ordoro::Record::Comment], readonly: true attribute :company_id, Integer, readonly: true attribute :credit_card_issuer, String attribute :discount_amount, BigDecimal attribute :grand_total, BigDecimal attribute :lines, Array[Ordoro::Record::OrderLineItem], readonly: true attribute :manually_edited, Boolean, readonly: true attribute :notes_from_customer, String attribute :order_date, DateTime attribute :order_id, String, readonly: true attribute :product_amount, BigDecimal attribute :shipments, Array[Ordoro::Record::Shipment], readonly: true attribute :shippability, String, readonly: true attribute :shipping_address, Address, readonly: true attribute :shipping_amount, BigDecimal attribute :shipping_type, String attribute :status, String, readonly: true attribute :tag_ids, Array[Integer] attribute :tags, Array[Ordoro::Record::Tag], readonly: true attribute :tax_amount, BigDecimal attribute :tax_lines, Array[Ordoro::Record::TaxLineItem], readonly: true attribute :total_price, BigDecimal, readonly: true def initialize(attributes={}) self.order_id = attributes.delete('id_token') super(attributes) end def persisted? order_id end end end end
Set the superjob queue as an ignored queue in Sidekiq::Monitor::Cleaner
require 'sidekiq' directory = File.dirname(File.absolute_path(__FILE__)) Dir.glob("#{directory}/superworker/**/*.rb") { |file| require file } Dir.glob("#{directory}/../generators/sidekiq/superworker/**/*.rb") { |file| require file } Dir.glob("#{directory}/../../app/models/sidekiq/superworker/*.rb") { |file| require file } module Sidekiq module Superworker def self.table_name_prefix 'sidekiq_superworker_' end end end Sidekiq.configure_server do |config| config.server_middleware do |chain| chain.add Sidekiq::Superworker::Server::Middleware end end Superworker = Sidekiq::Superworker::Worker unless Object.const_defined?('Superworker')
require 'sidekiq' directory = File.dirname(File.absolute_path(__FILE__)) Dir.glob("#{directory}/superworker/**/*.rb") { |file| require file } Dir.glob("#{directory}/../generators/sidekiq/superworker/**/*.rb") { |file| require file } Dir.glob("#{directory}/../../app/models/sidekiq/superworker/*.rb") { |file| require file } module Sidekiq module Superworker def self.table_name_prefix 'sidekiq_superworker_' end end end Sidekiq.configure_server do |config| config.server_middleware do |chain| chain.add Sidekiq::Superworker::Server::Middleware end end Superworker = Sidekiq::Superworker::Worker unless Object.const_defined?('Superworker') Sidekiq::Monitor::Cleaner.add_ignored_queue(Sidekiq::Superworker::SuperjobProcessor.queue_name) if defined?(Sidekiq::Monitor)
Use idiomatic Ruby for the counts implementation
class PokerHand def initialize(cards) @cards = cards end def high_card card = @cards.sort.last card.value if card end def pair pairs.keys.first end def two_pair p = pairs() p.keys.sort if p.count > 0 end def three_of_a_kind threes = counts.select do |value, count| count == 3 end threes.keys.first end private def pairs counts.select do |value, count| count == 2 end end def counts c = {} @cards.each do |card| count = (c[card.value] || 0) + 1 c[card.value] = count end c end end
class PokerHand def initialize(cards) @cards = cards end def high_card card = @cards.sort.last card.value if card end def pair pairs.keys.first end def two_pair p = pairs() p.keys.sort if p.count > 0 end def three_of_a_kind threes = counts.select do |value, count| count == 3 end threes.keys.first end private def pairs counts.select do |value, count| count == 2 end end def counts @cards.each_with_object(Hash.new(0)) do |card, hash| hash[card.value] += 1 end end end
Reduce number of pictures per page from 24 to 12
# frozen_string_literal: true Kaminari.configure do |config| config.default_per_page = 24 # config.max_per_page = nil # config.window = 4 # config.outer_window = 0 # config.left = 0 # config.right = 0 # config.page_method_name = :page # config.param_name = :page # config.params_on_first_page = false end
# frozen_string_literal: true Kaminari.configure do |config| config.default_per_page = 12 # config.max_per_page = nil # config.window = 4 # config.outer_window = 0 # config.left = 0 # config.right = 0 # config.page_method_name = :page # config.param_name = :page # config.params_on_first_page = false end
Make nop do something useful.
require 'serialport' require 'pry' class Lightbringer < Thor class_option :device, type: :string, default: Dir["/dev/tty.usbmodem*"].first class_option :baud, type: :string, default: 9600 desc "on", "turn on all the lights" def on port = init_port(options) leds = num_leds(port) (0...leds).each do |i| port.write("s#{i} 255 255 255\n") end end desc "off", "turn off all the lights" def off port = init_port(options) leds = num_leds(port) (0...leds).each do |i| port.write("s#{i} 0 0 0\n") end end desc "nop", "do nothing" def nop port = init_port(options) end private def init_port(options) port = SerialPort.new(options[:device], baud: options[:baud], dtr: 0) loop do break if port.gets.chomp == "ready." end port end def num_leds(port) port.write("c\n") port.gets.chomp.to_i end end
require 'serialport' require 'pry' class Lightbringer < Thor class_option :device, type: :string, default: Dir["/dev/tty.usbmodem*"].first class_option :baud, type: :string, default: 9600 desc "on", "turn on all the lights" def on port = init_port(options) leds = num_leds(port) (0...leds).each do |i| port.write("s#{i} 255 255 255\n") end end desc "off", "turn off all the lights" def off port = init_port(options) leds = num_leds(port) (0...leds).each do |i| port.write("s#{i} 0 0 0\n") end end desc "console", "open a pry console with the port open" def nop port = init_port(options) binding.pry end private def init_port(options) port = SerialPort.new(options[:device], baud: options[:baud], dtr: 0) loop do break if port.gets.chomp == "ready." end port end def num_leds(port) port.write("c\n") port.gets.chomp.to_i end end
Add benchmark demonstrating bad perf with enqueing a batch.
require 'benchmark' require 'bundler/setup' require 'plines' module MyPipeline extend Plines::Pipeline configure do |plines| plines.batch_list_key { "key" } redis_url = if File.exist?('./config/redis_connection_url.txt') File.read('./config/redis_connection_url.txt').strip else "redis://localhost:6379/1" end redis = Redis.new(url: redis_url) qless = Qless::Client.new(redis: redis) plines.qless_client { qless } end class Step1 extend Plines::Step fan_out do |batch_data| batch_data.fetch(:size).times.map do |i| { num: i } end end end class ValidateStep1 extend Plines::Step depends_on :Step1 end class Step2 extend Plines::Step fan_out do |batch_data| batch_data.fetch(:size).times.map do |i| { num: i } end end end class ValidateStep2 extend Plines::Step depends_on :Step2 end end description = "Enqueing a batch of %s" sizes = [10, 100, 1000] Benchmark.bm((description % sizes.last).length) do |bm| sizes.each do |size| bm.report(description % size) do MyPipeline.enqueue_jobs_for(size: size) end end end =begin Original times (using naive DFS): user system total real Enqueing a batch of 10 0.030000 0.010000 0.040000 ( 0.031085) Enqueing a batch of 100 0.150000 0.010000 0.160000 ( 0.223950) Enqueing a batch of 1000 1.650000 0.130000 1.780000 ( 2.302887) =end
Remove haml require all together.
require File.expand_path('guard/reload_meta_wordpress.rb', File.dirname(__FILE__)) require 'haml' # we need to be able to reload the view helper load File.expand_path('haml/helpers.rb', File.dirname(__FILE__)) require File.expand_path('haml/filters', File.dirname(__FILE__))
require File.expand_path('guard/reload_meta_wordpress.rb', File.dirname(__FILE__)) # we need to be able to reload the view helper load File.expand_path('haml/helpers.rb', File.dirname(__FILE__)) require File.expand_path('haml/filters', File.dirname(__FILE__))
Increase polling frequency to avoid delays sending emails
Delayed::Worker.logger = Logger.new(File.join(Rails.root, 'log', 'dj.log')) Delayed::Worker.destroy_failed_jobs = false Delayed::Worker.sleep_delay = Rails.env.development? ? 1 : 60 Delayed::Worker.max_attempts = 3 Delayed::Worker.max_run_time = 5.minutes Delayed::Worker.read_ahead = 10 Delayed::Worker.default_queue_name = 'default' Delayed::Worker.delay_jobs = !Rails.env.test? Delayed::Worker.raise_signal_exceptions = :term #Delayed::Worker.logger.auto_flushing = true
Delayed::Worker.logger = Logger.new(File.join(Rails.root, 'log', 'dj.log')) Delayed::Worker.destroy_failed_jobs = false Delayed::Worker.sleep_delay = Rails.env.development? ? 1 : 10 Delayed::Worker.max_attempts = 3 Delayed::Worker.max_run_time = 5.minutes Delayed::Worker.read_ahead = 10 Delayed::Worker.default_queue_name = 'default' Delayed::Worker.delay_jobs = !Rails.env.test? Delayed::Worker.raise_signal_exceptions = :term #Delayed::Worker.logger.auto_flushing = true
Add Tobi as an author
Gem::Specification.new do |s| s.name = "statsd-instrument" s.version = '1.3.1' s.authors = ["Jesse Storimer"] s.email = ["jesse@shopify.com"] s.homepage = "http://github.com/shopify/statsd-instrument" s.summary = %q{A StatsD client for Ruby apps} s.description = %q{A StatsD client for Ruby apps. Provides metaprogramming methods to inject StatsD instrumentation into your code.} s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.add_development_dependency 'mocha' end
Gem::Specification.new do |s| s.name = "statsd-instrument" s.version = '1.3.1' s.authors = ["Jesse Storimer", "Tobias Lutke"] s.email = ["jesse@shopify.com"] s.homepage = "http://github.com/shopify/statsd-instrument" s.summary = %q{A StatsD client for Ruby apps} s.description = %q{A StatsD client for Ruby apps. Provides metaprogramming methods to inject StatsD instrumentation into your code.} s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.add_development_dependency 'mocha' end
Update magic_shell dependency to >= 1.0.0
name 'aliases' maintainer 'Oregon State University' maintainer_email 'rudy@grigar.net' license 'Apache 2.0' description 'Installs/Configures aliases' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.1' depends 'magic_shell', '~> 0.2.0'
name 'aliases' maintainer 'Oregon State University' maintainer_email 'rudy@grigar.net' license 'Apache 2.0' description 'Installs/Configures aliases' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.1' depends 'magic_shell', '>= 1.0.0'
Remove updated_at from the list of changes
class SandboxShipmentSerializer < ActiveModel::Serializer attributes :id, :appendix, :taxon_name, #:reported_taxon_name, :accepted_taxon_name, :term_code, :quantity, :unit_code, :trading_partner, :country_of_origin, :export_permit, :origin_permit, :purpose_code, :source_code, :year, :import_permit, :versions, :changes # def reported_taxon_name # object.reported_taxon_concept && "#{object.reported_taxon_concept.full_name} (#{object.reported_taxon_concept.name_status})" || # object.taxon_name # end # # def accepted_taxon_name # object.taxon_concept && "#{object.taxon_concept.full_name} (#{object.taxon_concept.name_status})" # end # def versions object.versions.map(&:reify) end def changes object.versions.map(&:changeset) end end
class SandboxShipmentSerializer < ActiveModel::Serializer attributes :id, :appendix, :taxon_name, #:reported_taxon_name, :accepted_taxon_name, :term_code, :quantity, :unit_code, :trading_partner, :country_of_origin, :export_permit, :origin_permit, :purpose_code, :source_code, :year, :import_permit, :versions, :changes # def reported_taxon_name # object.reported_taxon_concept && "#{object.reported_taxon_concept.full_name} (#{object.reported_taxon_concept.name_status})" || # object.taxon_name # end # # def accepted_taxon_name # object.taxon_concept && "#{object.taxon_concept.full_name} (#{object.taxon_concept.name_status})" # end # def versions object.versions.map(&:reify) end def changes object.versions.map(&:changeset).each do |changes| changes.delete("updated_at") end end end
Add reflection section to ruby file.
# Full Name Greeting puts "What is your first name?" first = gets.chomp puts "What is your middle name?" middle = gets.chomp puts "What is your last name?" last = gets.chomp puts "Hello " + first + " " + middle + " " + last +"! It is very nice to meet you!" # Bigger, Better Favorite Number puts "What is your favorite number?" fav = gets.chomp better = fav.to_i + 1 puts "How about the bigger, better number of " + better.to_s + "?"
# Full Name Greeting puts "What is your first name?" first = gets.chomp puts "What is your middle name?" middle = gets.chomp puts "What is your last name?" last = gets.chomp puts "Hello " + first + " " + middle + " " + last +"! It is very nice to meet you!" # Bigger, Better Favorite Number puts "What is your favorite number?" fav = gets.chomp better = fav.to_i + 1 puts "How about the bigger, better number of " + better.to_s + "?" =begin * How did you define a local variable? You can define a local varible by naming the variable and following it with an "=" sign and then a value. * How do you define a method? You can define a method with "def <method name>". You should be sure to complete the Ruby method by using the "end" keyword. * What is the difference between a local variable and a method? A local variable stores a value whereas a method is an executable piece of code. * How do you run a ruby program from the command line? You can run a ruby program from the command line using the command "ruby <file.rb>". * How do you run an RSpec file from the command line? You can RSpec file from the command line using the command "rspec <RSpec.rb>". * What was confusing about the material? What made sense? Having to convert integer/floats to strings for output was confusing at first. This is different than in Python (a language I've had experience with) where numbers are automatically converted to strings in the proper context. =end
Order payments to update the gateway_data
desc "Migrate payments data using first payment notification" task :migrate_payment_data => :environment do payments = Payment.all payments.each do |payment| first_notification = PaymentNotification.where(payment_id: payment.id).order(:id).first if first_notification.present? data = first_notification.extra_data data = JSON.parse(first_notification.extra_data) if data.kind_of? String if data.present? contribution = Contribution.find(payment.id) data["tid"] = contribution.acquirer_tid data["acquirer_name"] = contribution.acquirer_name data["card_brand"] = contribution.card_brand data["boleto_url"] = contribution.slip_url payment.gateway_data = data if payment.save puts "Saved data for payment #{payment.id}" else puts "Error saving data" end end end end end
desc "Migrate payments data using first payment notification" task :migrate_payment_data => :environment do payments = Payment.order(id: :desc) payments.each do |payment| first_notification = PaymentNotification.where(payment_id: payment.id).order(:id).first if first_notification.present? data = first_notification.extra_data data = JSON.parse(first_notification.extra_data) if data.kind_of? String if data.present? contribution = Contribution.find(payment.id) data["tid"] = contribution.acquirer_tid data["acquirer_name"] = contribution.acquirer_name data["card_brand"] = contribution.card_brand data["boleto_url"] = contribution.slip_url payment.gateway_data = data if payment.save puts "Saved data for payment #{payment.id}" else puts "Error saving data" end end end end end
Add another namespace to deprecate
# Mostly copied from: # https://github.com/rails/rails/blob/3-2-stable/activesupport/lib/active_support/deprecation/method_wrappers.rb def deprecate_methods(target_module, *method_names) options = method_names.extract_options! method_names += options.keys method_names.each do |method_name| target_module.alias_method_chain(method_name, :deprecation) do |target, punctuation| target_module.module_eval(<<-end_eval, __FILE__, __LINE__ + 1) def #{target}_with_deprecation#{punctuation}(*args, &block) ::ActiveSupport::Deprecation.warn("Prototype Usage: #{method_name}", caller) send(:#{target}_without_deprecation#{punctuation}, *args, &block) end end_eval end end end # This must be done after_initialize because # prototype_rails has its own engine initializer # that runs after local/app initializers. Rails.application.config.after_initialize do if ENV.fetch('DEPRECATE_PROTOTYPE', true) != 'false' namespaces = [ ActionView::Helpers::PrototypeHelper, ActionView::Helpers::ScriptaculousHelper, PrototypeHelper, ActionView::Helpers::JavaScriptHelper ] namespaces.each do |namespace| methods = namespace.public_instance_methods deprecate_methods(namespace, *methods) end end end
# Mostly copied from: # https://github.com/rails/rails/blob/3-2-stable/activesupport/lib/active_support/deprecation/method_wrappers.rb def deprecate_methods(target_module, *method_names) options = method_names.extract_options! method_names += options.keys method_names.each do |method_name| target_module.alias_method_chain(method_name, :deprecation) do |target, punctuation| target_module.module_eval(<<-end_eval, __FILE__, __LINE__ + 1) def #{target}_with_deprecation#{punctuation}(*args, &block) ::ActiveSupport::Deprecation.warn("Prototype Usage: #{method_name}", caller) send(:#{target}_without_deprecation#{punctuation}, *args, &block) end end_eval end end end # This must be done after_initialize because # prototype_rails has its own engine initializer # that runs after local/app initializers. Rails.application.config.after_initialize do if ENV.fetch('DEPRECATE_PROTOTYPE', true) != 'false' namespaces = [ ActionView::Helpers::PrototypeHelper, ActionView::Helpers::ScriptaculousHelper, ActionView::Helpers::JavaScriptHelper, ActionView::Helpers::PrototypeHelper::JavaScriptGenerator::GeneratorMethods, PrototypeHelper ] namespaces.each do |namespace| methods = namespace.public_instance_methods deprecate_methods(namespace, *methods) end end end
Fix HasMany manual association preloader
# frozen_string_literal: true module ActiveRecord::Associations::Preloader::ManualAssociationPreloader def initialize(klass, owners, reflection, records) super(klass, owners, reflection, nil) @records_by_owner = records.each_with_object({}) do |record, h| owner_id = record[association_key_name] owner_id = owner_id.to_s if key_conversion_required? records = (h[owner_id] ||= []) records << record end end def scope raise NotImplementedError end def records_for(ids) ids.flat_map { |id| @records_by_owner[id] }.tap(&:compact!) end end
# frozen_string_literal: true module ActiveRecord::Associations::Preloader::ManualAssociationPreloader def initialize(klass, owners, reflection, records) super(klass, owners, reflection, nil) @records_by_owner = records.each_with_object({}) do |record, h| owner_id = convert_key(record[association_key_name]) records = (h[owner_id] ||= []) records << record end end def scope raise NotImplementedError end def records_for(ids, &block) ids.flat_map { |id| @records_by_owner[id] }.tap(&:compact!).tap do |result| # In ActiveRecord 5.0.1, an ActiveRecord::Relation is expected to be returned. result.define_singleton_method(:load) do self end end end end
Migrate notifications template name to contribution
class MigrateNotificationsTemplateNameToContribution < ActiveRecord::Migration TEMPLATE_NAMES = [ [:backer_confirmed_after_project_was_closed, :contribution_confirmed_after_project_was_closed], [:backer_project_successful, :contribution_project_successful], [:backer_project_unsuccessful, :contribution_project_unsuccessful], [:confirm_backer, :confirm_contribution], [:pending_backer_project_unsuccessful, :pending_contribution_project_unsuccessful], [:project_owner_backer_confirmed, :project_owner_contribution_confirmed], [:backer_canceled_after_confirmed, :contribution_canceled_after_confirmed] ] def up TEMPLATE_NAMES.each do |t| execute "UPDATE notifications SET template_name = '#{t[1]}' WHERE notifications.template_name = '#{t[0]}'" end end def down TEMPLATE_NAMES.each do |t| execute "UPDATE notifications SET template_name = '#{t[0]}' WHERE notifications.template_name = '#{t[1]}'" end end end
Update migration to use appropriate version of HTMLFormatter
class AddRawContents < ActiveRecord::Migration[5.2] ANNOTATABLES = [Case, TextBlock] def up create_table :raw_contents do |t| t.text :content t.references :source, polymorphic: true, index: { unique: true } t.timestamps null: false end ANNOTATABLES.each do |klass| # Copy over existing, unmodified content attributes to new raw_contents table ActiveRecord::Base.connection.execute("INSERT INTO raw_contents (source_id, source_type, content, created_at, updated_at) SELECT id, '#{klass.name}', content, created_at, updated_at FROM #{klass.table_name}") # Apply HTML cleansing / munging to existing content attributes klass.find_each do |instance| # use update_column to avoid touching the timestamps instance.update_column :content, HTMLFormatter.process(instance.content) end end end def down ANNOTATABLES.each do |klass| ActiveRecord::Base.connection.execute("UPDATE #{klass.table_name} SET content = raw_contents.content FROM raw_contents WHERE raw_contents.source_type = '#{klass.name}' AND #{klass.table_name}.id = raw_contents.source_id") end drop_table :raw_contents end end
class AddRawContents < ActiveRecord::Migration[5.2] ANNOTATABLES = [Case, TextBlock] def up create_table :raw_contents do |t| t.text :content t.references :source, polymorphic: true, index: { unique: true } t.timestamps null: false end ANNOTATABLES.each do |klass| # Copy over existing, unmodified content attributes to new raw_contents table ActiveRecord::Base.connection.execute("INSERT INTO raw_contents (source_id, source_type, content, created_at, updated_at) SELECT id, '#{klass.name}', content, created_at, updated_at FROM #{klass.table_name}") # Apply HTML cleansing / munging to existing content attributes klass.find_each do |instance| # if the case was annotated, use the HTMLFormatter version that was in place at the point # that the first annotation was created, maxing out at V3 because V4 onward was only used # when formatting HTML for exports. If it's not annotated, use the newest HTMLFormatter date = instance.annotated? ? [instance.annotations.order(created_at: :asc).limit(1).pluck(:created_at)[0], HTMLFormatter::V3::EFFECTIVE_DATE].min : Date.today # use update_column to avoid touching the timestamps instance.update_column :content, HTMLFormatter.at(date).process(instance.content) end end end def down ANNOTATABLES.each do |klass| ActiveRecord::Base.connection.execute("UPDATE #{klass.table_name} SET content = raw_contents.content FROM raw_contents WHERE raw_contents.source_type = '#{klass.name}' AND #{klass.table_name}.id = raw_contents.source_id") end drop_table :raw_contents end end
Allow an admin to delete a user
class UsersController < ApplicationController http_basic_authenticate_with name: "bender", password: Setting.admin_password, if: :needs_authetication?, except: [:index, :show, :new, :create] respond_to :html, :json def index @users = User.all respond_with @users end def show @user = User.where("id = ? OR rfid = ?", params[:id], params[:user_rfid]).first! respond_with @user end def new @user = User.new end def create @user = User.new(user_params) if @user.save respond_to do |format| format.json { respond_with @user } format.html do flash[:success] = 'User created' redirect_to root_path end end else render :new end end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) @user.attributes = user_params if @user.save respond_to do |format| format.json { respond_with @user } format.html do flash[:success] = 'User updated' redirect_to users_path end end else render :edit end end protected def user_params params.require(:user).permit(:name, :email) end private def needs_authetication? Setting.admin_password.present? end end
class UsersController < ApplicationController http_basic_authenticate_with name: "bender", password: Setting.admin_password, if: :needs_authetication?, except: [:index, :show, :new, :create] respond_to :html, :json def index @users = User.all respond_with @users end def show @user = User.where("id = ? OR rfid = ?", params[:id], params[:user_rfid]).first! respond_with @user end def new @user = User.new end def create @user = User.new(user_params) if @user.save respond_to do |format| format.json { respond_with @user } format.html do flash[:success] = 'User created' redirect_to root_path end end else render :new end end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) @user.attributes = user_params if @user.save respond_to do |format| format.json { respond_with @user } format.html do flash[:success] = 'User updated' redirect_to users_path end end else render :edit end end def destroy user = User.find(params[:id]) user.destroy redirect_to users_path end protected def user_params params.require(:user).permit(:name, :email) end private def needs_authetication? Setting.admin_password.present? end end
Add a before_action to find the request, and a before_action to verify that the current user is associated with the request.
class VotesController < ApplicationController def create @vote = Vote.new(vote_params) if @vote.save @vote.candidate.update_vote_total flash[:success] = "Thank you for your feedback!" redirect_to root_path else flash[:now] = "Your vote has failed" render 'requests/show.html.erb' end end def other_party_of(request) if current_user == request.requester request.responder elsif current_user == request.responder request.requester end end private def vote_params @request = Request.find_by(id: params[:request_id]) @candidate = other_party_of(@request) known_attrs = { request_id: @request.id, candidate_id: @candidate.id } params.require(:vote).permit(:value).merge(known_attrs) end end
class VotesController < ApplicationController before_action :set_request, :verify_association def create @vote = Vote.new(vote_params) if @vote.save @vote.candidate.update_vote_total flash[:success] = "Thank you for your feedback!" redirect_to root_path else flash[:now] = "Your vote has failed" render 'requests/show.html.erb' end end def other_party_of(request) if current_user == request.requester request.responder elsif current_user == request.responder request.requester end end private def set_request @request = Request.find_by(id: params[:request_id]) end def verify_association unless @request.is_party_to?(current_user) redirect_to request_path(@request) end end def vote_params @candidate = other_party_of(@request) known_attrs = { request_id: @request.id, candidate_id: @candidate.id } params.require(:vote).permit(:value).merge(known_attrs) end end
Add test-unit gem to development dependencies
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = "fluent-plugin-keep-forward" s.version = "0.1.8" s.authors = ["Naotoshi Seo"] s.email = ["sonots@gmail.com"] s.homepage = "https://github.com/sonots/fluent-plugin-keep-forward" s.summary = "Fluentd plugin to keep forwarding to a node" s.description = s.summary s.rubyforge_project = "fluent-plugin-keep-forward" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_runtime_dependency "fluentd" s.add_development_dependency "rake" s.add_development_dependency "rspec" s.add_development_dependency "rspec-its" s.add_development_dependency "pry" s.add_development_dependency "pry-nav" s.add_development_dependency "delorean" end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = "fluent-plugin-keep-forward" s.version = "0.1.8" s.authors = ["Naotoshi Seo"] s.email = ["sonots@gmail.com"] s.homepage = "https://github.com/sonots/fluent-plugin-keep-forward" s.summary = "Fluentd plugin to keep forwarding to a node" s.description = s.summary s.rubyforge_project = "fluent-plugin-keep-forward" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_runtime_dependency "fluentd" s.add_development_dependency "rake" s.add_development_dependency "rspec" s.add_development_dependency "rspec-its" s.add_development_dependency "pry" s.add_development_dependency "pry-nav" s.add_development_dependency "delorean" s.add_development_dependency "test-unit" end
Package version is increased from 0.1.4 to 0.1.5
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'raygun_client' s.version = '0.1.4' s.summary = 'Client for the Raygun API using the Obsidian HTTP client' s.description = ' ' s.authors = ['Obsidian Software, Inc'] s.email = 'opensource@obsidianexchange.com' s.homepage = 'https://github.com/obsidian-btc/raygun-client' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.2.3' s.add_runtime_dependency 'error_data' s.add_runtime_dependency 'schema' s.add_runtime_dependency 'casing' s.add_runtime_dependency 'connection' s.add_runtime_dependency 'controls' s.add_runtime_dependency 'http-protocol' s.add_development_dependency 'minitest' s.add_development_dependency 'minitest-spec-context' s.add_development_dependency 'pry' s.add_development_dependency 'runner' end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'raygun_client' s.version = '0.1.5' s.summary = 'Client for the Raygun API using the Obsidian HTTP client' s.description = ' ' s.authors = ['Obsidian Software, Inc'] s.email = 'opensource@obsidianexchange.com' s.homepage = 'https://github.com/obsidian-btc/raygun-client' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.2.3' s.add_runtime_dependency 'error_data' s.add_runtime_dependency 'schema' s.add_runtime_dependency 'casing' s.add_runtime_dependency 'connection' s.add_runtime_dependency 'controls' s.add_runtime_dependency 'http-protocol' s.add_development_dependency 'minitest' s.add_development_dependency 'minitest-spec-context' s.add_development_dependency 'pry' s.add_development_dependency 'runner' end
Monitor redis in status url
# coding: UTF-8 class HomeController < ApplicationController skip_before_filter :browser_is_html5_compliant?, :only => :app_status layout 'front_layout' def index if logged_in? redirect_to dashboard_path and return else @user = User.new end end def app_status status = begin Rails::Sequel.connection.select('OK').first.values.include?('OK') ? 200 : 500 rescue Exception => e 500 end head status end end
# coding: UTF-8 class HomeController < ApplicationController skip_before_filter :browser_is_html5_compliant?, :only => :app_status layout 'front_layout' def index if logged_in? redirect_to dashboard_path and return else @user = User.new end end def app_status db_ok = Rails::Sequel.connection.select('OK').first.values.include?('OK') redis_ok = $tables_metadata.dbsize api_ok = true head (db_ok && redis_ok && api_ok) ? 200 : 500 rescue Rails.logger.info "======== status method failed: #{$!}" head 500 end end
Use Camel-Cased header names in the specs.
require 'spidr/page' require 'spec_helper' shared_examples_for "Page" do it "should have a status code" do @page.code.should be_integer end it "should have a body" do @page.body.should_not be_empty end it "should provide transparent access to the response headers" do @page.content_type.should == @page.headers['content-type'] end end
require 'spidr/page' require 'spec_helper' shared_examples_for "Page" do it "should have a status code" do @page.code.should be_integer end it "should have a body" do @page.body.should_not be_empty end it "should provide transparent access to the response headers" do @page.content_type.should == @page.response['Content-Type'] end end
Make sure view helpers work in production
SwitchUser.setup do |config| config.available_users = { :user => lambda { User.order(:email) } } config.controller_guard = lambda { |current_user, request| current_user.try(:admin?) } config.redirect_path = lambda { |request, params| '/users/dashboard' } config.helper_with_guest = false end
SwitchUser.setup do |config| config.available_users = { :user => lambda { User.order(:email) } } config.controller_guard = lambda { |current_user, request| current_user.try(:admin?) } config.view_guard = lambda { |current_user, request| current_user.try(:admin?) } config.redirect_path = lambda { |request, params| '/users/dashboard' } config.helper_with_guest = false end
Set dev env to send email
# Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_view.debug_rjs = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false config.action_mailer.delivery_method = :test
# Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_view.debug_rjs = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = true
Correct bug, where we have twice the bars added to render
# encoding: UTF-8 # Copyright 2008, 2009, 2010 Boris ARZUR # # This file is part of Kemuri. # # Kemuri is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # Kemuri is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public # License along with Kemuri. If not, see http://www.gnu.org/licenses. class Kan def execute request, path, query, response kan = path[1] kan.force_encoding(Encoding::UTF_8) kanji = Kanji.new( kan ) kid = kanji.kid.to_i kan_lists = kanji.lists kanji.to_html + kanji.radicals + Static::voyage end end
# encoding: UTF-8 # Copyright 2008, 2009, 2010 Boris ARZUR # # This file is part of Kemuri. # # Kemuri is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # Kemuri is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public # License along with Kemuri. If not, see http://www.gnu.org/licenses. class Kan def execute request, path, query, response kan = path[1] kan.force_encoding(Encoding::UTF_8) kanji = Kanji.new( kan ) kid = kanji.kid.to_i kan_lists = kanji.lists kanji.to_html + kanji.radicals end end
Fix *Multiple IDs found with provided prefix* error
# encoding: UTF-8 # # Author:: Xabier de Zuazo (<xabier@zuazo.org>) # Copyright:: Copyright (c) 2015-2016 Xabier de Zuazo # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe 'Build a Dockerfile from a tag' do context docker_build(id: 'nginx:1', tag: 'from_tag_spec') do context docker_run('from_tag_spec') do describe package('nginx') do it { should be_installed } end it 'is a Linux distro' do expect(command('uname').stdout).to include 'Linux' end describe server(described_container) do describe http('/') do it 'responds content including "Welcome to nginx!"' do expect(response.body).to include 'Welcome to nginx!' end it 'responds as "nginx" server' do expect(response.headers['server']).to match(/nginx/i) end end end end end end
# encoding: UTF-8 # # Author:: Xabier de Zuazo (<xabier@zuazo.org>) # Copyright:: Copyright (c) 2015-2016 Xabier de Zuazo # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe 'Build a Dockerfile from a tag' do context docker_build(id: 'nginx:1.9', tag: 'from_tag_spec') do context docker_run('from_tag_spec') do describe package('nginx') do it { should be_installed } end it 'is a Linux distro' do expect(command('uname').stdout).to include 'Linux' end describe server(described_container) do describe http('/') do it 'responds content including "Welcome to nginx!"' do expect(response.body).to include 'Welcome to nginx!' end it 'responds as "nginx" server' do expect(response.headers['server']).to match(/nginx/i) end end end end end end
Add Email Alert API to Services
require "gds_api/publishing_api" require "gds_api/content_store" require "gds_api/link_checker_api" module Services def self.publishing_api @publishing_api ||= GdsApi::PublishingApi.new( Plek.new.find("publishing-api"), disable_cache: true, bearer_token: ENV["PUBLISHING_API_BEARER_TOKEN"] || "example", ) end def self.content_store @content_store ||= GdsApi::ContentStore.new( Plek.new.find("content-store"), disable_cache: true, ) end def self.link_checker_api @link_checker_api ||= GdsApi::LinkCheckerApi.new( Plek.new.find("link-checker-api"), bearer_token: ENV["LINK_CHECKER_API_BEARER_TOKEN"], ) end end
require "gds_api/publishing_api" require "gds_api/content_store" require "gds_api/link_checker_api" require "gds_api/email_alert_api" module Services def self.publishing_api @publishing_api ||= GdsApi::PublishingApi.new( Plek.new.find("publishing-api"), disable_cache: true, bearer_token: ENV["PUBLISHING_API_BEARER_TOKEN"] || "example", ) end def self.content_store @content_store ||= GdsApi::ContentStore.new( Plek.new.find("content-store"), disable_cache: true, ) end def self.link_checker_api @link_checker_api ||= GdsApi::LinkCheckerApi.new( Plek.new.find("link-checker-api"), bearer_token: ENV["LINK_CHECKER_API_BEARER_TOKEN"], ) end def self.email_alert_api @email_alert_api || GdsApi::EmailAlertApi.new( Plek.new.find("email-alert-api"), bearer_token: ENV["EMAIL_ALERT_API_BEARER_TOKEN"], ) end end
Remove unused Product SLUG constant
module Tiqets module Resources module Product SLUG = 'products'.freeze def find_product(id) response = get("products/#{id}", 'product') Product.new(response) end class Product attr_reader :id, :language, :languages, :title, :tagline, :price, :sale_status, :country_name, :country_id, :city_name, :city_id, :tag_ids, :images, :ratings, :geolocation, :distance, :venue, :product_url, :product_checkout_url def initialize(attributes) @id = attributes['id'] @language = attributes['language'] @languages = attributes['languages'] @title = attributes['title'] @tagline = attributes['tagline'] @price = attributes['price'] @sale_status = attributes['sale_status'] @country_name = attributes['country_name'] @country_id = attributes['country_id'] @city_name = attributes['city_name'] @city_id = attributes['city_id'] @tag_ids = attributes['tag_ids'] @images = attributes['images'] @ratings = attributes['ratings'] @geolocation = attributes['geolocation'] @distance = attributes['distance'] @venue = attributes['venue'] @product_url = attributes['product_url'] @product_checkout_url = attributes['product_checkout_url'] end end end end end
module Tiqets module Resources module Product def find_product(id) response = get("products/#{id}", 'product') Product.new(response) end class Product attr_reader :id, :language, :languages, :title, :tagline, :price, :sale_status, :country_name, :country_id, :city_name, :city_id, :tag_ids, :images, :ratings, :geolocation, :distance, :venue, :product_url, :product_checkout_url def initialize(attributes) @id = attributes['id'] @language = attributes['language'] @languages = attributes['languages'] @title = attributes['title'] @tagline = attributes['tagline'] @price = attributes['price'] @sale_status = attributes['sale_status'] @country_name = attributes['country_name'] @country_id = attributes['country_id'] @city_name = attributes['city_name'] @city_id = attributes['city_id'] @tag_ids = attributes['tag_ids'] @images = attributes['images'] @ratings = attributes['ratings'] @geolocation = attributes['geolocation'] @distance = attributes['distance'] @venue = attributes['venue'] @product_url = attributes['product_url'] @product_checkout_url = attributes['product_checkout_url'] end end end end end
Use the reflection class's connection when calling explain for compat with per-class databases / active_record_shards
require 'active_record/associations/preloader' module PredictiveLoad class PreloadLog < ActiveRecord::Associations::Preloader attr_accessor :logger def preload(association) grouped_records(association).each do |reflection, klasses| klasses.each do |klass, records| preloader = preloader_for(reflection).new(klass, records, reflection, options) if preloader.respond_to?(:through_reflection) log("encountered :through association for #{association}. Requires loading records to generate query, so skipping for now.") next end preload_sql = preloader.scoped.where(collection_arel(preloader)).to_sql log("would preload with: #{preload_sql.to_s}") ActiveRecord::Base.connection.explain(preload_sql).each_line do |line| log(line) end end end end def collection_arel(preloader) owners_map = preloader.owners_by_key owner_keys = owners_map.keys.compact preloader.association_key.in(owner_keys) end def log(message) ActiveRecord::Base.logger.info("predictive_load: #{message}") end end end
require 'active_record/associations/preloader' module PredictiveLoad class PreloadLog < ActiveRecord::Associations::Preloader attr_accessor :logger def preload(association) grouped_records(association).each do |reflection, klasses| klasses.each do |klass, records| preloader = preloader_for(reflection).new(klass, records, reflection, options) if preloader.respond_to?(:through_reflection) log("encountered :through association for #{association}. Requires loading records to generate query, so skipping for now.") next end preload_sql = preloader.scoped.where(collection_arel(preloader)).to_sql log("would preload with: #{preload_sql.to_s}") klass.connection.explain(preload_sql).each_line do |line| log(line) end end end end def collection_arel(preloader) owners_map = preloader.owners_by_key owner_keys = owners_map.keys.compact preloader.association_key.in(owner_keys) end def log(message) ActiveRecord::Base.logger.info("predictive_load: #{message}") end end end
Check the task is already exists or not and print it
require "remindice/version" require "thor" module Remindice TASK_FILENAME = File.expand_path("~/.reamindice_tasks") class << self def tasks @@tasks.clone end def save(tasks) file = File.open(TASK_FILENAME, "w") tasks.each do |i| file.puts i end end end class Commands < Thor @@tasks = if File.exists?(Remindice::TASK_FILENAME); File.readlines(Remindice::TASK_FILENAME) else [] end desc 'add TASKS', 'Add tasks' def add(*task) task.each do |i| @@tasks << i end Remindice.save @@tasks end end end
require "remindice/version" require "thor" module Remindice TASK_FILENAME = File.expand_path("~/.reamindice_tasks") class << self def tasks @@tasks.clone end def save(tasks) file = File.open(TASK_FILENAME, "w") tasks.each do |i| file.puts i end end end class Commands < Thor @@tasks = if File.exists?(Remindice::TASK_FILENAME); File.readlines(Remindice::TASK_FILENAME) else [] end desc 'add TASKS', 'Add tasks' def add(*task) task.each do |i| if @@tasks.include? i STDERR.puts "'#{i}' is already added" else @@tasks << i puts "'#{i}' is successfully added" end end Remindice.save @@tasks end end end
Change to pass in environment.
# encoding: utf-8 require 'tty/color/support' require 'tty/color/mode' require 'tty/color/version' module TTY # Responsible for checking terminal color support # # @api public module Color extend self NoValue = Module.new @verbose = false @output = $stderr attr_accessor :output, :verbose def supports? Support.new.supports? end alias_method :color?, :supports? alias_method :supports_color?, :supports? # @api public def mode Mode.new.mode end # TERM environment variable # # @api public def term ENV['TERM'] end # @api private def tty? output.tty? end end # Color end # TTY
# encoding: utf-8 require 'tty/color/support' require 'tty/color/mode' require 'tty/color/version' module TTY # Responsible for checking terminal color support # # @api public module Color extend self NoValue = Module.new @verbose = false @output = $stderr attr_accessor :output, :verbose def supports? Support.new.supports? end alias_method :color?, :supports? alias_method :supports_color?, :supports? # Check how many colors this terminal supports # # @return [Integer] # # @api public def mode Mode.new(ENV).mode end # TERM environment variable # # @api public def term ENV['TERM'] end # @api private def tty? output.tty? end end # Color end # TTY
Return nil if the organisation link doesn't exist
module Whitehall class AdminLinkLookup include Govspeak::EmbeddedContentPatterns def self.find_edition(admin_url) case admin_url when ADMIN_ORGANISATION_CIP_PATH organisation = Organisation.find_by(slug: $1) corporate_info_page(organisation: organisation, corporate_info_slug: $2) when ADMIN_WORLDWIDE_ORGANISATION_CIP_PATH organisation = WorldwideOrganisation.find_by(slug: $1) corporate_info_page(organisation: organisation, corporate_info_slug: $2) when ADMIN_EDITION_PATH Edition.unscoped.find_by(id: $1) end end def self.corporate_info_page(organisation:, corporate_info_slug:) organisation.corporate_information_pages.find(corporate_info_slug) end private_class_method :corporate_info_page end end
module Whitehall class AdminLinkLookup include Govspeak::EmbeddedContentPatterns def self.find_edition(admin_url) case admin_url when ADMIN_ORGANISATION_CIP_PATH organisation = Organisation.find_by(slug: $1) corporate_info_page(organisation: organisation, corporate_info_slug: $2) when ADMIN_WORLDWIDE_ORGANISATION_CIP_PATH organisation = WorldwideOrganisation.find_by(slug: $1) corporate_info_page(organisation: organisation, corporate_info_slug: $2) when ADMIN_EDITION_PATH Edition.unscoped.find_by(id: $1) end end def self.corporate_info_page(organisation:, corporate_info_slug:) return nil unless organisation organisation.corporate_information_pages.find(corporate_info_slug) end private_class_method :corporate_info_page end end
Add current directory to test, for Ruby 1.9.2 compatibility
require 'test/unit' require File.join(File.dirname(__FILE__),'..','lib','subelsky_enhancements','hash') class TestHash < Test::Unit::TestCase def hash @hash ||= { :a => 1, :b => 2, :c => 3, :d => 4 } end def test_except_with_one_key assert_equal({ :a => 1, :b => 2, :d => 4 }, hash.except(:c)) end def test_except_with_multiple_keys assert_equal({ :b => 2, :c => 3 }, hash.except(:a,:d)) end def test_except_with_absent_key assert_equal(hash, hash.except(:e)) end def test_only_with_one_key assert_equal({ :a => 1 }, hash.only(:a)) end def test_only_with_multiple_keys assert_equal({ :b => 2, :c => 3, :d => 4 }, hash.only(:b,:c,:d)) end def test_only_with_absent_key assert_equal({}, hash.only(:e)) end end
require 'test/unit' require File.join('.',File.dirname(__FILE__),'..','lib','subelsky_enhancements','hash') class TestHash < Test::Unit::TestCase def hash @hash ||= { :a => 1, :b => 2, :c => 3, :d => 4 } end def test_except_with_one_key assert_equal({ :a => 1, :b => 2, :d => 4 }, hash.except(:c)) end def test_except_with_multiple_keys assert_equal({ :b => 2, :c => 3 }, hash.except(:a,:d)) end def test_except_with_absent_key assert_equal(hash, hash.except(:e)) end def test_only_with_one_key assert_equal({ :a => 1 }, hash.only(:a)) end def test_only_with_multiple_keys assert_equal({ :b => 2, :c => 3, :d => 4 }, hash.only(:b,:c,:d)) end def test_only_with_absent_key assert_equal({}, hash.only(:e)) end end
Add Luke Morton to authors
$:.push File.expand_path("../lib", __FILE__) require "ydtd_frontend/version" Gem::Specification.new do |s| s.name = "ydtd_frontend" s.version = YdtdFrontend::VERSION s.authors = ["Rory MacDonald", "Seb Ashton", "Scott Mason"] s.email = ["rory@madebymade.co.uk"] s.homepage = "http://www.madebymade.co.uk" s.summary = "Frontend component for the YDTD application and marketing site." s.description = "" s.add_development_dependency "middleman", "3.2.2" s.add_development_dependency "middleman-livereload", "3.1.0" s.add_development_dependency "middleman-minify-html", "3.1.1" s.add_development_dependency "sass", "3.2.17" s.add_development_dependency "compass", "0.12.4" s.add_development_dependency "modular-scale", "2.0.4" s.add_development_dependency "oj", "2.2.3" s.add_development_dependency "therubyracer", "0.12.0" s.add_development_dependency "rails", "3.2.17" s.require_paths = ["lib", "app", "vendor"] s.files = Dir["{lib,app,vendor}/**/*"] + ["README.md"] end
$:.push File.expand_path("../lib", __FILE__) require "ydtd_frontend/version" Gem::Specification.new do |s| s.name = "ydtd_frontend" s.version = YdtdFrontend::VERSION s.authors = ["Rory MacDonald", "Seb Ashton", "Scott Mason", "Luke Morton"] s.email = ["rory@madebymade.co.uk"] s.homepage = "http://www.madebymade.co.uk" s.summary = "Frontend component for the YDTD application and marketing site." s.description = "" s.add_development_dependency "middleman", "3.2.2" s.add_development_dependency "middleman-livereload", "3.1.0" s.add_development_dependency "middleman-minify-html", "3.1.1" s.add_development_dependency "sass", "3.2.17" s.add_development_dependency "compass", "0.12.4" s.add_development_dependency "modular-scale", "2.0.4" s.add_development_dependency "oj", "2.2.3" s.add_development_dependency "therubyracer", "0.12.0" s.add_development_dependency "rails", "3.2.17" s.require_paths = ["lib", "app", "vendor"] s.files = Dir["{lib,app,vendor}/**/*"] + ["README.md"] end
Add organization relationship to CourseSerializer.
# frozen_string_literal: true class CourseSerializer < BaseSerializer attributes :id, :name, :description, :editable, :locations, :track_points link(:self) { api_v1_course_path(object) } has_many :splits def locations object.ordered_splits.select(&:has_location?).map do |split| {id: split.id, base_name: split.base_name, latitude: split.latitude, longitude: split.longitude} end end end
# frozen_string_literal: true class CourseSerializer < BaseSerializer attributes :id, :name, :description, :editable, :locations, :track_points link(:self) { api_v1_course_path(object) } has_many :splits belongs_to :organization def locations object.ordered_splits.select(&:has_location?).map do |split| {id: split.id, base_name: split.base_name, latitude: split.latitude, longitude: split.longitude} end end end
Update IntellIJ IDEA to version 14.1.2
cask :v1 => 'intellij-idea' do version '14.1.1' sha256 '3d17062a6371a5bf04acd1f2526c3972deea719f43798b9a7e679672258d3828' url "http://download.jetbrains.com/idea/ideaIU-#{version}.dmg" name 'IntelliJ IDEA' homepage 'https://www.jetbrains.com/idea/' license :commercial app 'IntelliJ IDEA 14.app' zap :delete => [ '~/Library/Application Support/IntelliJIdea14', '~/Library/Preferences/IntelliJIdea14', ] caveats <<-EOS.undent #{token} requires Java 6 like any other IntelliJ-based IDE. You can install it with brew cask install caskroom/homebrew-versions/java6 The vendor (JetBrains) doesn't support newer versions of Java (yet) due to several critical issues, see details at https://intellij-support.jetbrains.com/entries/27854363 To use existing newer Java at your own risk, add JVMVersion=1.6+ to ~/Library/Preferences/IntelliJIdea14/idea.properties EOS end
cask :v1 => 'intellij-idea' do version '14.1.2' sha256 'ea3326004a8e1dd113ea54b825494f60be0f506c5e6a25743481a719931ce896' url "http://download.jetbrains.com/idea/ideaIU-#{version}.dmg" name 'IntelliJ IDEA' homepage 'https://www.jetbrains.com/idea/' license :commercial app 'IntelliJ IDEA 14.app' zap :delete => [ '~/Library/Application Support/IntelliJIdea14', '~/Library/Preferences/IntelliJIdea14', ] caveats <<-EOS.undent #{token} requires Java 6 like any other IntelliJ-based IDE. You can install it with brew cask install caskroom/homebrew-versions/java6 The vendor (JetBrains) doesn't support newer versions of Java (yet) due to several critical issues, see details at https://intellij-support.jetbrains.com/entries/27854363 To use existing newer Java at your own risk, add JVMVersion=1.6+ to ~/Library/Preferences/IntelliJIdea14/idea.properties EOS end
Concatenate monasca-ui settings into horizon's settings Fix some places where recipe was not idempotent
# Installs the mon-ui panel # Grab the necessary packages include_recipe "python" ['monasca-ui','python-monascaclient'].each do |pkg| python_pip pkg do action :install end end # Set up symlinks # Use 'execute' resource because chef does not support symlinking directories execute "ln -sfv /usr/local/lib/python2.7/dist-packages/enabled/* /opt/stack/horizon/openstack_dashboard/local/enabled/" execute "ln -sv /usr/local/lib/python2.7/dist-packages/monitoring /opt/stack/horizon/monitoring" # install grafana and integrate with horizon if !::File.exists?("/usr/local/lib/python2.7/dist-packages/monitoring/static/grafana") execute "git clone https://github.com/hpcloud-mon/grafana.git /opt/stack/grafana" execute "cp /opt/stack/grafana/src/config.sample.js /opt/stack/grafana/src/config.js" execute "ln -sv /opt/stack/grafana/src /usr/local/lib/python2.7/dist-packages/monitoring/static/grafana" end # Bounce the webserver service "apache2" do action :restart end
# Installs the mon-ui panel # Grab the necessary packages include_recipe "python" ['monasca-ui','python-monascaclient'].each do |pkg| python_pip pkg do action :install end end # Set up symlinks # Use 'execute' resource because chef does not support symlinking directories if !::File.exists?("/opt/stack/horizon/monitoring") execute "ln -sfv /usr/local/lib/python2.7/dist-packages/enabled/* /opt/stack/horizon/openstack_dashboard/local/enabled/" execute "ln -sv /usr/local/lib/python2.7/dist-packages/monitoring /opt/stack/horizon/monitoring" end if ::File.exists?("/usr/local/lib/python2.7/dist-packages/monitoring/local_settings.py") && ::File.readlines("/opt/stack/horizon/openstack_dashboard/local/local_settings.py").grep(/MONITORING_SERVICES/).size == 0 execute "cat /usr/local/lib/python2.7/dist-packages/monitoring/local_settings.py >> /opt/stack/horizon/openstack_dashboard/local/local_settings.py" end # install grafana and integrate with horizon if !::File.exists?("/usr/local/lib/python2.7/dist-packages/monitoring/static/grafana") execute "git clone https://github.com/hpcloud-mon/grafana.git /opt/stack/grafana" execute "cp /opt/stack/grafana/src/config.sample.js /opt/stack/grafana/src/config.js" execute "ln -sv /opt/stack/grafana/src /usr/local/lib/python2.7/dist-packages/monitoring/static/grafana" end # Bounce the webserver service "apache2" do action :restart end
Write tests for experiment show page
require 'rails_helper' describe 'Experiment' do describe 'Experiment Show Page', js: true do it 'displays an experiments title' do visit '/experiments/1' expect(page).to have_content "Article Title" end xit 'displays the sign-up button, redirects back to the experiment show page and shows the users name at the bottom of the staff list' do end end end
Update tests to handle the widgetized way of doing things
context "Activities" do fixtures :users, :companies, :customers, :tasks, :projects, :milestones, :work_logs setup do use_controller ActivitiesController @request.host = 'cit.local.host' @request.session[:user_id] = 1 end specify "/index should render :success" do get :index assigns(:tz).should.equal Timezone.get('Europe/Oslo') assigns(:current_user).should.equal User.find(1) status.should.be :success end specify "/list should render :success" do get :list status.should.be :success template.should.be 'activities/list' assigns(:projects).should.not.be.nil assigns(:projects).size.should.be > 0 assigns(:tasks).should.not.be.nil assigns(:tasks).size.should.be > 0 assigns(:tasks).should.not.equal assigns(:new_tasks) end end
context "Activities" do fixtures :users, :companies, :customers, :tasks, :projects, :milestones, :work_logs setup do use_controller ActivitiesController @request.host = 'cit.local.host' @request.session[:user_id] = 1 end specify "/index should render :success" do get :index assigns(:current_user).tz.should.equal Timezone.get('Europe/Oslo') assigns(:current_user).should.equal User.find(1) status.should.be :success end specify "/list should render :success" do get :list status.should.be :success template.should.be 'activities/list' end end
Remove support for SLES 11 and simplify package logic
# # Cookbook:: cron # Attributes:: default # # Copyright:: 2010-2019, Chef Software, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # default['cron']['package_name'] = case node['platform_family'] when 'debian' ['cron'] when 'amazon' ['cronie'] when 'rhel', 'fedora' node['platform_version'].to_i >= 6 ? ['cronie'] : ['vixie-cron'] when 'suse' node['platform_version'].to_i >= 12 ? ['cronie'] : ['cron'] when 'solaris2' 'core-os' when 'pld' 'cronie' else [] end default['cron']['service_name'] = case node['platform_family'] when 'amazon', 'rhel', 'fedora', 'pld' 'crond' else 'cron' end
# # Cookbook:: cron # Attributes:: default # # Copyright:: 2010-2019, Chef Software, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # default['cron']['package_name'] = case node['platform_family'] when 'debian' ['cron'] when 'amazon', 'suse', 'pld' ['cronie'] when 'rhel', 'fedora' node['platform_version'].to_i >= 6 ? ['cronie'] : ['vixie-cron'] when 'solaris2' 'core-os' else [] end default['cron']['service_name'] = case node['platform_family'] when 'amazon', 'rhel', 'fedora', 'pld' 'crond' else 'cron' end
Remove :app designation from HandBrake link
class Handbrake < Cask url 'http://handbrake.fr/rotation.php?file=HandBrake-0.9.9-MacOSX.6_GUI_x86_64.dmg' homepage 'http://handbrake.fr/' version '0.9.9' sha1 '9b6f0259f3378b0cc136378d7859162aa95c0eb7' link :app, 'HandBrake.app' end
class Handbrake < Cask url 'http://handbrake.fr/rotation.php?file=HandBrake-0.9.9-MacOSX.6_GUI_x86_64.dmg' homepage 'http://handbrake.fr/' version '0.9.9' sha1 '9b6f0259f3378b0cc136378d7859162aa95c0eb7' link 'HandBrake.app' end
Add specs for the StatRaptor::Error class
require 'spec_helper' describe StatRaptor::Error do context "#initialize" do it "returns an instance of StatRaptor::Error" do StatRaptor::Error.new("message").should be_a(StatRaptor::Error) end it "is a subclass of StandardError" do StatRaptor::Error.superclass.should == StandardError end end end
Use `is_a?` instead of `kind_of?`
class HashParser def initialize(hash) @hash = hash end def parse array = Array.new @hash.each_key do |key| if key.kind_of?(Fixnum) array << key.to_s else array << key end end sort_result(array) end private def sort_result(input) input.sort! do |x,y| y.size <=> x.size end sorted_keys = return_fixnums(input) assemble_hash(sorted_keys) end def return_fixnums(input) array = Array.new input.each do |str| if str.kind_of?(Symbol) array << str elsif is_integer?(str) array << str.to_i else array << str end end array end def is_integer?(str) result = str.split('').select do |char| /\d/.match(char) end if result.size == str.size true else false end end def assemble_hash(array) hash = Hash.new array.each do |key| hash[key] = @hash[key] end hash end end
class HashParser def initialize(hash) @hash = hash end def parse array = Array.new @hash.each_key do |key| if key.is_a?(Fixnum) array << key.to_s else array << key end end sort_result(array) end private def sort_result(input) input.sort! do |x,y| y.size <=> x.size end sorted_keys = return_fixnums(input) assemble_hash(sorted_keys) end def return_fixnums(input) array = Array.new input.each do |str| if str.is_a?(Symbol) array << str elsif is_fixnum?(str) array << str.to_i else array << str end end array end def is_fixnum?(str) result = str.split('').select do |char| /\d/.match(char) end if result.size == str.size true else false end end def assemble_hash(array) hash = Hash.new array.each do |key| hash[key] = @hash[key] end hash end end
Change gemspec to add metada, remove test artefacts and dev dependencies
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'benchmark/perf/version' Gem::Specification.new do |spec| spec.name = "benchmark-perf" spec.version = Benchmark::Perf::VERSION spec.authors = ["Piotr Murach"] spec.email = ["me@piotrmurach.com"] spec.summary = %q{Execution time and iteration performance benchmarking} spec.description = %q{Execution time and iteration performance benchmarking} spec.homepage = "" spec.license = "MIT" spec.files = Dir['{lib,spec}/**/*.rb'] spec.files += Dir['tasks/*', 'benchmark-perf.gemspec'] spec.files += Dir['README.md', 'CHANGELOG.md', 'LICENSE.txt', 'Rakefile'] spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^spec/}) spec.require_paths = ["lib"] spec.required_ruby_version = '>= 2.0.0' spec.add_development_dependency 'bundler', '>= 1.16' spec.add_development_dependency 'rspec', '~> 3.0' spec.add_development_dependency 'rake' end
require_relative "lib/benchmark/perf/version" Gem::Specification.new do |spec| spec.name = "benchmark-perf" spec.version = Benchmark::Perf::VERSION spec.authors = ["Piotr Murach"] spec.email = ["piotr@piotrmurach.com"] spec.summary = %q{Execution time and iteration performance benchmarking} spec.description = %q{Execution time and iteration performance benchmarking} spec.homepage = "https://github.com/piotrmurach/benchmark-perf" spec.license = "MIT" spec.metadata = { "allowed_push_host" => "https://rubygems.org", "bug_tracker_uri" => "https://github.com/piotrmurach/benchmark-perf/issues", "changelog_uri" => "https://github.com/piotrmurach/benchmark-perf/blob/master/CHANGELOG.md", "documentation_uri" => "https://www.rubydoc.info/gems/benchmark-perf", "homepage_uri" => spec.homepage, "source_code_uri" => "https://github.com/piotrmurach/benchmark-perf" } spec.files = Dir["lib/**/*", "README.md", "CHANGELOG.md", "LICENSE.txt"] spec.extra_rdoc_files = ["README.md", "CHANGELOG.md"] spec.require_paths = ["lib"] spec.required_ruby_version = ">= 2.0.0" end
Add specs for other attributes
require "spec_helper" require "conceptual/attributes" RSpec.describe Conceptual::Attribute do describe("StringAttribute") do subject(:attr) { Conceptual::StringAttribute.new(:name) } describe(:name) do subject { attr.name } it "is as initializer receives" do expect(subject).to eq(:name) end end end end
require "spec_helper" require "conceptual/attributes" RSpec.describe Conceptual::Attribute do describe("StringAttribute") do subject(:attr) { Conceptual::StringAttribute.new(:name) } describe(:name) do subject { attr.name } it "is as initializer receives" do expect(subject).to eq(:name) end end end describe("IntAttribute") do subject(:attr) { Conceptual::IntAttribute.new(:age) } describe(:name) do subject { attr.name } it "is as initializer receives" do expect(subject).to eq(:age) end end end describe("DateAttribute") do subject(:attr) { Conceptual::DateAttribute.new(:birthday) } describe(:name) do subject { attr.name } it "is as initializer receives" do expect(subject).to eq(:birthday) end end end describe("DatetimeAttribute") do subject(:attr) { Conceptual::DateTimeAttribute.new(:created_at) } describe(:name) do subject { attr.name } it "is as initializer receives" do expect(subject).to eq(:created_at) end end end end
Remove member_actions as it is not being used.
require "canonical-rails/engine" module CanonicalRails # Default way to setup CanonicalRails. Run `rails g canonical_rails:install` to create # a fresh initializer with all configuration values. # # the config\setup concept politely observed at and borrowed from Devise: https://github.com/plataformatec/devise/blob/master/lib/devise.rb def self.setup yield self end mattr_accessor :host @@host = nil mattr_accessor :protocol @@protocol = nil mattr_accessor :collection_actions @@collection_actions = [:index] mattr_accessor :member_actions @@member_actions = [:show] mattr_accessor :whitelisted_parameters @@whitelisted_parameters = [] def self.sym_collection_actions @@sym_collection_actions ||= self.collection_actions.map(&:to_sym) end def self.sym_whitelisted_parameters @@sym_whitelisted_actions ||= self.whitelisted_parameters.map(&:to_sym) end end
require "canonical-rails/engine" module CanonicalRails # Default way to setup CanonicalRails. Run `rails g canonical_rails:install` to create # a fresh initializer with all configuration values. # # the config\setup concept politely observed at and borrowed from Devise: https://github.com/plataformatec/devise/blob/master/lib/devise.rb def self.setup yield self end mattr_accessor :host @@host = nil mattr_accessor :protocol @@protocol = nil mattr_accessor :collection_actions @@collection_actions = [:index] mattr_accessor :whitelisted_parameters @@whitelisted_parameters = [] def self.sym_collection_actions @@sym_collection_actions ||= self.collection_actions.map(&:to_sym) end def self.sym_whitelisted_parameters @@sym_whitelisted_actions ||= self.whitelisted_parameters.map(&:to_sym) end end
Add the private methods to the class instance
require 'play_store_info/errors' require 'play_store_info/app_parser' require 'metainspector' require 'sanitize' module PlayStoreInfo MIN_IDS_REGEXP_MATCHES = 2 FIRST_ID_REGEXP_MATCH = 1 def self.read(id, lang = 'en') parse(id, "https://play.google.com/store/apps/details?id=#{id}&hl=#{lang}") end def self.read_url(url) id = url.match(/id=([[:alnum:]\.]+)[&]?/) raise InvalidStoreLink unless google_store?(url) && id && id.length == MIN_IDS_REGEXP_MATCHES parse(id[FIRST_ID_REGEXP_MATCH], url) end private def parse(id, url) inspector ||= MetaInspector.new(url) raise AppNotFound unless inspector.response.status == 200 AppParser.new(id, inspector.parsed) rescue Faraday::ConnectionFailed, Faraday::SSLError, Errno::ETIMEDOUT raise ConnectionError end def google_store?(url) url.match(%r{\Ahttps://play.google.com}) end end
require 'play_store_info/errors' require 'play_store_info/app_parser' require 'metainspector' require 'sanitize' module PlayStoreInfo MIN_IDS_REGEXP_MATCHES = 2 FIRST_ID_REGEXP_MATCH = 1 class << self def read(id, lang = 'en') parse(id, "https://play.google.com/store/apps/details?id=#{id}&hl=#{lang}") end def read_url(url) id = url.match(/id=([[:alnum:]\.]+)[&]?/) raise InvalidStoreLink unless google_store?(url) && id && id.length == MIN_IDS_REGEXP_MATCHES parse(id[FIRST_ID_REGEXP_MATCH], url) end private def parse(id, url) inspector ||= MetaInspector.new(url) raise AppNotFound unless inspector.response.status == 200 AppParser.new(id, inspector.parsed) rescue Faraday::ConnectionFailed, Faraday::SSLError, Errno::ETIMEDOUT raise ConnectionError end def google_store?(url) url.match(%r{\Ahttps://play.google.com}) end end end
Rename methods to be more descriptive
# # Copyright (c) 2012-2013 by Lifted Studios. All Rights Reserved. # require 'html/pipeline' module HTML class Pipeline # An `HTML::Pipeline` filter class that detects wiki-style links and converts them to HTML links. class WikiLinkFilter < Filter # Performs the translation and returns the updated text. # # @return [String] Updated text with translated wiki links. def call text = html.gsub(/\[\[(.*)\|(.*)\]\]/) do |match| link = $1 desc = $2 link = convert_spaces(link) desc = collapse_spaces(desc) "<a href=\"/#{link}\">#{desc}</a>" end text.gsub(/\[\[(.*)\]\]/) do |match| desc = $1 link = convert_spaces(desc) desc = collapse_spaces(desc) "<a href=\"/#{link}\">#{desc}</a>" end end private # Collapses multiple whitespace characters into a single space. # # @param text Text within which to collapse whitespace. # @return Text with collapsed whitespace. def collapse_spaces(text) text.gsub(/\s+/, ' ') end # Converts spaces to underscores in the given text. # # @param text Text within which to replace spaces. # @return Text with spaces replaced with underscores. def convert_spaces(text) text.gsub(/\s+/, '_') end end end end
# # Copyright (c) 2012-2013 by Lifted Studios. All Rights Reserved. # require 'html/pipeline' module HTML class Pipeline # An `HTML::Pipeline` filter class that detects wiki-style links and converts them to HTML links. class WikiLinkFilter < Filter # Performs the translation and returns the updated text. # # @return [String] Updated text with translated wiki links. def call text = html.gsub(/\[\[(.*)\|(.*)\]\]/) do |match| link = $1 desc = $2 link = convert_whitespace(link) desc = collapse_whitespace(desc) "<a href=\"/#{link}\">#{desc}</a>" end text.gsub(/\[\[(.*)\]\]/) do |match| desc = $1 link = convert_whitespace(desc) desc = collapse_whitespace(desc) "<a href=\"/#{link}\">#{desc}</a>" end end private # Collapses multiple whitespace characters into a single space. # # @param text Text within which to collapse whitespace. # @return Text with collapsed whitespace. def collapse_whitespace(text) text.gsub(/\s+/, ' ') end # Converts spaces to underscores in the given text. # # @param text Text within which to replace spaces. # @return Text with spaces replaced with underscores. def convert_whitespace(text) text.gsub(/\s+/, '_') end end end end
Add hidden scope to make it easier to play with categories.
class Category < ActiveRecord::Base has_many :skills has_many :courses, through: :skills validates_presence_of :name, :handle validates_uniqueness_of :handle default_scope -> { where(hidden: false) } scope :sorted, -> { order(:sort_order) } scope :by_courses, -> (courses) { includes(:courses).where(id: courses.map(&:id)) } def self.summarize table = self.arel_table attributes = [table[:id], table[:name], table[:handle]] table.project(attributes).group(attributes).order(table[:sort_order]) end end
class Category < ActiveRecord::Base has_many :skills has_many :courses, through: :skills validates_presence_of :name, :handle validates_uniqueness_of :handle default_scope -> { where(hidden: false) } scope :hidden, -> { where(hidden: true) } scope :sorted, -> { order(:sort_order) } scope :by_courses, -> (courses) { includes(:courses).where(id: courses.map(&:id)) } def self.summarize table = self.arel_table attributes = [table[:id], table[:name], table[:handle]] table.project(attributes).group(attributes).order(table[:sort_order]) end end
Add some tests for cookies_concern
require 'rails_helper' RSpec.describe Referrals::CookiesConcern, type: :controller do controller(ApplicationController) do include Referrals::CookiesConcern def fake_action; render plain: 'ok'; end end before do routes.draw { get 'fake_action' => 'anonymous#fake_action' } end describe '#handle_pid' do context "when no pid in request" do before { get :fake_action } it "does not set referral cookie" do expect(response.cookies[:referrals_pid]).to eq(nil) end end context "when pid in request" do context "when no cookie set" do context "when partner exists" do it "" do FactoryGirl.create(:partner) end end context "when partner does not exist" do end end context "when cookie set" do end end end end
require 'rails_helper' RSpec.describe Referrals::CookiesConcern, type: :controller do controller(ApplicationController) do include Referrals::CookiesConcern def fake_action; render plain: 'ok'; end end before do routes.draw { get 'fake_action' => 'anonymous#fake_action' } end describe '#handle_pid' do context "when no pid in request" do before { get :fake_action } it "does not set referral cookie" do expect(response.cookies['referrals_pid']).to eq(nil) end end context "when pid in request" do context "when no cookie set" do context "when partner exists" do let!(:partner) { FactoryGirl.create(:partner) } it "set cookie value to partner id" do get :fake_action, params: { pid: partner.id } expected = { value: partner.id, expires: 1.year.from_now } expect(response.cookies['referrals_pid']).to eq(partner.id.to_s) end it "set cookie expiration time" do date = 1.year.from_now allow_any_instance_of(ActiveSupport::Duration).to receive(:from_now).and_return(date) # thanks to http://bit.ly/2hXQka9 stub_cookie_jar = HashWithIndifferentAccess.new allow(controller).to receive(:cookies).and_return(stub_cookie_jar) get :fake_action, params: { pid: partner.id } expect(stub_cookie_jar['referrals_pid'][:expires]).to eq(date) end end context "when partner does not exist" do it "does not set cookie" do get :fake_action, params: { pid: 7 } expect(response.cookies['referrals_pid']).to eq(nil) end end end context "when cookie set" do end end context "when no pid in request" do end end end
Make (most) date helpers locale-aware.
module DatesHelper # Format a datestamp as "December 26, 2015 at 8:45 PM" def long_friendly_datetime(date) date.strftime("%B %e, %Y at %l:%M%p") end # Format a datestamp as "December 26, 2015" def long_friendly_date(date) date.strftime("%B %e, %Y") end # Format a datestamp as "Dec 26 - 20:45" def short_friendly_datetime(date) date.strftime("%b %e - %k:%M") end # Format a datestamp as "Dec 26" def short_friendly_date(date) date.strftime("%b %e") end def friendly_time(date) date.strftime("%l:%M%p") end end
module DatesHelper # Format a datestamp as "December 26, 2015 at 8:45 PM" def long_friendly_datetime(date) date.strftime("%B %e, %Y at %l:%M%p") end # Format a datestamp as "December 26, 2015" def long_friendly_date(date) l(date, format: "%B %e, %Y") end # Format a datestamp as "Dec 26 - 20:45" def short_friendly_datetime(date) l(date, format: "%b %e - %k:%M") end # Format a datestamp as "Dec 26" def short_friendly_date(date) l(date, format: "%b %e") end def friendly_time(date) l(date, format: "%l:%M%p") end end
Create class method User.new_token to create a new token
require 'bcrypt' class User < ApplicationRecord validates :username, presence: { message: "Username field can't be left blank"}, length: { in: 4..15, message: 'Username must be between 4-15 characters in length' }, uniqueness: { message: 'Username is already taken'} # email validation still needs email format validation validates :email, presence: { message: "Email can't be left blank" }, uniqueness: { message: "Email is already taken"} validates :password, presence: { message: "Password field can't be left blank" }, length: { in: 4..10, message: "Password must be between 4-15 characters in length" } has_secure_password validations: false end
require 'bcrypt' class User < ApplicationRecord validates :username, presence: { message: "Username field can't be left blank"}, length: { in: 4..15, message: 'Username must be between 4-15 characters in length' }, uniqueness: { message: 'Username is already taken'} # email validation still needs email format validation validates :email, presence: { message: "Email can't be left blank" }, uniqueness: { message: "Email is already taken"} validates :password, presence: { message: "Password field can't be left blank" }, length: { in: 4..10, message: "Password must be between 4-15 characters in length" } has_secure_password validations: false # Returns a random token def User.new_token SecureRandom.urlsafe_base64 end end
Move `Format` class to `Format` module
module Calyx class Format def self.load(filename) file = File.read(filename) extension = File.extname(filename) if extension == ".yml" self.load_yml(file) elsif extension == ".json" self.load_json(file) else raise "Cannot convert #{extension} files." end end def self.load_yml(file) require 'yaml' yaml = YAML.load(file) self.build_grammar(yaml) end def self.load_json(file) require 'json' json = JSON.parse(file) self.build_grammar(json) end private def self.build_grammar(rules) Calyx::Grammar.new do rules.each do |label, productions| rule(label, *productions) end end end end end
module Calyx module Format def self.load(filename) file = File.read(filename) extension = File.extname(filename) if extension == ".yml" self.load_yml(file) elsif extension == ".json" self.load_json(file) else raise "Cannot convert #{extension} files." end end def self.load_yml(file) require 'yaml' yaml = YAML.load(file) self.build_grammar(yaml) end def self.load_json(file) require 'json' json = JSON.parse(file) self.build_grammar(json) end private def self.build_grammar(rules) Calyx::Grammar.new do rules.each do |label, productions| rule(label, *productions) end end end end end
Fix some N+1 queries on the home page.
class HomeController < ApplicationController def home @filter = CollectionFilter.new(current_user, LightweightActivity, params[:filter] || {}) # TODO: Add 'oficial' to the criteron? @activities = @filter.collection.first(10) @filter.klass = Sequence # TODO: Add 'oficial' to the criteron? @sequences = @filter.collection.first(10) end end
class HomeController < ApplicationController def home @filter = CollectionFilter.new(current_user, LightweightActivity, params[:filter] || {}) # TODO: Add 'oficial' to the criteron? @activities = @filter.collection.includes(:user,:changed_by,:portal_publications,:runs).first(10) @filter.klass = Sequence # TODO: Add 'oficial' to the criteron? @sequences = @filter.collection.includes(:user,:lightweight_activities).first(10) end end
Add example of creating and deleting plans on a connected user's account.
#! /usr/bin/ruby # Example of deleting a plan on a connected user's account require "stripe" # You can do it by passing the access token as an additional parameter on calls made with your own secret key Stripe.api_key = ENV['STRIPE_SECRET_KEY'] access_token = ENV['STRIPE_ACCESS_TOKEN'] p Stripe.api_key plan_id = "gold" + rand(1..10).to_s Stripe::Plan.create( { :amount => 2000, :interval => 'month', :name => 'Amazing Plan '+ plan_id, :currency => 'usd', :id => plan_id}, access_token ) plan = Stripe::Plan.retrieve(plan_id,access_token) p plan puts "Sleeping..." sleep(30) plan.delete # Or you can do it by using the access token directly as the api key Stripe.api_key = access_token plan_id = "gold" + rand(1..10).to_s Stripe::Plan.create( :amount => 2000, :interval => 'month', :name => 'Amazing Plan '+ plan_id, :currency => 'usd', :id => plan_id ) plan = Stripe::Plan.retrieve( plan_id ) p plan puts "Sleeping..." sleep(30) plan.delete
Update to latest ember-source dependency
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'iridium/ember/version' Gem::Specification.new do |gem| gem.name = "iridium-ember" gem.version = Iridium::Ember::VERSION gem.authors = ["Adam Hawkins"] gem.email = ["me@brodcastingdam.com"] gem.description = %q{Ember integration for Iridium} gem.summary = %q{} gem.homepage = "https://github.com/radiumsoftware/iridium-ember" gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.add_dependency "barber" gem.add_dependency "ember-source", "1.0.0rc2" gem.add_development_dependency "rake" gem.add_development_dependency "simplecov" gem.add_development_dependency "mocha" end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'iridium/ember/version' Gem::Specification.new do |gem| gem.name = "iridium-ember" gem.version = Iridium::Ember::VERSION gem.authors = ["Adam Hawkins"] gem.email = ["me@brodcastingdam.com"] gem.description = %q{Ember integration for Iridium} gem.summary = %q{} gem.homepage = "https://github.com/radiumsoftware/iridium-ember" gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.add_dependency "barber" gem.add_dependency "ember-source", "1.0.0.rc6.4" gem.add_development_dependency "rake" gem.add_development_dependency "simplecov" gem.add_development_dependency "mocha" end
Fix typo (spotted by @mrcasals)
# Public: The Hyperclient module has various methods to so you can setup your # API client. # # Examples # # class MyAPI # extend Hyperclient # # entry_point 'http://api.myapp.com' # end # module Hyperclient # Internal: Extend the parent class with our class methods. def self.included(base) base.send :extend, ClassMethods end private # Private: Initializes the API with the entry point. def api @api = Resource.new('/') unless @api @api end # Private: Delegate the method to the API if it exists. # # This way the we can call our API client with the resources name instead of # having to add the methods to it. def method_missing(method, *args, &block) if api.respond_to?(method) api.send(method, *args, &block) else super end end module ClassMethods # Public: Set the entry point of your API. # # Returns nothing. def entry_point(url) Resource.entry_point = url end end end require 'hyperclient/resource' require "hyperclient/version"
# Public: The Hyperclient module has various methods to so you can setup your # API client. # # Examples # # class MyAPI # extend Hyperclient # # entry_point 'http://api.myapp.com' # end # module Hyperclient # Internal: Extend the parent class with our class methods. def self.included(base) base.send :extend, ClassMethods end private # Private: Initializes the API with the entry point. def api @api = Resource.new('/') unless @api @api end # Private: Delegate the method to the API if it exists. # # This way we can call our API client with the resources name instead of # having to add the methods to it. def method_missing(method, *args, &block) if api.respond_to?(method) api.send(method, *args, &block) else super end end module ClassMethods # Public: Set the entry point of your API. # # Returns nothing. def entry_point(url) Resource.entry_point = url end end end require 'hyperclient/resource' require "hyperclient/version"
Use create with a bang
class GamesController < ApplicationController def index end def create game = Game.create redirect_to game end def show @game = Game.find(params[:id]) @game.deal end end
class GamesController < ApplicationController def index end def create game = Game.create! redirect_to game end def show @game = Game.find(params[:id]) @game.deal end end
Use default date in gemspec
$: << File.expand_path('../lib', __FILE__) require 'overcommit/version' Gem::Specification.new do |s| s.name = 'overcommit' s.version = Overcommit::VERSION s.license = 'MIT' s.date = '2013-05-15' s.summary = 'Opinionated git hook manager' s.description = 'Overcommit is a utility to install and extend git hooks' s.authors = ['Causes Engineering'] s.email = 'eng@causes.com' s.homepage = 'http://github.com/causes/overcommit' s.require_paths = %w[lib] s.executables = ['overcommit'] s.files = `git ls-files -- lib`.split("\n") end
$: << File.expand_path('../lib', __FILE__) require 'overcommit/version' Gem::Specification.new do |s| s.name = 'overcommit' s.version = Overcommit::VERSION s.license = 'MIT' s.summary = 'Opinionated git hook manager' s.description = 'Overcommit is a utility to install and extend git hooks' s.authors = ['Causes Engineering'] s.email = 'eng@causes.com' s.homepage = 'http://github.com/causes/overcommit' s.require_paths = %w[lib] s.executables = ['overcommit'] s.files = `git ls-files -- lib`.split("\n") end
Exclude gettimeofday() tests on Windows.
# # This file is part of ruby-ffi. # For licensing, see LICENSE.SPECS # require File.expand_path(File.join(File.dirname(__FILE__), "spec_helper")) class Timeval < FFI::Struct layout :tv_sec, :ulong, 0, :tv_usec, :ulong, 4 end module LibC extend FFI::Library ffi_lib FFI::Library::LIBC attach_function :gettimeofday, [:pointer, :pointer], :int end describe FFI::Library, "#attach_function" do it "correctly returns a value for gettimeofday" do t = Timeval.new time = LibC.gettimeofday(t.pointer, nil) expect(time).to be_kind_of(Integer) end it "correctly populates a struct for gettimeofday" do t = Timeval.new LibC.gettimeofday(t.pointer, nil) expect(t[:tv_sec]).to be_kind_of(Numeric) expect(t[:tv_usec]).to be_kind_of(Numeric) end end
# # This file is part of ruby-ffi. # For licensing, see LICENSE.SPECS # require File.expand_path(File.join(File.dirname(__FILE__), "spec_helper")) unless FFI::Platform.windows? class Timeval < FFI::Struct layout :tv_sec, :ulong, 0, :tv_usec, :ulong, 4 end module LibC extend FFI::Library ffi_lib FFI::Library::LIBC attach_function :gettimeofday, [:pointer, :pointer], :int end describe FFI::Library, "#attach_function" do it "correctly returns a value for gettimeofday" do t = Timeval.new time = LibC.gettimeofday(t.pointer, nil) expect(time).to be_kind_of(Integer) end it "correctly populates a struct for gettimeofday" do t = Timeval.new LibC.gettimeofday(t.pointer, nil) expect(t[:tv_sec]).to be_kind_of(Numeric) expect(t[:tv_usec]).to be_kind_of(Numeric) end end end
Add optional parameters for /random and /randompic to allow specification of arbitrary flickr users and tag
require 'sinatra' require 'flickraw' def random_pic_url FlickRaw.api_key = ENV['FLICKR_API_KEY'] FlickRaw.shared_secret = ENV['FLICKR_SHARED_SECRET'] user_id = ENV['FLICKR_USER_ID'] list = flickr.photos.search :user_id => user_id, :tags => ENV['FLICKR_TAG'] ridx = rand(list.count) info = flickr.photos.getInfo :photo_id => list[ridx].id, :secret => list[ridx].secret FlickRaw.url_z(info) end configure do mime_type :jpg, 'image/jpeg' end get '/' do "Meow!" end get '/random' do random_pic_url end get '/randompic' do "<img src=\"#{random_pic_url}\">" end
require 'sinatra' require 'flickraw' def random_pic_url(user_id = nil, tag = nil) FlickRaw.api_key = ENV['FLICKR_API_KEY'] FlickRaw.shared_secret = ENV['FLICKR_SHARED_SECRET'] if (user_id == nil) user_id = ENV['FLICKR_USER_ID'] tag = ENV['FLICKR_TAG'] end begin list = flickr.photos.search :user_id => user_id, :tags => tag rescue list = nil end if (list != nil && list.count != 0) ridx = rand(list.count) info = flickr.photos.getInfo :photo_id => list[ridx].id, :secret => list[ridx].secret FlickRaw.url_z(info) else nil end end configure do mime_type :jpg, 'image/jpeg' end get '/' do "Meow!" end get '/random' do url = random_pic_url(params[:user_id], params[:tag]) if (url) url else [404,"no pics found"] end end get '/randompic/?:user_id?/?:tag?' do url = random_pic_url(params[:user_id], params[:tag]) if (url) "<img src=\"#{url}\">" else [404,"no pics found"] end end
Return an empty response to not crash sinatra and rack
require 'httparty' require 'sinatra' require 'json' post '/payload' do push = JSON.parse(request.body.read) # parse the JSON repo_name = push['repository']['full_name'] # look through each commit message push["commits"].each do |commit| # Look for an AWS access key # See https://blogs.aws.amazon.com/security/blog/tag/key+rotation for the pattern if /(?<![A-Z0-9])[A-Z0-9]{20}(?![A-Z0-9])/.match commit['message'] state = 'failure' description = 'It looks like you commit a AWS access key. Please review your changes!' else state = 'success' description = 'Ave, I did not find any AWS credentials!' end # post status to GitHub sha = commit["id"] status_url = "https://api.github.com/repos/#{repo_name}/statuses/#{sha}" status = { "state" => state, "description" => description, "target_url" => "https://github.com/mchv/github-aws-credential-checker", "context" => "validate/no-credentials-in-commits" } HTTParty.post(status_url, :body => status.to_json, :headers => { 'Content-Type' => 'application/json', 'User-Agent' => 'mchv/github-aws-credential-checker', 'Authorization' => "token #{ENV['TOKEN']}" } ) end end
require 'httparty' require 'sinatra' require 'json' post '/payload' do push = JSON.parse(request.body.read) # parse the JSON repo_name = push['repository']['full_name'] # look through each commit message push["commits"].each do |commit| # Look for an AWS access key # See https://blogs.aws.amazon.com/security/blog/tag/key+rotation for the pattern if /(?<![A-Z0-9])[A-Z0-9]{20}(?![A-Z0-9])/.match commit['message'] state = 'failure' description = 'It looks like you commit a AWS access key. Please review your changes!' else state = 'success' description = 'Ave, I did not find any AWS credentials!' end # post status to GitHub sha = commit["id"] status_url = "https://api.github.com/repos/#{repo_name}/statuses/#{sha}" status = { "state" => state, "description" => description, "target_url" => "https://github.com/mchv/github-aws-credential-checker", "context" => "validate/no-credentials-in-commits" } HTTParty.post(status_url, :body => status.to_json, :headers => { 'Content-Type' => 'application/json', 'User-Agent' => 'mchv/github-aws-credential-checker', 'Authorization' => "token #{ENV['TOKEN']}" } ) end # return an empty reponse "" end
Tweak the way Python dependency is expressed.
class NormalizeFilename < Formula desc "Normalize Filename" homepage "http://github.com/andrewferrier/normalize-filename" url "https://github.com/andrewferrier/normalize-filename/archive/X.Y.zip" version "X.Y" depends_on :python3 def install bin.install "normalize-filename" doc.install "README.md", "LICENSE.txt" end end
class NormalizeFilename < Formula desc "Normalize Filename" homepage "http://github.com/andrewferrier/normalize-filename" url "https://github.com/andrewferrier/normalize-filename/archive/X.Y.zip" version "X.Y" depends_on "python@3" def install bin.install "normalize-filename" doc.install "README.md", "LICENSE.txt" end end
Fix homepage url in gemspec
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'kong/version' Gem::Specification.new do |spec| spec.name = "kong" spec.version = Kong::VERSION spec.authors = ["Lauri Nevala"] spec.email = ["lauri@kontena.io"] spec.summary = %q{A Ruby client for the Kong API } spec.description = %q{A Ruby client for the Kong API} spec.homepage = "https://github/kontena/kong-client-ruby" spec.license = "Apache-2.0" spec.files = `git ls-files -z`.split("\x0") spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.required_ruby_version = ">= 2.0.0" spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" spec.add_runtime_dependency "excon", "~> 0.49.0" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'kong/version' Gem::Specification.new do |spec| spec.name = "kong" spec.version = Kong::VERSION spec.authors = ["Lauri Nevala"] spec.email = ["lauri@kontena.io"] spec.summary = %q{A Ruby client for the Kong API } spec.description = %q{A Ruby client for the Kong API} spec.homepage = "https://github.com/kontena/kong-client-ruby" spec.license = "Apache-2.0" spec.files = `git ls-files -z`.split("\x0") spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.required_ruby_version = ">= 2.0.0" spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" spec.add_runtime_dependency "excon", "~> 0.49.0" end
Change the path the stand-alone sidekiq admin runs on to /sidekiq
require 'sidekiq' Sidekiq.configure_client do |config| config.redis = { :size => 1 } end require 'sidekiq/web' use Rack::Session::Cookie, :secret => ENV.fetch('SESSION_SECRET_KEY') run Sidekiq::Web
require 'sidekiq' Sidekiq.configure_client do |config| config.redis = { :size => 1 } end require 'sidekiq/web' use Rack::Session::Cookie, :secret => ENV.fetch('SESSION_SECRET_KEY') run Rack::URLMap.new('/sidekiq' => Sidekiq::Web)
Add documentation of public Adapter.new interface
module Veritas module Adapter module Arango # Adapter to read tuples from remote elasticsearch database class Adapter include Adamantium::Flat, Composition.new(:database, :logger) # Return new adapter # # @param [Ashikawa::Core::Database] _database # @param [NullLogger] _logger # # @return [undefined] # # @api private # def self.new(_database, _logger = NullLogger.instance) super end # Return reader for base relation # # @param [Relation::Base] base_relation # the relation to read from # # @return [Reader] # the reader # # @api private # def reader(base_relation) Reader.new(self, base_relation) end # Return gateway for arango adapter # # @param [Relation::Base] base_relation # # @return [Gateway] # # @api private # def gateway(base_relation) Gateway.new(self, base_relation) end end end end end
module Veritas module Adapter module Arango # Adapter to read tuples from remote elasticsearch database class Adapter include Adamantium::Flat, Composition.new(:database, :logger) # Return new adapter # # @param [Ashikawa::Core::Database] _database # @param [NullLogger] _logger # # @return [undefined] # # @example # # database = Ashikawa::Core::Database.new('http://localhost:8529') # adapter = Veritas::Adapter::Arango::Adapter.new(database, Logger.new($stderr, :debug)) # # @api public # def self.new(_database, _logger = NullLogger.instance) super end # Return reader for base relation # # @param [Relation::Base] base_relation # the relation to read from # # @return [Reader] # the reader # # @api private # def reader(base_relation) Reader.new(self, base_relation) end # Return gateway for arango adapter # # @param [Relation::Base] base_relation # # @return [Gateway] # # @api private # def gateway(base_relation) Gateway.new(self, base_relation) end end end end end
Change HwErratum Class to no longer extend BaseErratum, all variables except id are options
module Origen module Errata class HwErratum < BaseErratum attr_accessor :hw_workaround_description, :disposition, :impact, :fix_plan, :affected_items def initialize(id, title, description, hw_workaround_description, disposition, impact, fix_plan, affected_items, options = {}) super(id, type = "hw", title, description) @hw_workaround_description = hw_workaround_description @disposition = disposition @impact = impact @fix_plan = fix_plan @affected_items = affected_items end end end end
module Origen module Errata class HwErratum attr_accessor :id, :title, :description, :hw_workaround_description, :disposition, :impact, :fix_plan, :affected_items, :sw_workaround def initialize(id, options = {}) @id = id @title = options[:title] @description = options[:description] @hw_workaround_description = options[:hw_workaround_description] @disposition = options[:disposition] @impact = options[:impact] @fix_plan = options[:fix_plan] @affected_items = options[:affected_items] @sw_workaround = options[:sw_workaround] end end end end
Disable all RSpec monkey patching
require 'codeclimate-test-reporter' CodeClimate::TestReporter.start ENV['RAILS_ENV'] = 'test' begin require 'pry' rescue LoadError end require_relative '../config/environment' require 'mas/development_dependencies/rspec/spec_helper' require 'webmock/rspec' require 'factory_girl' require 'html_validation' require 'core/repositories/categories/fake' Core::Registries::Repository[:category] = Core::Repositories::Categories::Fake.new I18n.available_locales = [:en, :cy] Draper::ViewContext.test_strategy :fast FactoryGirl.definition_file_paths << File.join(File.dirname(__FILE__), '..', 'features', 'factories') FactoryGirl.find_definitions RSpec.configure do |c| c.include FactoryGirl::Syntax::Methods c.include PageValidations c.alias_it_should_behave_like_to :it_has_behavior, 'exhibits behaviour of an' c.expose_dsl_globally = false end WebMock.disable_net_connect!(allow: 'codeclimate.com') PageValidations::HTMLValidation.ignored_attribute_errors = ['tabindex'] PageValidations::HTMLValidation.ignored_tag_errors = ['main']
require 'codeclimate-test-reporter' CodeClimate::TestReporter.start ENV['RAILS_ENV'] = 'test' begin require 'pry' rescue LoadError end require_relative '../config/environment' require 'mas/development_dependencies/rspec/spec_helper' require 'webmock/rspec' require 'factory_girl' require 'html_validation' require 'core/repositories/categories/fake' Core::Registries::Repository[:category] = Core::Repositories::Categories::Fake.new I18n.available_locales = [:en, :cy] Draper::ViewContext.test_strategy :fast FactoryGirl.definition_file_paths << File.join(File.dirname(__FILE__), '..', 'features', 'factories') FactoryGirl.find_definitions RSpec.configure do |c| c.include FactoryGirl::Syntax::Methods c.include PageValidations c.alias_it_should_behave_like_to :it_has_behavior, 'exhibits behaviour of an' c.disable_monkey_patching! end WebMock.disable_net_connect!(allow: 'codeclimate.com') PageValidations::HTMLValidation.ignored_attribute_errors = ['tabindex'] PageValidations::HTMLValidation.ignored_tag_errors = ['main']
Increase version to 1.0.1 and gem date
require 'rake' Gem::Specification.new do |s| s.name = 'udooneorest' s.version = '1.0.0' s.date = '2015-12-07' s.summary = 'Rest API for interacting with UDOO Neo' s.description = 'Rest API for interacting with UDOO Neo GPIOs, motion sensors and brick sensors' s.authors = ['Mark Sullivan'] s.email = 'mark@sullivans.id.au' s.files = FileList['lib/**/*.rb', '[A-Z]*'].to_a s.homepage = 'http://rubygems.org/gems/udooneorest' s.license = 'MIT' s.add_runtime_dependency 'sinatra' s.executables = ['udooneorest'] end
require 'rake' Gem::Specification.new do |s| s.name = 'udooneorest' s.version = '1.0.1' s.date = '2015-12-13' s.summary = 'Rest API for interacting with UDOO Neo' s.description = 'Rest API for interacting with UDOO Neo GPIOs, motion sensors and brick sensors' s.authors = ['Mark Sullivan'] s.email = 'mark@sullivans.id.au' s.files = FileList['lib/**/*.rb', '[A-Z]*'].to_a s.homepage = 'http://rubygems.org/gems/udooneorest' s.license = 'MIT' s.add_runtime_dependency 'sinatra' s.executables = ['udooneorest'] end
Add own method for generating a random 'alnum' character
# To change this template, choose Tools | Templates # and open the template in the editor. # Ruby 1.8 does not contains sample() function class Array def sample() return self.choice() end end class RandomString def initialize end def self.generate(length = 20, alphabet = ('A' .. 'Z').to_a + ('a' .. 'z').to_a + ('0' .. '9').to_a) return (0 .. length).map { alphabet.sample }.join end def self.generate_name(length = 20) return (('A' .. 'Z').to_a + ('a' .. 'z').to_a).sample + generate(length - 1) end end
# To change this template, choose Tools | Templates # and open the template in the editor. # Ruby 1.8 does not contains sample() function # NB: # - ruby 1.8.6 has no equivalent method # - ruby 1.8.7 has choice() method # - ruby 1.9 has sample() method class Array def sec_sample() if self.respond_to?(:sample, true) return self.sample() elsif self.respond_to?(:choice, true) return self.choice() else return (('A' .. 'Z').to_a + ('a' .. 'z').to_a + ('0' .. '9').to_a)[Kernel.srand.modulo(62)] end end end class RandomString def initialize end def self.generate(length = 20, alphabet = ('A' .. 'Z').to_a + ('a' .. 'z').to_a + ('0' .. '9').to_a) return (0 .. length).map { alphabet.sec_sample }.join end def self.generate_name(length = 20) return (('A' .. 'Z').to_a + ('a' .. 'z').to_a).sec_sample + generate(length - 1) end end
Add an option to use upsert instead of insert.
module Metacrunch class Db::Writer def initialize(database_connection_or_url, dataset_proc, options = {}) @db = if database_connection_or_url.is_a?(String) Sequel.connect(database_connection_or_url, options) else database_connection_or_url end @dataset = dataset_proc.call(@db) end def write(data) if data.is_a?(Array) @db.transaction do data.each do |d| @dataset.insert(d) if d end end else @dataset.insert(data) if data end end def close @db.disconnect end end end
module Metacrunch class Db::Writer def initialize(database_connection_or_url, dataset_proc, options = {}) @use_upsert = options.delete(:use_upsert) || false @id_key = options.delete(:id_key) || :id @db = if database_connection_or_url.is_a?(String) Sequel.connect(database_connection_or_url, options) else database_connection_or_url end @dataset = dataset_proc.call(@db) end def write(data) if data.is_a?(Array) @db.transaction do data.each{|d| insert_or_upsert(d) } end else insert_or_upsert(data) end end def close @db.disconnect end private def insert_or_upsert(data) @use_upsert ? upsert(data) : insert(data) end def insert(data) @dataset.insert(data) if data end def upsert(data) if data rec = @dataset.where(id: data[@id_key]) if 1 != rec.update(data) insert(data) end end end end end
Support testing message key in RSpec
require "streamy/helpers/have_hash_matcher" module Streamy module Helpers module RspecHelper def expect_published_event(topic: kind_of(String), type:, body:, event_time: nil) expect(Streamy.message_bus.deliveries).to have_hash( topic: topic, type: type, body: body, event_time: event_time || kind_of(Time) ) end Streamy.message_bus = MessageBuses::TestMessageBus.new RSpec.configure do |config| config.include Streamy::Helpers::RspecHelper config.before(:each) do Streamy.message_bus.deliveries.clear end end end end end
require "streamy/helpers/have_hash_matcher" module Streamy module Helpers module RspecHelper def expect_published_event(topic: kind_of(String), key: kind_of(String), type:, body:, event_time: nil) expect(Streamy.message_bus.deliveries).to have_hash( topic: topic, key: key, type: type, body: body, event_time: event_time || kind_of(Time) ) end Streamy.message_bus = MessageBuses::TestMessageBus.new RSpec.configure do |config| config.include Streamy::Helpers::RspecHelper config.before(:each) do Streamy.message_bus.deliveries.clear end end end end end