Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix rails4 secret token config option. | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Dummy::Application.config.secret_token = 'c00157b5a1bb6181792f0f4a8a080485de7bab9987e6cf159dc74c4f0573345c1bfa713b5d756e1491fc0b098567e8a619e2f8d268eda86a20a720d05d633780'
| # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Dummy::Application.config.secret_key_base =
Dummy::Application.config.secret_token =
'c00157b5a1bb6181792f0f4a8a080485de7bab9987e6cf159dc74c4f0573345c1bfa713b5d756e1491fc0b098567e8a619e2f8d268eda86a20a720d05d633780'
|
Fix url and appcast to use SSL in MoneyMoney Cask | cask :v1 => 'moneymoney' do
version :latest
sha256 :no_check
url 'http://moneymoney-app.com/download/MoneyMoney.zip'
appcast 'http://moneymoney-app.com/update/appcast.xml'
name 'MoneyMoney'
homepage 'https://moneymoney-app.com/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'MoneyMoney.app'
end
| cask :v1 => 'moneymoney' do
version :latest
sha256 :no_check
url 'https://moneymoney-app.com/download/MoneyMoney.zip'
appcast 'https://moneymoney-app.com/update/appcast.xml'
name 'MoneyMoney'
homepage 'https://moneymoney-app.com/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'MoneyMoney.app'
end
|
Remove index route for pages | Rails.application.routes.draw do
get 'organizations/index'
get 'organizations/show'
resources :pages
namespace :admin do
DashboardManifest::DASHBOARDS.each do |dashboard_resource|
resources dashboard_resource
end
root controller: DashboardManifest::ROOT_DASHBOARD, action: :index
end
devise_for :users
resources :events, :news_items, :organizations
root 'home#index'
end
| Rails.application.routes.draw do
get 'organizations/index'
get 'organizations/show'
resources :pages, except: [:index]
namespace :admin do
DashboardManifest::DASHBOARDS.each do |dashboard_resource|
resources dashboard_resource
end
root controller: DashboardManifest::ROOT_DASHBOARD, action: :index
end
devise_for :users
resources :events, :news_items, :organizations
root 'home#index'
end
|
Add test for disclosures index page, ensuring links to each disclosure page | require "rails_helper"
describe "Disclosures" do
feature "creating a disclosure" do
it "accepts valid attributes" do
visit new_disclosure_path
fill_in "Title", with: "My New Valid Disclosure"
fill_in "Abstract", with: "This is my disclosure" * 10
fill_in "Body", with: "Here is a detailed description of my disclosure" * 30
check "Consented"
click_on "Create Disclosure"
expect(page).to have_content "Disclosure was successfully created"
expect(page).to have_content "My New Valid Disclosure"
end
it "rejects invalid attributes" do
visit new_disclosure_path
click_on "Create Disclosure"
expect(page).to have_content "can't be blank"
end
it "can be tagged" do
tag = FactoryGirl.create(:tag)
visit new_disclosure_path
fill_in "Title", with: "My New Valid Disclosure"
fill_in "Abstract", with: "This is my disclosure" * 10
fill_in "Body", with: "Here is a detailed description of my disclosure" * 30
check "Consented"
check tag.name
click_on "Create Disclosure"
expect(page).to have_content "Disclosure was successfully created"
expect(page).to have_content tag.name
end
end
end
| require "rails_helper"
describe "Disclosures" do
feature "creating a disclosure" do
it "accepts valid attributes" do
visit new_disclosure_path
fill_in "Title", with: "My New Valid Disclosure"
fill_in "Abstract", with: "This is my disclosure" * 10
fill_in "Body", with: "Here is a detailed description of my disclosure" * 30
check "Consented"
click_on "Create Disclosure"
expect(page).to have_content "Disclosure was successfully created"
expect(page).to have_content "My New Valid Disclosure"
end
it "rejects invalid attributes" do
visit new_disclosure_path
click_on "Create Disclosure"
expect(page).to have_content "can't be blank"
end
it "can be tagged" do
tag = FactoryGirl.create(:tag)
visit new_disclosure_path
fill_in "Title", with: "My New Valid Disclosure"
fill_in "Abstract", with: "This is my disclosure" * 10
fill_in "Body", with: "Here is a detailed description of my disclosure" * 30
check "Consented"
check tag.name
click_on "Create Disclosure"
expect(page).to have_content "Disclosure was successfully created"
expect(page).to have_link tag.name
end
end
feature "index page" do
it "has links to each disclosure" do
disclosure_1 = FactoryGirl.create(:disclosure)
disclosure_2 = FactoryGirl.create(:disclosure)
visit disclosures_path
expect(page).to have_link disclosure_1.title
expect(page).to have_link disclosure_2.title
end
end
end
|
Add specs for font since due to the conditional of updating font families if resume font is not included in the Prawn built-ins | require 'resume/pdf/font'
module Resume
module PDF
RSpec.describe Font do
describe '.configure' do
let(:font_families) { instance_double('Hash', :font_families) }
let(:pdf) do
instance_double(
'Prawn::Document',
:pdf,
font_families: font_families
)
end
let(:font_name) { 'My Font' }
let(:normal_font_file) { 'normal.ttf' }
let(:bold_font_file) { 'bold.ttf' }
let(:font) do
{
name: font_name,
normal: normal_font_file,
bold: bold_font_file
}
end
context 'when selected font is included in Prawn font built-ins' do
let(:built_ins) { [font_name] }
before do
stub_const('Prawn::Font::AFM::BUILT_INS', built_ins)
end
it 'sets the PDF font to the selected font' do
expect(pdf).to receive(:font).with(font_name)
described_class.configure(pdf, font)
end
end
context 'when selected font is not included in Prawn font built-ins' do
let(:built_ins) { ['SomeOtherFont'] }
let(:normal_font_file_path) { "/tmp/#{normal_font_file}" }
let(:bold_font_file_path) { "/tmp/#{normal_font_file}" }
before do
stub_const('Prawn::Font::AFM::BUILT_INS', built_ins)
allow(FileSystem).to \
receive(:tmpfile_path).with(normal_font_file).
and_return(normal_font_file_path)
allow(FileSystem).to \
receive(:tmpfile_path).with(bold_font_file).
and_return(bold_font_file_path)
end
it 'updates the PDF font families with the font and sets it' do
expect(font_families).to receive(:update).with(
font_name => {
normal: normal_font_file_path,
bold: bold_font_file_path
}
)
expect(pdf).to receive(:font).with(font_name)
described_class.configure(pdf, font)
end
end
end
end
end
end
| |
Include session helper in all application controllers | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
end
| class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
include SessionsHelper
end
|
Make regex group non capturing | require "email_assessor/email_validator"
module EmailAssessor
DISPOSABLE_DOMAINS_FILE_NAME = File.expand_path("../../vendor/disposable_domains.txt", __FILE__)
BLACKLISTED_DOMAINS_FILE_NAME = File.expand_path("vendor/blacklisted_domains.txt")
def self.domain_is_disposable?(domain)
domain_in_file?(domain, DISPOSABLE_DOMAINS_FILE_NAME)
end
def self.domain_is_blacklisted?(domain)
domain_in_file?(domain, BLACKLISTED_DOMAINS_FILE_NAME)
end
protected
def self.domain_in_file?(domain, file_name)
file_name ||= ""
domain = domain.downcase
File.open(file_name).each_line.any? { |line| domain =~ %r{\A(.*\.)*#{line.chomp}\z}i }
end
end
| require "email_assessor/email_validator"
module EmailAssessor
DISPOSABLE_DOMAINS_FILE_NAME = File.expand_path("../../vendor/disposable_domains.txt", __FILE__)
BLACKLISTED_DOMAINS_FILE_NAME = File.expand_path("vendor/blacklisted_domains.txt")
def self.domain_is_disposable?(domain)
domain_in_file?(domain, DISPOSABLE_DOMAINS_FILE_NAME)
end
def self.domain_is_blacklisted?(domain)
domain_in_file?(domain, BLACKLISTED_DOMAINS_FILE_NAME)
end
protected
def self.domain_in_file?(domain, file_name)
file_name ||= ""
domain = domain.downcase
File.open(file_name).each_line.any? { |line| domain =~ %r{\A(?:.+\.)*?#{line.chomp}\z}i }
end
end
|
Make the time output look a little better than something non-sensical | module Util
def self.ago_in_words(time1, time2)
diff = time1.to_i - time2.to_i
ago = ''
if diff == 1
ago = "#{diff} second ago"
elsif diff < 60
ago = "#{diff} seconds ago"
elsif diff < 120
ago = "a minute ago"
elsif diff < 3600
ago = "#{diff.to_i / 60} minutes ago"
elsif diff < 7200
ago = "an hour ago"
elsif diff < 86400
ago = "#{diff.to_i / 3600} hours ago"
elsif diff < 172800
ago = "yesterday"
elsif diff < 604800
ago = "#{diff.to_i / 86400} days ago"
elsif diff < 1209600
ago = "last week"
else
ago = "#{diff.to_i / 604800} weeks ago"
end
ago
end
end | module Util
def self.ago_in_words(time1, time2)
diff = time1.to_i - time2.to_i
ago = ''
if diff == 1
ago = "#{diff} second ago"
elsif diff < 60
ago = "#{diff} seconds ago"
elsif diff < 120
ago = "a minute ago"
elsif diff < 3600
ago = "#{(diff / 60).to_i} minutes ago"
elsif diff < 7200
ago = "an hour ago"
elsif diff < 86400
ago = "#{(diff / 3600).to_i} hours ago"
elsif diff < 172800
ago = "yesterday"
elsif diff < 604800
ago = "#{(diff / 86400).to_i} days ago"
elsif diff < 1209600
ago = "last week"
else
ago = "#{(diff / 604800).to_i} weeks ago"
end
ago
end
end |
Use Rack::Reloader in dev mode | require './application'
<%= app_const %>.initialize!
# Development middlewares
if <%= app_const %>.env == 'development'
require 'async-rack'
use AsyncRack::CommonLogger
end
# Running thin :
#
# bundle exec thin --max-persistent-conns 1024 -R config.ru start
#
# Vebose mode :
#
# Very useful when you want to view all the data being sent/received by thin
#
# bundle exec thin --max-persistent-conns 1024 -R -V config.ru start
#
run <%= app_const %>.routes
| require './application'
<%= app_const %>.initialize!
# Development middlewares
if <%= app_const %>.env == 'development'
require 'async-rack'
use AsyncRack::CommonLogger
# Enable code reloading on every request
use Rack::Reloader, 0
end
# Running thin :
#
# bundle exec thin --max-persistent-conns 1024 -R config.ru start
#
# Vebose mode :
#
# Very useful when you want to view all the data being sent/received by thin
#
# bundle exec thin --max-persistent-conns 1024 -R -V config.ru start
#
run <%= app_const %>.routes
|
Add test for join table index | require 'rails_helper'
RSpec.describe Menu, :type => :model do
let(:menu) { FactoryGirl.create(:menu) }
describe 'Fixtures' do
it 'should have valid fixture factory' do
expect(FactoryGirl.create(:menu)).to be_valid
end
end
describe 'Associations' do
it { is_expected.to have_and_belong_to_many :menu_items }
end
describe 'Database schema' do
it { is_expected.to have_db_column :show_category }
it { is_expected.to have_db_column :start_date }
it { is_expected.to have_db_column :end_date }
# Timestamps
it { is_expected.to have_db_column :created_at }
it { is_expected.to have_db_column :updated_at }
end
describe 'Validations' do
it { is_expected.to validate_presence_of :start_date }
it { is_expected.to validate_presence_of :end_date }
end
end
| require 'rails_helper'
RSpec.describe Menu, :type => :model do
let(:menu) { FactoryGirl.create(:menu) }
describe 'Fixtures' do
it 'should have valid fixture factory' do
expect(FactoryGirl.create(:menu)).to be_valid
end
end
describe 'Associations' do
it { is_expected.to have_and_belong_to_many :menu_items }
it 'join table should have unique index' do
ActiveRecord::Migration.index_exists?(:menu_items_menus, [:menu_id, :menu_item_id], unique: true)
end
end
describe 'Database schema' do
it { is_expected.to have_db_column :show_category }
it { is_expected.to have_db_column :start_date }
it { is_expected.to have_db_column :end_date }
# Timestamps
it { is_expected.to have_db_column :created_at }
it { is_expected.to have_db_column :updated_at }
end
describe 'Validations' do
it { is_expected.to validate_presence_of :start_date }
it { is_expected.to validate_presence_of :end_date }
end
end
|
Add rake as a development dependency | $LOAD_PATH.push File.expand_path("lib")
require 'bundler_ext/version'
Gem::Specification.new do |s|
s.name = "bundler_ext"
s.version = BundlerExt::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Jason Guiditta", "Mo Morsi", "Lukas Zapletal"]
s.email = ["mmorsi@redhat.com"]
s.homepage = "https://github.com/bundlerext/bundler_ext"
s.summary = "Load system gems via Bundler DSL"
s.description = "Simple library leveraging the Bundler Gemfile DSL to load gems already on the system and managed by the systems package manager (like yum/apt)"
s.license = 'MIT'
s.files = Dir["lib/**/*.rb", "README.md", "MIT-LICENSE","Rakefile","CHANGELOG"]
s.test_files = Dir["spec/**/*.*",".rspec"]
s.require_path = 'lib'
s.add_dependency "bundler"
s.requirements = ['Install the linux_admin gem and set BEXT_ACTIVATE_VERSIONS to true to activate rpm/deb installed gems']
s.add_development_dependency('rspec', '>=1.3.0')
end
| $LOAD_PATH.push File.expand_path("lib")
require 'bundler_ext/version'
Gem::Specification.new do |s|
s.name = "bundler_ext"
s.version = BundlerExt::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Jason Guiditta", "Mo Morsi", "Lukas Zapletal"]
s.email = ["mmorsi@redhat.com"]
s.homepage = "https://github.com/bundlerext/bundler_ext"
s.summary = "Load system gems via Bundler DSL"
s.description = "Simple library leveraging the Bundler Gemfile DSL to load gems already on the system and managed by the systems package manager (like yum/apt)"
s.license = 'MIT'
s.files = Dir["lib/**/*.rb", "README.md", "MIT-LICENSE","Rakefile","CHANGELOG"]
s.test_files = Dir["spec/**/*.*",".rspec"]
s.require_path = 'lib'
s.add_dependency "bundler"
s.requirements = ['Install the linux_admin gem and set BEXT_ACTIVATE_VERSIONS to true to activate rpm/deb installed gems']
s.add_development_dependency('rspec', '>=1.3.0')
s.add_development_dependency('rake', '>= 12', '< 14')
end
|
Make clean folder recursive so that it clears an entire tree of files | class Cleaner
def self.clean_folder path
Dir.glob(path + "/**").sort.each do |file|
if File.file?(file)
self.rename_file file, path
else
puts file + " is a folder"
end
end
"Cleaned files in folder: " + path
end
def self.rename_file file, path
filename = self.clean_file_name file
filename = path + "/" + filename
File.rename file, filename
end
def self.clean_file_name file
extension = File.extname file
base_name = File.basename file, extension
base_name = self.clean_string base_name
base_name + extension
end
def self.clean_string string = ""
string.gsub /[^\w,\-]/, "_"
end
end | class Cleaner
def self.clean_folder path
Dir.glob(path + "/**").sort.each do |file|
if File.file?(file)
self.rename_file file, path
else
puts file + " is a folder"
self.clean_folder file
end
end
"Cleaned files in folder: " + path
end
def self.rename_file file, path
filename = self.clean_file_name file
filename = path + "/" + filename
File.rename file, filename
end
def self.clean_file_name file
extension = File.extname file
base_name = File.basename file, extension
base_name = self.clean_string base_name
base_name + extension
end
def self.clean_string string = ""
string.gsub /[^\w,\-]/, "_"
end
end |
Update bundler requirement from ~> 1.5 to ~> 2.2 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'hashtel/version'
Gem::Specification.new do |spec|
spec.name = "hashtel"
spec.version = Hashtel::VERSION
spec.authors = ["Jurre Stender"]
spec.email = ["jurrestender+github@gmail.com"]
spec.summary = %q{Consistently convert strings to the same (pretty) color}
spec.license = "MIT"
spec.files = `git ls-files`.split("\n")
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rspec"
spec.add_development_dependency "rake"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'hashtel/version'
Gem::Specification.new do |spec|
spec.name = "hashtel"
spec.version = Hashtel::VERSION
spec.authors = ["Jurre Stender"]
spec.email = ["jurrestender+github@gmail.com"]
spec.summary = %q{Consistently convert strings to the same (pretty) color}
spec.license = "MIT"
spec.files = `git ls-files`.split("\n")
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 2.2"
spec.add_development_dependency "rspec"
spec.add_development_dependency "rake"
end
|
Update byebug to latest and greatest | $:.push File.expand_path('../lib', __FILE__)
require 'icepick/version'
Gem::Specification.new do |gem|
gem.name = 'icepick'
gem.version = Icepick::VERSION
gem.authors = ['doomspork']
gem.email = 'seancallan@gmail.com'
gem.license = 'MIT'
gem.homepage = 'https://github.com/doomspork/icepick'
gem.summary = 'Pry bundled with plugins and helpful configurations.'
gem.description = gem.summary
gem.executables = ['icepick']
gem.files = `git ls-files`.split("\n")
gem.require_paths = ['lib']
# Dependencies
gem.required_ruby_version = '>= 2.0.0'
gem.add_runtime_dependency 'awesome_print', '~> 1.2'
gem.add_runtime_dependency 'colorize', '~> 0.7'
gem.add_runtime_dependency 'pry', '~> 0.10'
gem.add_runtime_dependency 'pry-byebug', '~> 2.0'
gem.add_runtime_dependency 'pry-doc', '~> 0.6'
gem.add_runtime_dependency 'pry-docmore', '~> 0.1'
gem.add_runtime_dependency 'pry-rescue', '~> 1.4'
gem.add_runtime_dependency 'pry-stack_explorer', '~> 0.4'
end
| $:.push File.expand_path('../lib', __FILE__)
require 'icepick/version'
Gem::Specification.new do |gem|
gem.name = 'icepick'
gem.version = Icepick::VERSION
gem.authors = ['doomspork']
gem.email = 'seancallan@gmail.com'
gem.license = 'MIT'
gem.homepage = 'https://github.com/doomspork/icepick'
gem.summary = 'Pry bundled with plugins and helpful configurations.'
gem.description = gem.summary
gem.executables = ['icepick']
gem.files = `git ls-files`.split("\n")
gem.require_paths = ['lib']
# Dependencies
gem.required_ruby_version = '>= 2.0.0'
gem.add_runtime_dependency 'awesome_print', '~> 1.2'
gem.add_runtime_dependency 'colorize', '~> 0.7'
gem.add_runtime_dependency 'pry', '~> 0.10'
gem.add_runtime_dependency 'pry-byebug', '~> 3.1.0'
gem.add_runtime_dependency 'pry-doc', '~> 0.6'
gem.add_runtime_dependency 'pry-docmore', '~> 0.1'
gem.add_runtime_dependency 'pry-rescue', '~> 1.4'
gem.add_runtime_dependency 'pry-stack_explorer', '~> 0.4'
end
|
Use caller filename by default | require 'rblineprof'
require 'rack/lineprof/source_extension'
class Lineprof
IGNORE_PATTERN = /lib\/lineprof\.rb$/
class << self
def profile(&block)
value = nil
result = lineprof(/./) { value = block.call }
puts Term::ANSIColor.blue("\n[Lineprof] #{'=' * 70}")
puts "\n#{format(result)}\n"
value
end
private
def format(result)
sources = result.map do |filename, samples|
next if filename =~ IGNORE_PATTERN
Rack::Lineprof::Source.new(filename, samples)
end
sources.compact.map(&:format).join("\n")
end
end
end
| require 'rblineprof'
require 'rack/lineprof/source_extension'
class Lineprof
IGNORE_PATTERN = /lib\/lineprof\.rb$/
DEFAULT_PATTERN = /./
class << self
def profile(filename = caller_filename(caller), &block)
value = nil
result = lineprof(filename) { value = block.call }
puts Term::ANSIColor.blue("\n[Lineprof] #{'=' * 70}")
puts "\n#{format(result)}\n"
value
end
private
def caller_filename(caller_lines)
caller_lines.first.split(':').first || DEFAULT_PATTERN
end
def format(result)
sources = result.map do |filename, samples|
next if filename =~ IGNORE_PATTERN
Rack::Lineprof::Source.new(filename, samples)
end
sources.compact.map(&:format).join("\n")
end
end
end
|
Add MongoHub.app latest current version 3.1.4 | cask :v1 => 'mongohub' do
version :latest
sha256 :no_check
url 'https://mongohub.s3.amazonaws.com/MongoHub.zip'
name 'MongoHub'
homepage 'https://github.com/jeromelebel/MongoHub-Mac'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'MongoHub.app'
end
| |
Test options for location_only and timezone_only | require 'test_helper'
class LocotimezoneTest < Minitest::Test
attr_reader :loco
def test_that_it_has_a_version_number
refute_nil ::Locotimezone::VERSION
end
def setup
@loco = Locotimezone.locotime address
end
def test_that_it_has_correct_formatted_address
assert_equal '525 NW 1st Ave, Fort Lauderdale, FL 33301, USA',
loco[:formatted_address]
end
def test_that_it_has_correct_geolocation
assert_equal 26.1288238, loco[:location]['lat']
assert_equal -80.1449743, loco[:location]['lng']
end
def test_that_it_has_correct_timezone_id
assert_equal 'America/New_York', loco[:timezone]['timeZoneId']
end
end
| require 'test_helper'
class LocotimezoneTest < Minitest::Test
attr_reader :locotime
attr_reader :just_location
attr_reader :just_timezone
def setup
@locotime = Locotimezone.locotime address
@just_location = Locotimezone.locotime address, loction_only: true
@just_timezone = Locotimezone.locotime address, timezone_only: true
end
def test_that_it_has_a_version_number
refute_nil ::Locotimezone::VERSION
end
def test_that_it_has_correct_formatted_address
assert_equal '525 NW 1st Ave, Fort Lauderdale, FL 33301, USA',
locotime[:formatted_address]
end
def test_that_it_has_correct_geolocation
assert_equal 26.1288238, locotime[:location]['lat']
assert_equal -80.1449743, locotime[:location]['lng']
end
def test_that_it_has_correct_timezone_id
assert_equal 'America/New_York', locotime[:timezone]['timeZoneId']
end
def test_that_it_only_returns_location
refute_nil just_location[:location]
assert_nil just_location[:timezone]
end
def test_that_it_only_returns_timezone
assert_nil just_location[:location]
refute_nil just_location[:timezone]
end
end
|
Add user id to search terms | migration 7, :add_user_id_to_search_terms do
up do
execute 'DROP INDEX searchable_messages_tsv'
execute 'DROP MATERIALIZED VIEW searchable_messages;'
execute <<~SQL
CREATE MATERIALIZED VIEW searchable_messages AS
SELECT
messages.*,
channels.name AS channel_name,
users.image AS user_image,
users.real_name AS user_real_name,
users.name AS user_name,
to_tsvector(messages.text || ' ' || channels.name || ' ' || users.id || ' ' || users.real_name || ' ' || users.name) AS tsv
FROM messages
INNER JOIN users ON messages.user_id = users.id
INNER JOIN channels ON messages.channel_id = channels.id
WITH NO DATA;
SQL
execute 'CREATE INDEX searchable_messages_tsv ON searchable_messages USING gin(tsv)'
end
down do
execute 'DROP INDEX searchable_messages_tsv'
execute 'DROP MATERIALIZED VIEW searchable_messages;'
execute <<~SQL
CREATE MATERIALIZED VIEW searchable_messages AS
SELECT
messages.*,
channels.name AS channel_name,
users.image AS user_image,
users.real_name AS user_real_name,
users.name AS user_name,
to_tsvector(messages.text || ' ' || channels.name || ' ' || users.real_name || ' ' || users.name) AS tsv
FROM messages
INNER JOIN users ON messages.user_id = users.id
INNER JOIN channels ON messages.channel_id = channels.id
WITH NO DATA;
SQL
end
end
| |
Add chef-spec for restore recipe | require_relative '../spec_helper'
describe 'backup_restore::restore' do
let(:chef_run) do
runner = ChefSpec::Runner.new(
cookbook_path: %w(site-cookbooks cookbooks),
platform: 'centos',
version: '6.5'
)do |node|
node.set['backup_restore']['destinations']['enabled'] = %w(s3)
node.set['backup_restore']['destinations']['s3'] = {
bucket: 's3bucket',
access_key_id: 'access_key_id',
secret_access_key: 'secret_access_key',
region: 'us-east-1',
prefix: '/backup'
}
node.set['backup_restore']['restore']['target_sources'] = %w(directory mysql ruby)
end
runner.converge(described_recipe)
end
it 'create temporary directory' do
expect(chef_run).to create_directory('/tmp/backup/restore').with(
recursive: true
)
end
it 'run directory backup' do
expect(chef_run).to include_recipe('backup_restore::fetch_s3')
end
it 'run directory backup' do
expect(chef_run).to include_recipe('backup_restore::restore_directory')
end
it 'run directory backup' do
expect(chef_run).to include_recipe('backup_restore::restore_mysql')
end
it 'run directory backup' do
expect(chef_run).to include_recipe('backup_restore::restore_ruby')
end
it 'delete temporary directory' do
expect(chef_run).to delete_directory('/tmp/backup/restore').with(
recursive: true
)
end
end
| |
Fix url generation by meeting proposal model | class MeetingProposal < ActiveRecord::Base
self.table_name = 'meetings_proposals'
belongs_to :meeting, counter_cache: :proposals_count
belongs_to :proposal
delegate :title, to: :proposal
end
| class MeetingProposal < ActiveRecord::Base
self.table_name = 'meetings_proposals'
belongs_to :meeting, counter_cache: :proposals_count
belongs_to :proposal
delegate :title, :participatory_process, to: :proposal
end
|
Add partial coverage for Handler. | require "spec_helper"
describe Lita::Handler do
let(:robot) do
robot = double("Robot")
allow(robot).to receive(:name).and_return("Lita")
robot
end
describe "#command?" do
it "is true when the message is addressed to the Robot" do
subject = described_class.new(robot, "#{robot.name}: hello")
expect(subject).to be_a_command
end
it "is false when the message is not addressed to the Robot" do
subject = described_class.new(robot, "hello")
expect(subject).not_to be_a_command
end
end
end
| |
Remove unnecessary `includes` in the home | class StaticPagesController < ApplicationController
before_action :logged_in_user, only: :donation
def home
@song = Song.includes(playings: :user).pickup
@lives = Live.includes(:songs).published.order_by_date.limit(5)
end
def donate; end
end
| class StaticPagesController < ApplicationController
before_action :logged_in_user, only: :donation
def home
@song = Song.includes(playings: :user).pickup
@lives = Live.published.order_by_date.limit(5)
end
def donate; end
end
|
Add recipient_id and is_new to comment serializer | class TaskCommentSerializer < ActiveModel::Serializer
attributes :id, :comment, :created_at, :comment_by
def comment_by
object.user.name
end
end
| class TaskCommentSerializer < ActiveModel::Serializer
attributes :id, :comment, :created_at, :comment_by, :recipient_id, :is_new
def comment_by
object.user.name
end
end
|
Add bearer_token for publishing API authentication | require 'gds_api/publishing_api_v2'
module Services
def self.publishing_api
@publishing_api ||= GdsApi::PublishingApiV2.new(Plek.new.find('publishing-api'))
end
end
| require 'gds_api/publishing_api_v2'
module Services
def self.publishing_api
@publishing_api ||= GdsApi::PublishingApiV2.new(
Plek.new.find('publishing-api'),
bearer_token: ENV['PUBLISHING_API_BEARER_TOKEN'] || 'example'
)
end
end
|
Fix connectable? due to a new error type in Rails 6.1 | module ActiveRecord
class Base
include Vmdb::Logging
# Truncates the table.
#
# ==== Example
#
# Post.truncate
def self.truncate
connection.truncate(table_name, "#{name} Truncate")
end
def self.reindex
_log.info("Reindexing table #{reindex_table_name}")
result = connection.reindex_table(reindex_table_name)
_log.info("Completed Reindexing of table #{reindex_table_name} with result #{result.result_status}")
end
def self.reindex_table_name
table_name
end
def self.vacuum
_log.info("Vacuuming table #{table_name}")
result = connection.vacuum_analyze_table(table_name)
_log.info("Completed Vacuuming of table #{table_name} with result #{result.result_status}")
end
def self.connectable?
connection && connected?
rescue ActiveRecord::NoDatabaseError, PG::ConnectionBad
false
end
end
end
| module ActiveRecord
class Base
include Vmdb::Logging
# Truncates the table.
#
# ==== Example
#
# Post.truncate
def self.truncate
connection.truncate(table_name, "#{name} Truncate")
end
def self.reindex
_log.info("Reindexing table #{reindex_table_name}")
result = connection.reindex_table(reindex_table_name)
_log.info("Completed Reindexing of table #{reindex_table_name} with result #{result.result_status}")
end
def self.reindex_table_name
table_name
end
def self.vacuum
_log.info("Vacuuming table #{table_name}")
result = connection.vacuum_analyze_table(table_name)
_log.info("Completed Vacuuming of table #{table_name} with result #{result.result_status}")
end
def self.connectable?
connection && connected?
rescue ActiveRecord::ConnectionNotEstablished, ActiveRecord::NoDatabaseError, PG::ConnectionBad
false
end
end
end
|
Add missing docs for debug | # -*- encoding: utf-8 -*-
# frozen_string_literal: true
#
# Copyright (c) 2016 Mark Lee and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute,
# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
# OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module Thermite
#
# Utility methods
#
module Util
def debug(msg)
# Should probably replace with a Logger
if config.debug_filename
@debug ||= File.open(config.debug_filename, 'w')
@debug.write("#{msg}\n")
end
end
end
end
| # -*- encoding: utf-8 -*-
# frozen_string_literal: true
#
# Copyright (c) 2016 Mark Lee and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute,
# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
# OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module Thermite
#
# Utility methods
#
module Util
#
# Logs a debug message to the specified `config.debug_filename`, if set.
#
def debug(msg)
# Should probably replace with a Logger
if config.debug_filename
@debug ||= File.open(config.debug_filename, 'w')
@debug.write("#{msg}\n")
end
end
end
end
|
Add source and issues URLs | name 's3_dir'
maintainer 'EverTrue, Inc.'
maintainer_email 'devops@evertrue.com'
license 'Apache v2.0'
description 'Installs/Configures s3_dir'
long_description 'Installs/Configures s3_dir'
version '1.4.1'
supports 'ubuntu', '= 14.04'
depends 's3_file', '>= 2.5.0'
depends 'et_fog', '~> 1.0'
| name 's3_dir'
maintainer 'EverTrue, Inc.'
maintainer_email 'devops@evertrue.com'
license 'Apache v2.0'
description 'Installs/Configures s3_dir'
long_description 'Installs/Configures s3_dir'
version '1.4.1'
source_url 'https://github.com/evertrue/s3_dir/' if respond_to?(:source_url)
issues_url 'https://github.com/evertrue/s3_dir/issues' if respond_to?(:issues_url)
supports 'ubuntu', '= 14.04'
depends 's3_file', '>= 2.5.0'
depends 'et_fog', '~> 1.0'
|
Test tagging polymorphism on a payment method | require "spec_helper"
# An inheritance bug made these specs fail.
# See config/initializers/spree.rb
shared_examples "taggable" do |parameter|
it "uses the given parameter" do
expect(subject.tag_list).to eq []
end
end
module Spree
describe PaymentMethod do
it_behaves_like "taggable"
end
describe Gateway do
it_behaves_like "taggable"
end
describe Gateway::PayPalExpress do
it_behaves_like "taggable"
end
describe Gateway::StripeConnect do
it_behaves_like "taggable"
end
end
| require "spec_helper"
# We extended Spree::PaymentMethod to be taggable. Unfortunately, an inheritance
# bug prevented the taggable code to be passed on to the descendants of
# PaymentMethod. We fixed that in config/initializers/spree.rb.
#
# This spec tests several descendants for their taggability. The tests are in
# a separate file, because they cover one aspect of several classes.
shared_examples "taggable" do |expected_taggable_type|
it "provides a tag list" do
expect(subject.tag_list).to eq []
end
it "stores tags for the root taggable type" do
subject.tag_list.add("one")
subject.save!
expect(subject.taggings.last.taggable_type).to eq expected_taggable_type
end
end
module Spree
describe "PaymentMethod and descendants" do
let(:shop) { create(:enterprise) }
let(:valid_subject) do
# Supply required parameters so that it can be saved to attach taggings.
described_class.new(
name: "Some payment method",
distributor_ids: [shop.id]
)
end
subject { valid_subject }
describe PaymentMethod do
it_behaves_like "taggable", "Spree::PaymentMethod"
end
describe Gateway do
it_behaves_like "taggable", "Spree::PaymentMethod"
end
describe Gateway::PayPalExpress do
it_behaves_like "taggable", "Spree::PaymentMethod"
end
describe Gateway::StripeConnect do
subject do
# StripeConnect needs an owner to be valid.
valid_subject.tap { |m| m.preferred_enterprise_id = shop.id }
end
it_behaves_like "taggable", "Spree::PaymentMethod"
end
end
end
|
Add new validator for all elements of an array | # frozen_string_literal: true
class ArrayValidator < ActiveModel::EachValidator
# Taken from https://gist.github.com/justalever/73a1b36df8468ec101f54381996fb9d1
def validate_each(record, attribute, values)
Array(values).each do |value|
options.each do |key, args|
validator_options = {attributes: attribute}
validator_options.merge!(args) if args.is_a?(Hash)
next if value.nil? && validator_options[:allow_nil]
next if value.blank? && validator_options[:allow_blank]
validator_class_name = "#{key.to_s.camelize}Validator"
validator_class = begin
validator_class_name.constantize
rescue NameError
"ActiveModel::Validations::#{validator_class_name}".constantize
end
validator = validator_class.new(validator_options)
validator.validate_each(record, attribute, value)
end
end
end
end
| |
Add context to practice specs | require 'spec_helper'
module Comptroller
describe Practice do
it 'retrieves all pratices' do
expect(Practice.all.first).to eql(Practice.new(:export_url => 'https://optimis.duxware.com', :token => '12345', :external_id => 3))
end
it 'creates new practices' do
practice = Practice.create(:external_id => 5, :export_url => 'http://hello.world', :token => '12345')
expect(practice).to eql(Practice.new(:external_id => 5, :export_url => 'http://hello.world', :token => '12345'))
end
it 'retrieves practice by id' do
practice = Practice.find(1)
expect(practice).to eql(Practice.new(:external_id => 3, :export_url => 'https://optimis.duxware.com', :token => '12345'))
end
it 'updates practices' do
expect(Practice.save_existing(1, :export_url => 'https://optimis.webpt.com')).to be_true
expect(Practice.find(1).export_url).to eql('https://optimis.webpt.com')
end
it 'deletes practices' do
Practice.destroy_existing(1)
practice_ids = Practice.all.map(&:id)
expect(practice_ids.include?(1)).to be_false
end
end
end
| require 'spec_helper'
module Comptroller
describe Practice do
context 'crud api' do
it 'retrieves all pratices' do
expect(Practice.all.first).to eql(Practice.new(:export_url => 'https://optimis.duxware.com', :token => '12345', :external_id => 3))
end
it 'creates new practices' do
practice = Practice.create(:external_id => 5, :export_url => 'http://hello.world', :token => '12345')
expect(practice).to eql(Practice.new(:external_id => 5, :export_url => 'http://hello.world', :token => '12345'))
end
it 'retrieves practice by id' do
practice = Practice.find(1)
expect(practice).to eql(Practice.new(:external_id => 3, :export_url => 'https://optimis.duxware.com', :token => '12345'))
end
it 'updates practices' do
expect(Practice.save_existing(1, :export_url => 'https://optimis.webpt.com')).to be_true
expect(Practice.find(1).export_url).to eql('https://optimis.webpt.com')
end
it 'deletes practices' do
Practice.destroy_existing(1)
practice_ids = Practice.all.map(&:id)
expect(practice_ids.include?(1)).to be_false
end
end
end
end
|
Update dependency on GirFFI and other gems | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "gir_ffi-gtk"
s.version = "0.6.0"
s.summary = "GirFFI-based Ruby bindings for Gtk+ 2 and 3"
s.authors = ["Matijs van Zuijlen"]
s.email = ["matijs@matijs.net"]
s.homepage = "http://www.github.com/mvz/gir_ffi-gtk"
s.files = Dir['{lib,test,tasks,examples}/**/*', "*.md", "Rakefile", "COPYING.LIB"] & `git ls-files -z`.split("\0")
s.test_files = `git ls-files -z -- test`.split("\0")
s.add_runtime_dependency('gir_ffi', ["~> 0.6.0"])
s.add_development_dependency('minitest', ["~> 5.0"])
s.add_development_dependency('rr', ["~> 1.0.4"])
s.add_development_dependency('rake', ["~> 10.0.3"])
s.require_paths = ["lib"]
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "gir_ffi-gtk"
s.version = "0.6.0"
s.summary = "GirFFI-based Ruby bindings for Gtk+ 2 and 3"
s.authors = ["Matijs van Zuijlen"]
s.email = ["matijs@matijs.net"]
s.homepage = "http://www.github.com/mvz/gir_ffi-gtk"
s.files = Dir['{lib,test,tasks,examples}/**/*', "*.md", "Rakefile", "COPYING.LIB"] & `git ls-files -z`.split("\0")
s.test_files = `git ls-files -z -- test`.split("\0")
s.add_runtime_dependency('gir_ffi', ["~> 0.7.0"])
s.add_development_dependency('minitest', ["~> 5.0"])
s.add_development_dependency('rr', ["~> 1.1.2"])
s.add_development_dependency('rake', ["~> 10.1"])
s.require_paths = ["lib"]
end
|
Bump dependency for data_objects to 0.9.12 and extlib to 0.9.11 | require Pathname(__FILE__).dirname.expand_path / 'data_objects_adapter'
gem 'do_mysql', '~>0.9.11'
require 'do_mysql'
module DataMapper
module Adapters
# Options:
# host, user, password, database (path), socket(uri query string), port
class MysqlAdapter < DataObjectsAdapter
module SQL
private
def supports_default_values?
false
end
# TODO: once the driver's quoting methods become public, have
# this method delegate to them instead
def quote_name(name)
escaped = name.gsub('`', '``')
if escaped.include?('.')
escaped.split('.').map { |part| "`#{part}`" }.join('.')
else
"`#{escaped}`"
end
end
# TODO: once the driver's quoting methods become public, have
# this method delegate to them instead
def quote_value(value)
case value
when TrueClass then super(1)
when FalseClass then super(0)
else
super
end
end
def like_operator(operand)
operand.kind_of?(Regexp) ? 'REGEXP' : 'LIKE'
end
end #module SQL
include SQL
end # class MysqlAdapter
const_added(:MysqlAdapter)
end # module Adapters
end # module DataMapper
| require Pathname(__FILE__).dirname.expand_path / 'data_objects_adapter'
gem 'do_mysql', '~>0.9.12'
require 'do_mysql'
module DataMapper
module Adapters
# Options:
# host, user, password, database (path), socket(uri query string), port
class MysqlAdapter < DataObjectsAdapter
module SQL
private
def supports_default_values?
false
end
# TODO: once the driver's quoting methods become public, have
# this method delegate to them instead
def quote_name(name)
escaped = name.gsub('`', '``')
if escaped.include?('.')
escaped.split('.').map { |part| "`#{part}`" }.join('.')
else
"`#{escaped}`"
end
end
# TODO: once the driver's quoting methods become public, have
# this method delegate to them instead
def quote_value(value)
case value
when TrueClass then super(1)
when FalseClass then super(0)
else
super
end
end
def like_operator(operand)
operand.kind_of?(Regexp) ? 'REGEXP' : 'LIKE'
end
end #module SQL
include SQL
end # class MysqlAdapter
const_added(:MysqlAdapter)
end # module Adapters
end # module DataMapper
|
Use stubbing here to ensure we trace the config block codepath | require 'test_helper'
describe PrxAuth::Rails::Configuration do
subject { PrxAuth::Rails::Configuration.new }
it 'initializes with a namespace defined by rails app name' do
assert subject.namespace == :dummy
end
it 'can be reconfigured using the namespace attr' do
subject.namespace = :new_test
assert subject.namespace == :new_test
end
it 'defaults to enabling the middleware' do
assert subject.install_middleware
end
it 'allows overriding of the middleware automatic installation' do
subject.install_middleware = false
assert subject.install_middleware == false
end
end
| require 'test_helper'
describe PrxAuth::Rails::Configuration do
subject { PrxAuth::Rails::Configuration.new }
it 'initializes with a namespace defined by rails app name' do
assert subject.namespace == :dummy
end
it 'can be reconfigured using the namespace attr' do
PrxAuth::Rails.stub(:configuration, subject) do
PrxAuth::Rails.configure do |config|
config.namespace = :new_test
end
assert PrxAuth::Rails.configuration.namespace == :new_test
end
end
it 'defaults to enabling the middleware' do
PrxAuth::Rails.stub(:configuration, subject) do
assert PrxAuth::Rails.configuration.install_middleware
end
end
it 'allows overriding of the middleware automatic installation' do
PrxAuth::Rails.stub(:configuration, subject) do
PrxAuth::Rails.configure do |config|
config.install_middleware = false
end
assert !PrxAuth::Rails.configuration.install_middleware
end
end
end
|
Move installdir to /opt/zookeeper and make snapshotdir inside of whatever datadir is | default[:zookeeper][:version] = "3.3.4"
default[:zookeeper][:installDir] = "/usr/local/share/zookeeper"
default[:zookeeper][:logDir] = '/var/log/zookeeper'
default[:zookeeper][:dataDir] = "/var/zookeeper"
default[:zookeeper][:snapshotDir] = "/var/lib/zookeeper/snapshots"
default[:zookeeper][:tickTime] = 2000
default[:zookeeper][:initLimit] = 10
default[:zookeeper][:syncLimit] = 5
default[:zookeeper][:clientPort] = 2181
default[:zookeeper][:snapshotNum] = 3
default[:zookeeper][:quorum] = ["localhost"] | default[:zookeeper][:version] = "3.3.4"
default[:zookeeper][:installDir] = "/opt/zookeeper"
default[:zookeeper][:logDir] = '/var/log/zookeeper'
default[:zookeeper][:dataDir] = "/var/zookeeper"
default[:zookeeper][:snapshotDir] = "#{default[:zookeeper][:dataDir]}/snapshots"
default[:zookeeper][:tickTime] = 2000
default[:zookeeper][:initLimit] = 10
default[:zookeeper][:syncLimit] = 5
default[:zookeeper][:clientPort] = 2181
default[:zookeeper][:snapshotNum] = 3
default[:zookeeper][:quorum] = ["localhost"] |
Add required ruby version to gemspec | Gem::Specification.new do |gem|
gem.name = 'sharepoint'
gem.version = '0.1.0'
gem.authors = [ 'Antonio Delfin' ]
gem.email = [ 'a.delfin@ifad.org' ]
gem.description = %q(Ruby client to consume Sharepoint services)
gem.summary = %q(Ruby client to consume Sharepoint services)
gem.homepage = "https://github.com/ifad/sharepoint"
gem.files = `git ls-files`.split("\n")
gem.require_paths = ["lib"]
gem.add_dependency 'ethon'
gem.add_dependency 'activesupport', '>= 4.0'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rspec'
gem.add_development_dependency 'dotenv'
gem.add_development_dependency 'webmock'
gem.add_development_dependency 'byebug'
gem.add_development_dependency 'ruby-filemagic'
end
| Gem::Specification.new do |gem|
gem.name = 'sharepoint'
gem.version = '0.1.0'
gem.authors = [ 'Antonio Delfin' ]
gem.email = [ 'a.delfin@ifad.org' ]
gem.description = %q(Ruby client to consume Sharepoint services)
gem.summary = %q(Ruby client to consume Sharepoint services)
gem.homepage = "https://github.com/ifad/sharepoint"
gem.files = `git ls-files`.split("\n")
gem.require_paths = ["lib"]
gem.required_ruby_version = '>= 2.3'
gem.add_dependency 'ethon'
gem.add_dependency 'activesupport', '>= 4.0'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rspec'
gem.add_development_dependency 'dotenv'
gem.add_development_dependency 'webmock'
gem.add_development_dependency 'byebug'
gem.add_development_dependency 'ruby-filemagic'
end
|
Add printer configuration for Evaluator::Transformer::Guard | module Morpher
class Evaluator
class Transformer
# Transformer that allows to guard transformation process with a predicate on input
class Guard < self
include Concord.new(:predicate), Transitive
register :guard
# Call evaluator
#
# @parma [Object] input
#
# @return [Object]
# if input evaluates true under predicate
#
# @raise [TransformError]
# otherwise
#
# @api private
#
def call(input)
if predicate.call(input)
input
else
raise TransformError.new(self, input)
end
end
# Return evaluation
#
# @param [Object] input
#
# @return [Evaluation::Guard]
#
# @api private
#
def evaluation(input)
Evaluation::Guard.new(
input: input,
output: input,
evaluator: self,
predicate: predicate.call(input)
)
end
# Return inverse evaluator
#
# @return [self]
#
# @api private
#
def inverse
self
end
# Build evaluator from node
#
# @param [Compiler] compiler
# @param [Node] node
#
# @api private
#
# @return [Evaluator ]
#
def self.build(compiler, node)
new(compiler.call(node.children.first))
end
end # Guard
end # Transformer
end # Evaluator
end # Morpher
| module Morpher
class Evaluator
class Transformer
# Transformer that allows to guard transformation process with a predicate on input
class Guard < self
include Concord::Public.new(:predicate), Transitive
register :guard
printer do
name
visit(:predicate)
end
# Call evaluator
#
# @parma [Object] input
#
# @return [Object]
# if input evaluates true under predicate
#
# @raise [TransformError]
# otherwise
#
# @api private
#
def call(input)
if predicate.call(input)
input
else
raise TransformError.new(self, input)
end
end
# Return evaluation
#
# @param [Object] input
#
# @return [Evaluation::Guard]
#
# @api private
#
def evaluation(input)
Evaluation::Guard.new(
input: input,
output: input,
evaluator: self,
predicate: predicate.call(input)
)
end
# Return inverse evaluator
#
# @return [self]
#
# @api private
#
def inverse
self
end
# Build evaluator from node
#
# @param [Compiler] compiler
# @param [Node] node
#
# @api private
#
# @return [Evaluator ]
#
def self.build(compiler, node)
new(compiler.call(node.children.first))
end
end # Guard
end # Transformer
end # Evaluator
end # Morpher
|
Use COALESCE in case there are no posts in a topic | class MigrateWordCounts < ActiveRecord::Migration
def up
disable_ddl_transaction
post_ids = execute("SELECT id FROM posts WHERE word_count IS NULL LIMIT 500").map {|r| r['id'].to_i }
while post_ids.length > 0
execute "UPDATE posts SET word_count = array_length(regexp_split_to_array(raw, ' '),1) WHERE id IN (#{post_ids.join(',')})"
post_ids = execute("SELECT id FROM posts WHERE word_count IS NULL LIMIT 500").map {|r| r['id'].to_i }
end
topic_ids = execute("SELECT id FROM topics WHERE word_count IS NULL LIMIT 500").map {|r| r['id'].to_i }
while topic_ids.length > 0
execute "UPDATE topics SET word_count = (SELECT SUM(COALESCE(posts.word_count, 0)) FROM posts WHERE posts.topic_id = topics.id) WHERE topics.id IN (#{topic_ids.join(',')})"
topic_ids = execute("SELECT id FROM topics WHERE word_count IS NULL LIMIT 500").map {|r| r['id'].to_i }
end
end
end
| class MigrateWordCounts < ActiveRecord::Migration
def up
disable_ddl_transaction
post_ids = execute("SELECT id FROM posts WHERE word_count IS NULL LIMIT 500").map {|r| r['id'].to_i }
while post_ids.length > 0
execute "UPDATE posts SET word_count = COALESCE(array_length(regexp_split_to_array(raw, ' '),1), 0) WHERE id IN (#{post_ids.join(',')})"
post_ids = execute("SELECT id FROM posts WHERE word_count IS NULL LIMIT 500").map {|r| r['id'].to_i }
end
topic_ids = execute("SELECT id FROM topics WHERE word_count IS NULL LIMIT 500").map {|r| r['id'].to_i }
while topic_ids.length > 0
execute "UPDATE topics SET word_count = COALESCE((SELECT SUM(COALESCE(posts.word_count, 0)) FROM posts WHERE posts.topic_id = topics.id), 0) WHERE topics.id IN (#{topic_ids.join(',')})"
topic_ids = execute("SELECT id FROM topics WHERE word_count IS NULL LIMIT 500").map {|r| r['id'].to_i }
end
end
end
|
Include base command helper to pass tests | require 'spec_helper'
include Serverspec::Helper::Attributes
describe 'Attributes Helper' do
before :all do
attr_set :role => 'proxy'
end
subject { attr }
it { should include :role => 'proxy' }
end
| require 'spec_helper'
require 'serverspec/helper/base'
include Serverspec::Helper::Base
include Serverspec::Helper::Attributes
describe 'Attributes Helper' do
before :all do
attr_set :role => 'proxy'
end
subject { attr }
it { should include :role => 'proxy' }
end
|
Set mate, getter returns String of mate. | describe USI::Resource::Score do
describe '#cp' do
let(:score) { USI::Resource::Score.new(args) }
context '`cp` is included' do
let(:args) { ["cp", "-1521"] }
it "returns the cp(centi pawn) value on Fixnum" do
expect(score.cp).to eq -1521
end
end
context '`cp` is not included' do
let(:args) { ["mate", "+"] }
it do
expect(score.cp).to be nil
end
end
context '`lowerbound` or `upperbound` is included' do
let(:args) { ["cp", "-9999", "lowerbound"] }
it "returns the cp(centi pawn) value on Fixnum" do
expect(score.cp).to eq -9999
end
end
end
end
| describe USI::Resource::Score do
describe '#cp' do
let(:score) { USI::Resource::Score.new(args) }
context '`cp` is included' do
let(:args) { ["cp", "-1521"] }
it "returns the cp(centi pawn) value on Fixnum" do
expect(score.cp).to eq -1521
end
end
context '`cp` is not included' do
let(:args) { ["mate", "+"] }
it do
expect(score.cp).to be nil
end
end
context '`lowerbound` or `upperbound` is included' do
let(:args) { ["cp", "-9999", "lowerbound"] }
it "returns the cp(centi pawn) value on Fixnum" do
expect(score.cp).to eq -9999
end
end
end
describe '#mate' do
let(:score) { USI::Resource::Score.new(args) }
context '`mate` is included' do
let(:args) { ["mate", "+"] }
it "returns the mate value" do
expect(score.mate).to eq "+"
end
end
context '`mate` is not included' do
let(:args) { ["cp", "-1521"] }
it do
expect(score.mate).to be nil
end
end
end
end
|
Handle warnings from changing ARGV | # coding: utf-8
require File.dirname(__FILE__) + "/spec_helper"
require "tempfile"
describe CLI do
it "should fail on an invalid subcommand" do
ARGV = ["invalid"]
lambda { CLI.start }.should raise_error InvalidCommandError
end
describe "temporary files" do
before :each do
# Create dictionary
@dictionary = Tempfile.new(["dict", ".yml"])
@dictionary.write <<-eos
-
en: dogs
ja: 犬
eos
@dictionary.rewind
# Create English text to translate
@english = Tempfile.new(["english", "_en.txt"])
@english.write "I like dogs."
@english.rewind
end
it "should correctly translate English text" do
begin
ARGV = ["translate", @english.path, "into", "japanese", "using", @dictionary.path]
CLI.start
converted_path = Utils.build_converted_file_name(@english.path, "en", "ja")
puts File.read(@english.path).should == "I like dogs."
File.read(converted_path).should == "I like 犬.\n"
ensure
@dictionary.close!
@english.close!
File.delete converted_path
end
end
end
end
| # coding: utf-8
require File.dirname(__FILE__) + "/spec_helper"
require "tempfile"
describe CLI do
# Super hacky way of setting a constant without setting off a warnings that the
# constant has already been initialized
def set_argv(*params)
Object.__send__ :remove_const, :ARGV
Object.const_set :ARGV, params
end
it "should fail on an invalid subcommand" do
set_argv "invalid"
lambda { CLI.start }.should raise_error InvalidCommandError
end
describe "temporary files" do
before :each do
# Create dictionary
@dictionary = Tempfile.new(["dict", ".yml"])
@dictionary.write <<-eos
-
en: dogs
ja: 犬
eos
@dictionary.rewind
# Create English text to translate
@english = Tempfile.new(["english", "_en.txt"])
@english.write "I like dogs."
@english.rewind
# Set ARGV
set_argv "translate", @english.path, "into", "japanese", "using",
@dictionary.path
end
it "should correctly translate English text" do
begin
CLI.start
converted_path = Utils.build_converted_file_name(@english.path, "en", "ja")
File.read(@english.path).should == "I like dogs."
File.read(converted_path).should == "I like 犬.\n"
ensure
@dictionary.close!
@english.close!
File.delete converted_path
end
end
it "should return the name of the file to translate" do
CLI.start.should == [@english.path]
end
end
end
|
Make script accept more than one directory or file | IO.write(
"leak_summary.txt",
Dir.glob("#{ARGV[0]}/*").map do |f|
IO.readlines(f).map do |e|
s = e.strip.split
puts "Null password in #{f}! Count: #{s[0]}" if s[1].nil?
e.strip
end
end.flatten.map do |e|
s = e.split
[s[0].to_i, s[1]]
end.group_by{|e| e[1] }.map do |k, g|
[
k,
g.map{|e| e[0] }.reduce(&:+)
]
end.sort_by{|e| e[1] }.reverse.reduce("") do |str, e|
str += "#{e[1]}\t#{e[0]}\n"
end
)
| IO.write(
"leak_summary.txt",
ARGV.map do |arg|
if File.file?(arg)
arg
elsif File.directory?(arg)
Dir.glob("#{arg}/*")
else
puts "#{arg} not file or directory"
[]
end
end.flatten.map do |f|
IO.readlines(f).map do |e|
s = e.strip.split
puts "Null password in #{f}! Count: #{s[0]}" if s[1].nil?
e.strip
end
end.flatten.map do |e|
s = e.split
[s[0].to_i, s[1]]
end.group_by{|e| e[1] }.map do |k, g|
[
k,
g.map{|e| e[0] }.reduce(&:+)
]
end.sort_by{|e| e[1] }.reverse.reduce("") do |str, e|
str += "#{e[1]}\t#{e[0]}\n"
end
)
|
Refactor defaulting to support files for style and layout | module Rpub
module CompilationHelpers
def create_book
book = Book.new(layout, config)
markdown_files.each(&book.method(:<<))
book
end
def markdown_files
@markdown_files ||= Dir['*.md'].sort.map(&File.method(:read))
end
def layout
@layout ||= if File.exist?('layout.html')
'layout.html'
else
Rpub.support_file('layout.html')
end
end
def styles
@styles ||= if File.exists?('styles.css')
'styles.css'
else
Rpub.support_file('styles.css')
end
end
def config
@config_file ||= begin
raise NoConfiguration unless File.exist?('config.yml')
YAML.load_file('config.yml')
end
end
end
end
| module Rpub
module CompilationHelpers
def create_book
book = Book.new(layout, config)
markdown_files.each(&book.method(:<<))
book
end
def markdown_files
@markdown_files ||= Dir['*.md'].sort.map(&File.method(:read))
end
def layout
@layout ||= own_or_support_file('layout.html')
end
def styles
@styles ||= own_or_support_file('styles.css')
end
def config
@config_file ||= begin
raise NoConfiguration unless File.exist?('config.yml')
YAML.load_file('config.yml')
end
end
private
def own_or_support_file(filename)
if File.exists?(filename)
filename
else
Rpub.support_file(filename)
end
end
end
end
|
Remove DummyApp migration code that targets Rails < 5.2 | # frozen_string_literal: true
module DummyApp
module Migrations
extend self
# Ensure database exists
def database_exists?
ActiveRecord::Base.connection
rescue ActiveRecord::NoDatabaseError
false
else
true
end
def needs_migration?
return true if !database_exists?
if ActiveRecord::Base.connection.respond_to?(:migration_context)
# Rails >= 5.2
ActiveRecord::Base.connection.migration_context.needs_migration?
else
ActiveRecord::Migrator.needs_migration?
end
end
def auto_migrate
if needs_migration?
puts "Configuration changed. Re-running migrations"
# Disconnect to avoid "database is being accessed by other users" on postgres
ActiveRecord::Base.remove_connection
sh 'rake db:reset VERBOSE=false'
# We have a brand new database, so we must re-establish our connection
ActiveRecord::Base.establish_connection
end
end
private
def sh(cmd)
puts cmd
system cmd
end
end
end
| # frozen_string_literal: true
module DummyApp
module Migrations
extend self
# Ensure database exists
def database_exists?
ActiveRecord::Base.connection
rescue ActiveRecord::NoDatabaseError
false
else
true
end
def needs_migration?
return true if !database_exists?
ActiveRecord::Base.connection.migration_context.needs_migration?
end
def auto_migrate
if needs_migration?
puts "Configuration changed. Re-running migrations"
# Disconnect to avoid "database is being accessed by other users" on postgres
ActiveRecord::Base.remove_connection
sh 'rake db:reset VERBOSE=false'
# We have a brand new database, so we must re-establish our connection
ActiveRecord::Base.establish_connection
end
end
private
def sh(cmd)
puts cmd
system cmd
end
end
end
|
Update gemspec to avoid bundler whining about missing desc and summary | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/soft_service/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = "soft_service"
gem.version = SoftService::VERSION
gem.summary = %q{TODO: Summary}
gem.description = %q{TODO: Description}
gem.license = "MIT"
gem.authors = ["Don Morrison"]
gem.email = "don@elskwid.net"
gem.homepage = "https://github.com/elskwid/soft_service#readme"
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_development_dependency 'bundler', '~> 1.2'
gem.add_development_dependency 'minitest', '~> 5.0'
gem.add_development_dependency 'rake', '~> 10.0'
gem.add_development_dependency 'rubygems-tasks', '~> 0.2'
gem.add_development_dependency 'yard', '~> 0.8'
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/soft_service/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = "soft_service"
gem.version = SoftService::VERSION
gem.summary = %q{Mixins for service objects.}
gem.description = %q{A pattern for service object interfaces.}
gem.license = "MIT"
gem.authors = ["Don Morrison"]
gem.email = "don@elskwid.net"
gem.homepage = "https://github.com/elskwid/soft_service#readme"
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_development_dependency 'bundler', '~> 1.2'
gem.add_development_dependency 'minitest', '~> 5.0'
gem.add_development_dependency 'rake', '~> 10.0'
gem.add_development_dependency 'rubygems-tasks', '~> 0.2'
gem.add_development_dependency 'yard', '~> 0.8'
end
|
Change to latest version of Torpedo. | class Torpedo < Cask
url 'http://usetorpedo.com/downloads/mac/Torpedo-1.2.2.app.zip'
homepage 'https://usetorpedo.com'
version '1.2.2'
sha256 '72f0a027ea525755e07e43d90464aa00f1c45167b30d333272017f64e0496dcf'
link 'Torpedo.app'
end
| class Torpedo < Cask
url 'http://usetorpedo.com/app/mac/download'
homepage 'https://usetorpedo.com'
version 'latest'
no_checksum
link 'Torpedo.app'
end
|
Refactor dictionary spec to gain an understanding | require 'spec_helper'
describe Zxcvbn::Matchers::Dictionary do
let(:matcher) { described_class.new('english', dictionary) }
let(:dictionary) { Zxcvbn::Data.new.ranked_dictionaries['english'] }
it 'finds all the matches' do
matches = matcher.matches('whatisinit')
expect(matches.count).to eq(14)
expected_matches = ['wha', 'what', 'ha', 'hat', 'a', 'at', 'tis', 'i', 'is',
'sin', 'i', 'in', 'i', 'it']
expect(matches.map(&:matched_word)).to eq(expected_matches)
end
it 'matches uppercase' do
matcher = described_class.new('user_inputs', Zxcvbn::DictionaryRanker.rank_dictionary(['test','AB10CD']))
expect(matcher.matches('AB10CD')).not_to be_empty
end
end | # frozen_string_literal: true
require "spec_helper"
describe Zxcvbn::Matchers::Dictionary do
subject(:matcher) { described_class.new("Test dictionary", dictionary) }
describe "#matches" do
let(:matches) { matcher.matches(password) }
let(:matched_words) { matches.map(&:matched_word) }
context "Given a dictionary of English words" do
let(:dictionary) { Zxcvbn::Data.new.ranked_dictionaries["english"] }
let(:password) { "whatisinit" }
it "finds all the matches" do
expect(matched_words).to match_array %w[wha what ha hat a at tis i is sin i in i it]
end
end
context "Given a custom dictionary" do
let(:dictionary) { Zxcvbn::DictionaryRanker.rank_dictionary(%w[test AB10CD]) }
let(:password) { "AB10CD" }
it "matches uppercase passwords with normalised dictionary entries" do
expect(matched_words).to match_array(%w[ab10cd])
end
end
end
end
|
Add admin status default false | class CreateTeachers < ActiveRecord::Migration
def change
create_table :teachers do |t|
t.string :name
t.string :email
t.string :password_digest
t.boolean :admin
t.timestamps null: false
end
end
end
| class CreateTeachers < ActiveRecord::Migration
def change
create_table :teachers do |t|
t.string :name
t.string :email
t.string :password_digest
t.boolean :admin, default: false
t.timestamps null: false
end
end
end
|
Build a return string in parts instead of explicitly switching | module Fizzbuzz
extend self
def fb_value(n)
divisible_by_three = (n % 3).zero?
divisible_by_five = (n % 5).zero?
if divisible_by_three && divisible_by_five
"FizzBuzz"
elsif divisible_by_three
"Fizz"
elsif divisible_by_five
"Buzz"
else
n
end
end
end
| module Fizzbuzz
extend self
def fb_value(n)
divisible_by_three = (n % 3).zero?
divisible_by_five = (n % 5).zero?
s = ''
if divisible_by_three
s << "Fizz"
end
if divisible_by_five
s << "Buzz"
end
if s.length.zero?
n
else
s
end
end
end
|
Add work type definitions to generic work model | # Generated via
# `rails generate curation_concerns:work GenericWork`
class GenericWork < ActiveFedora::Base
include ::CurationConcerns::WorkBehavior
include ::CurationConcerns::BasicMetadata
include Sufia::WorkBehavior
validates :title, presence: { message: 'Your work must have a title.' }
# Custom Metadata
#
# work_type - Currently either a 'thesis' or a 'generic_work'.
property :work_type, predicate: ::RDF::URI('http://example.org/terms/work_type'), multiple: false do |index|
index.as :stored_searchable
end
# draft - Pertinent only for 'thesis' work_type.
# True if the thesis is not finalized (i.e. submitted, for whatever the
# term means for the work resource type, (dissertation, masters,
# fourth_year, class, project, etc.)).
# False if the thesis is finalized.
# False for any other work_type other than 'thesis'.
property :draft, predicate: ::RDF::URI('http://example.org/terms/draft'), multiple: false do |index|
index.as :stored_searchable
end
end
| # Generated via
# `rails generate curation_concerns:work GenericWork`
class GenericWork < ActiveFedora::Base
include ::CurationConcerns::WorkBehavior
include ::CurationConcerns::BasicMetadata
include Sufia::WorkBehavior
validates :title, presence: { message: 'Your work must have a title.' }
# work type definitions
WORK_TYPE_GENERIC = 'generic_work'.freeze
WORK_TYPE_THESIS = 'thesis'.freeze
# Custom Metadata
#
# work_type - Currently either a 'thesis' or a 'generic_work'.
property :work_type, predicate: ::RDF::URI('http://example.org/terms/work_type'), multiple: false do |index|
index.as :stored_searchable
end
# draft - Pertinent only for 'thesis' work_type.
# True if the thesis is not finalized (i.e. submitted, for whatever the
# term means for the work resource type, (dissertation, masters,
# fourth_year, class, project, etc.)).
# False if the thesis is finalized.
# False for any other work_type other than 'thesis'.
property :draft, predicate: ::RDF::URI('http://example.org/terms/draft'), multiple: false do |index|
index.as :stored_searchable
end
end
|
Set parsed results to instance variables of Statement in parse_link() | # statement.rb
module SecStatementParser
class Statement
include SecStatementFields
include Debug
attr_reader(:symbol,:urls)
@@single_mapping_fields.each do |k, v|
self.__send__(:attr_reader, k)
end
def initialize(log_level='')
init_logger(log_level)
end
def list(symbol='')
puts "Please enter symbol." or return nil if symbol.empty?
@list = StatementUrlList.get(symbol.upcase)
end
def parse_annual_report(year)
# Check year range
return nil unless year_range_is_valid(year)
# TODO: reset fields before parse
link = @urls[:annual_report]["y#{year}".to_sym]
result = SecStatementFields.parse(link)
# Set parsed results to instance variables of Statement
result.each do |k, v|
instance_variable_set("@#{k}", v)
end
return result
end
def parse_link(link)
result = SecStatementFields.parse(link)
return result
end
def parse_file(file)
return nil unless file.is_a? File
result = SecStatementFields.parse(file)
# Set parsed results to instance variables of Statement
result.each do |k, v|
instance_variable_set("@#{k}", v)
end
return result
end
end
end
| # statement.rb
module SecStatementParser
class Statement
include SecStatementFields
include Debug
attr_reader(:symbol,:urls)
@@single_mapping_fields.each do |k, v|
self.__send__(:attr_reader, k)
end
def initialize(log_level='')
init_logger(log_level)
end
def list(symbol='')
puts "Please enter symbol." or return nil if symbol.empty?
@list = StatementUrlList.get(symbol.upcase)
end
def parse_annual_report(year)
# Check year range
return nil unless year_range_is_valid(year)
# TODO: reset fields before parse
link = @urls[:annual_report]["y#{year}".to_sym]
result = SecStatementFields.parse(link)
# Set parsed results to instance variables of Statement
result.each do |k, v|
instance_variable_set("@#{k}", v)
end
return result
end
def parse_link(link)
result = SecStatementFields.parse(link)
# Set parsed results to instance variables of Statement
result.each do |k, v|
instance_variable_set("@#{k}", v)
end
return result
end
def parse_file(file)
return nil unless file.is_a? File
result = SecStatementFields.parse(file)
# Set parsed results to instance variables of Statement
result.each do |k, v|
instance_variable_set("@#{k}", v)
end
return result
end
end
end
|
Improve output readibility for featured stories. | class NprTodaysNews::CLI
def run
get_newslist
print_stories
end
def get_newslist
puts "These are today's top stories on NPR:"
NprTodaysNews::Scraper.new.scrape
end
def print_stories
get_newslist.stories.each.with_index(1) do |story, index|
puts "#{index}. #{story.title} -- #{story.teaser}"
end
end
# this is where I want to receive input from the user to loop through his/her options.
end
| class NprTodaysNews::CLI
def run
print_stories
end
def get_newslist
puts "These are today's top stories on NPR:"
puts
NprTodaysNews::Scraper.new.scrape
end
def print_stories
get_newslist.stories.each.with_index(1) do |story, index|
puts "#{index}. #{story.title}" #-- #{story.teaser}
#binding.pry
end
puts
get_user_input
end
def get_user_input
puts "Please select the story number (#1-3) or type 'exit' to quit."
input = gets.strip.to_i
if input == 1
puts "you chose the first story!"
end
#
end
end
|
Set proper error level for setnry raven | module Aws
module Xray
class DefaultErrorHandler
# @param [IO] io
def initialize(io)
@io = io
end
# @param [Exception] error
# @param [String] payload
# @param [String,nil] host
# @param [Integer,nil] port
def call(error, payload, host:, port:)
@io.puts(<<-EOS)
Failed to send a segment to #{host}:#{port}:
Segnemt:
#{payload}
Error: #{error}
#{error.backtrace.join("\n")}
EOS
end
end
# Must be configured sentry-raven gem.
class ErrorHandlerWithSentry
def call(error, payload, host:, port:)
if defined?(Raven)
::Raven.capture_exception(error)
else
$stderr.puts('ErrorHandlerWithSentry is configured but `Raven` is undefined.')
end
end
end
end
end
| module Aws
module Xray
class DefaultErrorHandler
# @param [IO] io
def initialize(io)
@io = io
end
# @param [Exception] error
# @param [String] payload
# @param [String,nil] host
# @param [Integer,nil] port
def call(error, payload, host:, port:)
@io.puts(<<-EOS)
Failed to send a segment to #{host}:#{port}:
Segnemt:
#{payload}
Error: #{error}
#{error.backtrace.join("\n")}
EOS
end
end
# Must be configured sentry-raven gem.
class ErrorHandlerWithSentry
ERROR_LEVEL = 'warning'.freeze
def call(error, payload, host:, port:)
if defined?(Raven)
::Raven.capture_exception(error, level: ERROR_LEVEL)
else
$stderr.puts('ErrorHandlerWithSentry is configured but `Raven` is undefined.')
end
end
end
end
end
|
Change API Councillors Query To Multiple Criteria | class Api::CouncillorsController < ApiController
def index
@councillors = if @@query.empty?
Councillor.all
else
Councillor.where("lower(first_name) LIKE ? OR
lower(last_name) LIKE ? OR
lower(email) LIKE ?", @@query, @@query, @@query)
end
paginate json: @councillors.order(change_query_order), per_page: change_per_page
end
def show
@councillor = Councillor.find(params[:id])
render json: @councillor, serializer: CouncillorDetailSerializer
end
end
| class Api::CouncillorsController < ApiController
def index
ward_id = params[:ward_id]
@councillors = Councillor.all
@councillors = @councillors.where("lower(first_name) LIKE ? OR
lower(last_name) LIKE ? OR
lower(email) LIKE ?", @@query, @@query, @@query) unless @@query.empty?
@councillors = @councillors.where("ward_id = ?", ward_id) if ward_id.present?
paginate json: @councillors.order(change_query_order), per_page: change_per_page
end
def show
@councillor = Councillor.find(params[:id])
render json: @councillor, serializer: CouncillorDetailSerializer
end
end
|
Change api origin to https | require 'smugsyncv2/version'
require 'faraday_middleware'
require 'faraday'
require 'simple_oauth'
require 'deepopenstruct'
require 'oauth'
require 'json'
require 'pp'
require_relative './smugsyncv2/client.rb'
module Smugsyncv2
OAUTH_ORIGIN = 'https://secure.smugmug.com'
REQUEST_TOKEN_PATH = '/services/oauth/1.0a/getRequestToken'
ACCESS_TOKEN_PATH = '/services/oauth/1.0a/getAccessToken'
AUTHORIZE_PATH = '/services/oauth/1.0a/authorize'
API_ORIGIN = 'http://api.smugmug.com'
BASE_PATH = 'api/v2'
BASE_URL = File.join(API_ORIGIN, BASE_PATH)
USER_AGENT = "Ruby/#{RUBY_VERSION} (#{RUBY_PLATFORM}; #{RUBY_ENGINE}) Smugsyncv2/#{Smugsyncv2::VERSION} Faraday/#{Faraday::VERSION}".freeze
end
| require 'smugsyncv2/version'
require 'faraday_middleware'
require 'faraday'
require 'simple_oauth'
require 'deepopenstruct'
require 'oauth'
require 'json'
require 'pp'
require_relative './smugsyncv2/client.rb'
module Smugsyncv2
OAUTH_ORIGIN = 'https://secure.smugmug.com'
REQUEST_TOKEN_PATH = '/services/oauth/1.0a/getRequestToken'
ACCESS_TOKEN_PATH = '/services/oauth/1.0a/getAccessToken'
AUTHORIZE_PATH = '/services/oauth/1.0a/authorize'
API_ORIGIN = 'https://api.smugmug.com'
BASE_PATH = 'api/v2'
BASE_URL = File.join(API_ORIGIN, BASE_PATH)
USER_AGENT = "Ruby/#{RUBY_VERSION} (#{RUBY_PLATFORM}; #{RUBY_ENGINE}) Smugsyncv2/#{Smugsyncv2::VERSION} Faraday/#{Faraday::VERSION}".freeze
end
|
Fix for RSpec 3 - this option doesn't exist | require 'adhearsion'
require 'adhearsion/reporter'
require 'socket'
ENV['AHN_ENV'] = 'production'
RSpec.configure do |config|
config.color_enabled = true
config.tty = true
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
end
| require 'adhearsion'
require 'adhearsion/reporter'
require 'socket'
ENV['AHN_ENV'] = 'production'
RSpec.configure do |config|
config.tty = true
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
end
|
Remove explicit require_paths as it's the default | Gem::Specification.new do |s|
s.name = 'aho_corasick_matcher'
s.version = '1.0.0'
s.summary = 'A library to search text for occurrences of a list of strings'
s.description = <<-EOF
Uses the fast Aho-Corasick text search system to find occurrences of any of
a dictionary of strings across an input string.
EOF
s.license = 'MIT'
s.authors = ['Matthew MacLeod']
s.email = 'support@altmetric.com'
s.homepage = 'https://github.com/altmetric/aho_corasick_matcher'
s.files = %w(README.md LICENSE lib/aho_corasick_matcher.rb)
s.test_files = Dir['spec/**/*.rb']
s.require_paths = ['lib']
s.add_development_dependency('rspec', '~> 3.2')
end
| Gem::Specification.new do |s|
s.name = 'aho_corasick_matcher'
s.version = '1.0.0'
s.summary = 'A library to search text for occurrences of a list of strings'
s.description = <<-EOF
Uses the fast Aho-Corasick text search system to find occurrences of any of
a dictionary of strings across an input string.
EOF
s.license = 'MIT'
s.authors = ['Matthew MacLeod']
s.email = 'support@altmetric.com'
s.homepage = 'https://github.com/altmetric/aho_corasick_matcher'
s.files = %w(README.md LICENSE lib/aho_corasick_matcher.rb)
s.test_files = Dir['spec/**/*.rb']
s.add_development_dependency('rspec', '~> 3.2')
end
|
Update Formula to version 4.2.0 | class Bartycrouch < Formula
desc "Incrementally update/translate your Strings files"
homepage "https://github.com/Flinesoft/BartyCrouch"
url "https://github.com/Flinesoft/BartyCrouch.git", :tag => "4.1.1", :revision => "201b0b02c196dcda14c806a539ab963284abeeaf"
head "https://github.com/Flinesoft/BartyCrouch.git"
depends_on :xcode => ["11.4", :build]
def install
system "make", "install", "prefix=#{prefix}"
end
test do
(testpath/"Test.swift").write <<~EOS
import Foundation
class Test {
func test() {
NSLocalizedString("test", comment: "")
}
}
EOS
(testpath/"en.lproj/Localizable.strings").write <<~EOS
/* No comment provided by engineer. */
"oldKey" = "Some translation";
EOS
system bin/"bartycrouch", "update"
assert_match /"oldKey" = "/, File.read("en.lproj/Localizable.strings")
assert_match /"test" = "/, File.read("en.lproj/Localizable.strings")
end
end
| class Bartycrouch < Formula
desc "Incrementally update/translate your Strings files"
homepage "https://github.com/Flinesoft/BartyCrouch"
url "https://github.com/Flinesoft/BartyCrouch.git", :tag => "4.2.0", :revision => "49b4cf27d5b521abf615d4ccb7754d642205f802"
head "https://github.com/Flinesoft/BartyCrouch.git"
depends_on :xcode => ["11.4", :build]
def install
system "make", "install", "prefix=#{prefix}"
end
test do
(testpath/"Test.swift").write <<~EOS
import Foundation
class Test {
func test() {
NSLocalizedString("test", comment: "")
}
}
EOS
(testpath/"en.lproj/Localizable.strings").write <<~EOS
/* No comment provided by engineer. */
"oldKey" = "Some translation";
EOS
system bin/"bartycrouch", "update"
assert_match /"oldKey" = "/, File.read("en.lproj/Localizable.strings")
assert_match /"test" = "/, File.read("en.lproj/Localizable.strings")
end
end
|
Add frozen string literal comment for test | # encoding: UTF-8
require 'helper'
class TestFakerJobVN < Test::Unit::TestCase
include DeterministicHelper
assert_methods_are_deterministic(FFaker::JobVN, :title)
def setup
@tester = FFaker::JobVN
end
def test_title
assert @tester.title.length >= 1
end
def test_nouns
puts @tester.title
assert_kind_of Array, @tester::JOB_NOUNS
end
end
| # frozen_string_literal: true
# encoding: UTF-8
require 'helper'
class TestFakerJobVN < Test::Unit::TestCase
include DeterministicHelper
assert_methods_are_deterministic(FFaker::JobVN, :title)
def setup
@tester = FFaker::JobVN
end
def test_title
assert @tester.title.length >= 1
end
def test_nouns
puts @tester.title
assert_kind_of Array, @tester::JOB_NOUNS
end
end
|
Print message and quit if auth_token isn't set in environment | module Snapme
module CLI
class Command
def self.start(args)
options = Options.parse(args)
Process.daemon(true) if options.daemon
Snapper.new(options.host, options.interval).run
end
end
end
end
| module Snapme
module CLI
class Command
def self.start(args)
options = Options.parse(args)
auth_token = ENV['SNAPME_AUTH_TOKEN']
if auth_token
Process.daemon(true) if options.daemon
Snapper.new(options.host, options.interval, auth_token).run
else
puts <<-MSG
Please set SNAPME_AUTH_TOKEN in your environment. You can get your
auth token from http://snapme.herokuapp.com
MSG
end
end
end
end
end
|
Create a rake task to copy the production database and restore locally. | namespace :db do
namespace :copy do
namespace :production do
desc 'Copy production database'
task to_local: ['db:drop'] do
MongodbClone::MongodbReplication.new.dump.restore
end
end
end
end
| |
Update gem version after adding direction feature |
Gem::Specification.new do |s|
s.name = 'chip-gpio'
s.version = '0.0.1'
s.date = '2016-09-10'
s.homepage = 'http://github.com/willia4/chip-gpio'
s.summary = "A ruby gem to control the GPIO pens on the CHIP computer"
s.description = "A ruby gem to control the GPIO pens on the CHIP computer"
s.authors = ['James Williams']
s.email = 'james@jameswilliams.me'
s.license = 'MIT'
s.files = Dir.glob("{lib}/**/*") + %w(README.md)
end |
Gem::Specification.new do |s|
s.name = 'chip-gpio'
s.version = '0.0.2'
s.date = '2016-09-10'
s.homepage = 'http://github.com/willia4/chip-gpio'
s.summary = "A ruby gem to control the GPIO pens on the CHIP computer"
s.description = "A ruby gem to control the GPIO pens on the CHIP computer"
s.authors = ['James Williams']
s.email = 'james@jameswilliams.me'
s.license = 'MIT'
s.files = Dir.glob("{lib}/**/*") + %w(README.md)
end |
Change active route to a requests controller action | Rails.application.routes.draw do
root to: 'welcome#index'
get '/login', :to => 'sessions#new', :as => :login
get '/logout', :to => 'sessions#destroy', :as => :logout
get "/auth/auth0/callback" => "auth0#callback"
get "/auth/failure" => "auth0#failure"
get "/groups/assign", to: "groups#inquire"
post "/groups/assign", to: "groups#assign"
post 'pusher/auth', to: 'pusher#auth'
get '/active', :to => 'transactions#active', :as => :active
get '/river', :to => 'transactions#river', :as => :river
get '/history', :to => 'transactions#history', :as => :history
resources :requests do
resources :messages
end
end
| Rails.application.routes.draw do
root to: 'welcome#index'
get '/login', :to => 'sessions#new', :as => :login
get '/logout', :to => 'sessions#destroy', :as => :logout
get "/auth/auth0/callback" => "auth0#callback"
get "/auth/failure" => "auth0#failure"
get "/groups/assign", to: "groups#inquire"
post "/groups/assign", to: "groups#assign"
post 'pusher/auth', to: 'pusher#auth'
get '/active', :to => 'requests#active', :as => :active
get '/river', :to => 'transactions#river', :as => :river
get '/history', :to => 'transactions#history', :as => :history
resources :requests do
resources :messages
end
end
|
Add a package for the Toolbar API Plugin. | class Toolbar < Kosmos::Package
title 'Toolbar Plugin'
aliases 'toolbar'
url 'http://blizzy.de/toolbar/Toolbar-1.7.1.zip'
def install
merge_directory 'Toolbar-1.7.1/GameData'
end
end
| |
Resolve type id in a function | module Subjoin
class DerivableResource < Resource
ROOT_URI = nil
TYPE_PATH = nil
def self.type_url
if self.class == Resource
raise Subjoin::SubclassError.new "Class must be a subclass of Resource to use this method"
end
if self::ROOT_URI.nil?
raise Subjoin::SubclassError.new "#{self.class} or a parent of #{self.class} derived from Subjoin::Resource must override ROOT_URI to use this method"
end
if self::TYPE_PATH.nil?
type_segment = self.to_s.downcase.gsub(/^.*::/, '')
else
type_segment = self::TYPE_PATH
end
return [self::ROOT_URI, type_segment].join('/')
end
end
end
| module Subjoin
class DerivableResource < Resource
ROOT_URI = nil
TYPE_PATH = nil
def self.type_id
return self.to_s.downcase.gsub(/^.*::/, '') if self::TYPE_PATH.nil?
return self::TYPE_PATH
end
def self.type_url
if self.class == Resource
raise Subjoin::SubclassError.new "Class must be a subclass of Resource to use this method"
end
if self::ROOT_URI.nil?
raise Subjoin::SubclassError.new "#{self.class} or a parent of #{self.class} derived from Subjoin::Resource must override ROOT_URI to use this method"
end
return [self::ROOT_URI, self::type_id].join('/')
end
end
end
|
Use data driven test case | require 'test/unit'
require 'test/unit/rr'
require_relative '../lib/yomou'
class NovelInfoTest < Test::Unit::TestCase
setup do
ENV["YOMOU_HOME"] = "/tmp"
end
sub_test_case "cache_path" do
test "valid" do
ncode = "x12345"
info = Yomou::NovelInfo::PageParser.new(ncode)
expected = "/tmp/info/12/x12345.html.xz"
assert_equal(expected, info.cache_path.to_s)
end
test "downcase ncode" do
ncode = "X12345"
info = Yomou::NovelInfo::PageParser.new(ncode)
expected = "/tmp/info/12/x12345.html.xz"
assert_equal(expected, info.cache_path.to_s)
end
end
sub_test_case "url" do
test "valid" do
ncode = "x12345"
info = Yomou::NovelInfo::PageParser.new(ncode)
expected = "http://ncode.syosetu.com/novelview/infotop/ncode/x12345/"
assert_equal(expected, info.url)
end
test "downcase ncode" do
ncode = "X12345"
info = Yomou::NovelInfo::PageParser.new(ncode)
expected = "http://ncode.syosetu.com/novelview/infotop/ncode/x12345/"
assert_equal(expected, info.url)
end
end
end
| require 'test/unit'
require 'test/unit/rr'
require_relative '../lib/yomou'
class NovelInfoTest < Test::Unit::TestCase
setup do
ENV["YOMOU_HOME"] = "/tmp"
end
sub_test_case "cache_path" do
expected = "/tmp/info/12/x12345.html.xz"
data(
'valid' => ["x12345", expected],
'unified to downcase?' => ["X12345", expected]
)
def test_cache_path?(data)
ncode, expected = data
info = Yomou::NovelInfo::PageParser.new(ncode)
assert_equal(expected, info.cache_path.to_s)
end
end
sub_test_case "url" do
expected = "http://ncode.syosetu.com/novelview/infotop/ncode/x12345/"
data(
'valid' => ["x12345", expected],
'unified to downcase?' => ["X12345", expected]
)
def test_url?(data)
ncode, expected = data
info = Yomou::NovelInfo::PageParser.new(ncode)
assert_equal(expected, info.url)
end
end
end
|
Add `.body` to faraday response | require 'faraday'
require 'graphql'
module GraphQLDocs
class Client
attr_accessor :faraday
def initialize(options)
@login = options[:login]
@password = options[:password]
if @login.nil? && !@password.nil?
fail ArgumentError, 'Client provided a login, but no password!'
end
if !@login.nil? && @password.nil?
fail ArgumentError, 'Client provided a password, but no login!'
end
@access_token = options[:access_token]
@url = options[:url]
@faraday = Faraday.new(url: @url)
if @login && @password
@faraday.basic_auth(@login, @password)
elsif @access_token
@faraday.authorization('token', @access_token)
end
end
def fetch
@faraday.post do |req|
req.headers['Content-Type'] = 'application/json'
req.body = "{ \"query\": \"#{GraphQL::Introspection::INTROSPECTION_QUERY.gsub("\n", '')}\" }"
end
end
def inspect
inspected = super
# mask password
inspected = inspected.gsub! @password, '*******' if @password
# Only show last 4 of token, secret
if @access_token
inspected = inspected.gsub! @access_token, "#{'*'*36}#{@access_token[36..-1]}"
end
inspected
end
end
end
| require 'faraday'
require 'graphql'
module GraphQLDocs
class Client
attr_accessor :faraday
def initialize(options)
@login = options[:login]
@password = options[:password]
if @login.nil? && !@password.nil?
fail ArgumentError, 'Client provided a login, but no password!'
end
if !@login.nil? && @password.nil?
fail ArgumentError, 'Client provided a password, but no login!'
end
@access_token = options[:access_token]
@url = options[:url]
@faraday = Faraday.new(url: @url)
if @login && @password
@faraday.basic_auth(@login, @password)
elsif @access_token
@faraday.authorization('token', @access_token)
end
end
def fetch
res = @faraday.post do |req|
req.headers['Content-Type'] = 'application/json'
req.body = "{ \"query\": \"#{GraphQL::Introspection::INTROSPECTION_QUERY.gsub("\n", '')}\" }"
end
res.body
end
def inspect
inspected = super
# mask password
inspected = inspected.gsub! @password, '*******' if @password
# Only show last 4 of token, secret
if @access_token
inspected = inspected.gsub! @access_token, "#{'*'*36}#{@access_token[36..-1]}"
end
inspected
end
end
end
|
Remove unused method in Gpdbtable | class GpdbTable < GpdbDatabaseObject
def analyzed_date(table_stats)
analyzed_date = table_stats.fetch("last_analyzed", '')
if analyzed_date.present?
Time.parse(analyzed_date).utc
end
end
def analyze(account)
table_name = '"' + schema.name + '"."' + name + '"';
query_string = "analyze #{table_name}"
schema.with_gpdb_connection(account) do |conn|
conn.select_all(query_string)
end
end
end
| class GpdbTable < GpdbDatabaseObject
def analyze(account)
table_name = '"' + schema.name + '"."' + name + '"';
query_string = "analyze #{table_name}"
schema.with_gpdb_connection(account) do |conn|
conn.select_all(query_string)
end
end
end
|
Fix bug setting check in destination section name. | class GroupTime < ActiveRecord::Base
belongs_to :group
belongs_to :checkin_time
validates_exclusion_of :section, in: ['', '!']
scope_by_site_id
def section=(s)
self[:section] = nil unless s.present?
end
before_create :update_ordering
def update_ordering
if checkin_time and ordering.nil?
scope = checkin_time.group_times
scope = scope.where.not(id: id) unless new_record?
self.ordering = scope.maximum(:ordering).to_i + 1
end
end
def self.section_names
connection.select_values("select distinct section from group_times where section is not null and section != '' and site_id=#{Site.current.id} order by section")
end
end
| class GroupTime < ActiveRecord::Base
belongs_to :group
belongs_to :checkin_time
validates_exclusion_of :section, in: ['', '!']
scope_by_site_id
def section=(s)
self[:section] = s.presence
end
before_create :update_ordering
def update_ordering
if checkin_time and ordering.nil?
scope = checkin_time.group_times
scope = scope.where.not(id: id) unless new_record?
self.ordering = scope.maximum(:ordering).to_i + 1
end
end
def self.section_names
connection.select_values("select distinct section from group_times where section is not null and section != '' and site_id=#{Site.current.id} order by section")
end
end
|
Add require spree_sample to spec helper to prevent failure when running build.sh. | # This file is copied to ~/spec when you run 'ruby script/generate rspec'
# from the project root directory.
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../dummy/config/environment", __FILE__)
require 'rspec/rails'
require 'ffaker'
RSpec.configure do |config|
config.color = true
config.mock_with :rspec
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, comment the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
config.include FactoryGirl::Syntax::Methods
config.fail_fast = ENV['FAIL_FAST'] || false
end
| # This file is copied to ~/spec when you run 'ruby script/generate rspec'
# from the project root directory.
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../dummy/config/environment", __FILE__)
require 'rspec/rails'
require 'ffaker'
require 'spree_sample'
RSpec.configure do |config|
config.color = true
config.mock_with :rspec
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, comment the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
config.include FactoryGirl::Syntax::Methods
config.fail_fast = ENV['FAIL_FAST'] || false
end
|
Support rich text areas without any embeddable forms | require "formalist/element"
require "formalist/elements"
require "formalist/types"
module Formalist
class Elements
class RichTextArea < Field
attribute :box_size, Types::String.enum("single", "small", "normal", "large", "xlarge"), default: "normal"
attribute :inline_formatters, Types::Array
attribute :block_formatters, Types::Array
attribute :embeddable_forms, Types::Strict::Hash # TODO: need better typing, perhaps even require a rich object rather than a hash
# FIXME: it would be tidier to have a reader method for each attribute
def attributes
attrs = super
# Replace the form objects with their AST
attrs.merge(
embeddable_forms: attrs[:embeddable_forms].map { |key, attrs|
original_attrs = attrs
adjusted_attrs = original_attrs.merge(form: original_attrs[:form].build.to_ast)
[key, adjusted_attrs]
}.to_h
)
end
end
register :rich_text_area, RichTextArea
end
end
| require "formalist/element"
require "formalist/elements"
require "formalist/types"
module Formalist
class Elements
class RichTextArea < Field
attribute :box_size, Types::String.enum("single", "small", "normal", "large", "xlarge"), default: "normal"
attribute :inline_formatters, Types::Array
attribute :block_formatters, Types::Array
attribute :embeddable_forms, Types::Strict::Hash # TODO: need better typing, perhaps even require a rich object rather than a hash
# FIXME: it would be tidier to have a reader method for each attribute
def attributes
attrs = super
# Replace the form objects with their AST
attrs.merge(
embeddable_forms: Hash(attrs[:embeddable_forms]).map { |key, attrs|
original_attrs = attrs
adjusted_attrs = original_attrs.merge(form: original_attrs[:form].build.to_ast)
[key, adjusted_attrs]
}.to_h
)
end
end
register :rich_text_area, RichTextArea
end
end
|
Send mails to company as bcc | class DeployerMailer < Mailer
default from: "from@test.com"
layout "mailer"
def send_start(deploy, project)
@deploy = deploy
mail_subject = "[deploys] {#{project.abbreviation}} Notificación de despliegue #{deploy.deploy_name}"
mail to: project.customers_deploys_notifications_emails, cc: project.deploys_notifications_emails, subject: mail_subject
end
def send_successful_end(deploy, project)
@deploy = deploy
mail_subject = "[deploys] {#{project.abbreviation}} Notificación de despliegue #{deploy.deploy_name}"
mail to: project.customers_deploys_notifications_emails, cc: project.deploys_notifications_emails, subject: mail_subject
end
def send_rollback(deploy, project)
@deploy = deploy
mail_subject = "[deploys] {#{project.abbreviation}} Notificación de despliegue #{deploy.deploy_name}"
mail to: project.customers_deploys_notifications_emails, cc: project.deploys_notifications_emails, subject: mail_subject
end
end
| class DeployerMailer < Mailer
default from: "from@test.com"
layout "mailer"
def send_start(deploy, project)
@deploy = deploy
mail_subject = "[deploys] {#{project.abbreviation}} Notificación de despliegue #{deploy.deploy_name}"
mail to: project.customers_deploys_notifications_emails, bcc: project.deploys_notifications_emails, subject: mail_subject
end
def send_successful_end(deploy, project)
@deploy = deploy
mail_subject = "[deploys] {#{project.abbreviation}} Notificación de despliegue #{deploy.deploy_name}"
mail to: project.customers_deploys_notifications_emails, bcc: project.deploys_notifications_emails, subject: mail_subject
end
def send_rollback(deploy, project)
@deploy = deploy
mail_subject = "[deploys] {#{project.abbreviation}} Notificación de despliegue #{deploy.deploy_name}"
mail to: project.customers_deploys_notifications_emails, bcc: project.deploys_notifications_emails, subject: mail_subject
end
end
|
Update Chef dependency to >= 16 | name 'rdiff-backup'
maintainer 'Oregon State University'
maintainer_email 'chef@osuosl.org'
license 'Apache-2.0'
chef_version '>= 14'
description 'Installs/Configures rdiff-backup'
version '4.3.1'
issues_url 'https://github.com/osuosl-cookbooks/rdiff-backup/issues'
source_url 'https://github.com/osuosl-cookbooks/rdiff-backup'
depends 'nrpe'
depends 'sudo'
depends 'yum-epel'
supports 'centos', '~> 7.0'
supports 'centos', '~> 8.0'
| name 'rdiff-backup'
maintainer 'Oregon State University'
maintainer_email 'chef@osuosl.org'
license 'Apache-2.0'
chef_version '>= 16.0'
description 'Installs/Configures rdiff-backup'
version '4.3.1'
issues_url 'https://github.com/osuosl-cookbooks/rdiff-backup/issues'
source_url 'https://github.com/osuosl-cookbooks/rdiff-backup'
depends 'nrpe'
depends 'sudo'
depends 'yum-epel'
supports 'centos', '~> 7.0'
supports 'centos', '~> 8.0'
|
Stop publisher registering certain frontend routes on deployment | namespace :router do
task :router_environment do
Bundler.require :router, :default
require 'logger'
@logger = Logger.new STDOUT
@logger.level = Logger::DEBUG
@router = Router::Client.new :logger => @logger
end
task :register_application => :router_environment do
platform = ENV['FACTER_govuk_platform']
url = "frontend.#{platform}.alphagov.co.uk/"
@logger.info "Registering application..."
@router.applications.update application_id: "frontend", backend_url: url
end
task :register_routes => [ :router_environment, :environment ] do
@logger.info "Registering homepage at /"
@router.routes.update application_id: "frontend", route_type: :full,
incoming_path: "/"
@logger.info "Registering asset path /publisher-assets"
@router.routes.update application_id: "frontend", route_type: :prefix,
incoming_path: "/publisher-assets"
end
desc "Register publisher application and routes with the router (run this task on server in cluster)"
task :register => [ :register_application, :register_routes ]
end
| namespace :router do
task :router_environment do
Bundler.require :router, :default
require 'logger'
@logger = Logger.new STDOUT
@logger.level = Logger::DEBUG
@router = Router::Client.new :logger => @logger
end
task :register_application => :router_environment do
platform = ENV['FACTER_govuk_platform']
url = "frontend.#{platform}.alphagov.co.uk/"
@logger.info "Registering application..."
@router.applications.update application_id: "frontend", backend_url: url
end
task :register_routes => [ :router_environment, :environment ] do
end
desc "Register publisher application and routes with the router (run this task on server in cluster)"
task :register => [ :register_application, :register_routes ]
end
|
Update ajax call on locations to contain latlng coordinates | get '/projects' do
@projects = Project.all.shuffle
erb :'projects/explore', layout: :map_layout
end
get '/projects/new' do
erb :'projects/new_project'
end
post '/projects' do
@project = Project.new(params[:project])
@project.set_default_user(session[:user_id])
@project.set_tags(params[:tags])
filename = params[:coverphoto][:filename]
tempfile = params[:coverphoto][:tempfile]
@project.set_cover_img(filename, tempfile)
@project.status = 1
@project.save
redirect "/projects/#{@project.id}"
end
get '/projects/:id' do
@project = Project.find(params[:id])
@members = User.find(@project.users.ids)
erb :'projects/detail'
end
get '/locations' do
if request.xhr?
@projects = Project.all
@locations = @projects.map(&:location)
p @locations
content_type :json
{ :locations => @locations }.to_json
else
redirect '/projects'
end
end
| get '/projects' do
@projects = Project.all.shuffle
erb :'projects/explore', layout: :map_layout
end
get '/projects/new' do
erb :'projects/new_project'
end
post '/projects' do
@project = Project.new(params[:project])
@project.set_default_user(session[:user_id])
@project.set_tags(params[:tags])
@project.set_location(params[:location])
filename = params[:coverphoto][:filename]
tempfile = params[:coverphoto][:tempfile]
@project.set_cover_img(filename, tempfile)
@project.status = 1
@project.save
p @project
redirect "/projects/#{@project.id}"
end
get '/projects/:id' do
@project = Project.find(params[:id])
@members = User.find(@project.users.ids)
erb :'projects/detail'
end
get '/locations' do
if request.xhr?
@projects = Project.all
@locations = @projects.map { |project| {lat: project.lat, lng: project.lng, title: project.project_name, id: project.id} }
content_type :json
{ :projects => @locations }.to_json
else
redirect '/projects'
end
end
|
Remove linefeed from og:description for post | module PostDecorator
def to_meta_description
plain_text_body.first(140)
end
def to_og_params
{
locale: 'ja_JP',
type: 'article',
title: title,
description: render_markdown(body),
url: post_url(id, all: true),
site_name: site.name,
modified_time: updated_at.to_datetime.to_s,
image: thumbnail_url
}
end
def to_article_params
{
section: category.name,
published_time: published_at.to_datetime.to_s
}
end
private
def plain_text_body
@plain_text_body ||= strip_tags(render_markdown(body)).gsub(/[[:space:]]+/, ' ')
end
end
| module PostDecorator
def to_meta_description
plain_text_body.first(140)
end
def to_og_params
{
locale: 'ja_JP',
type: 'article',
title: title,
description: render_markdown(body)&.gsub("\n", ''),
url: post_url(id, all: true),
site_name: site.name,
modified_time: updated_at.to_datetime.to_s,
image: thumbnail_url
}
end
def to_article_params
{
section: category.name,
published_time: published_at.to_datetime.to_s
}
end
private
def plain_text_body
@plain_text_body ||= strip_tags(render_markdown(body)).gsub(/[[:space:]]+/, ' ')
end
end
|
Expand category header on articles | module CategoriesHelper
def active?(category)
current_category
current_page?(category_path(category)) || (category.is_homepage && current_page?(root_path)) ||
(defined?(@current_category) && @current_category&.id == category.id)
end
def expandable?
(defined?(@category) && !current_page?(new_category_path)) ||
(defined?(@post) && !@post.category.nil?) ||
(defined?(@question) && !@question.category.nil?)
end
def current_category
@current_category ||= if defined? @category
@category
elsif defined?(@post) && !@post.category.nil?
@post.category
elsif defined?(@question) && !@question.category.nil?
@question.category
end
end
end
| module CategoriesHelper
def active?(category)
current_category
current_page?(category_path(category)) || (category.is_homepage && current_page?(root_path)) ||
(defined?(@current_category) && @current_category&.id == category.id)
end
def expandable?
(defined?(@category) && !current_page?(new_category_path)) ||
(defined?(@post) && !@post.category.nil?) ||
(defined?(@question) && !@question.category.nil?) ||
(defined?(@article) && !@article.category.nil?)
end
def current_category
@current_category ||= if defined? @category
@category
elsif defined?(@post) && !@post.category.nil?
@post.category
elsif defined?(@question) && !@question.category.nil?
@question.category
end
end
end
|
Fix - Redundant self detected. | module Spree
class Subscription < ActiveRecord::Base
belongs_to :user
belongs_to :address
belongs_to :subscription_product
has_and_belongs_to_many :shipped_products, class_name: 'Spree::Product'
before_create do
self.next_date = Time.zone.today + 1
end
scope :send_today, -> { where next_date: Time.zone.today }
def missing_items
limit - shipped_products.count
end
def create_order
order = Order.create(
user: user,
bill_address: user.bill_address || address,
ship_address: address,
email: user.email,
state: 'confirm'
)
self.shipped_products << random_product
add_line_item(order)
set_next_order_date
order.next
order
end
def self.create_order(subscription_id)
Spree::Subscription.find(subscription_id).create_order
end
def random_product
@random_product ||= Product.unsubscribable.
active.
where.not(id: shipped_products).
order("RANDOM()").
limit(1).
first
end
private
def set_next_order_date
if paid && missing_items > 0
update_attribute :next_date , created_at + shipped_products.count.months
end
end
def add_line_item(order)
Spree::LineItem.create(
order: order,
#NOTE it only works with products without variants
variant: random_product.master
)
end
end
end
| module Spree
class Subscription < ActiveRecord::Base
belongs_to :user
belongs_to :address
belongs_to :subscription_product
has_and_belongs_to_many :shipped_products, class_name: 'Spree::Product'
before_create do
self.next_date = Time.zone.today + 1
end
scope :send_today, -> { where next_date: Time.zone.today }
def missing_items
limit - shipped_products.count
end
def create_order
order = Order.create(
user: user,
bill_address: user.bill_address || address,
ship_address: address,
email: user.email,
state: 'confirm'
)
shipped_products << random_product
add_line_item(order)
set_next_order_date
order.next
order
end
def self.create_order(subscription_id)
Spree::Subscription.find(subscription_id).create_order
end
def random_product
@random_product ||= Product.unsubscribable.
active.
where.not(id: shipped_products).
order("RANDOM()").
limit(1).
first
end
private
def set_next_order_date
if paid && missing_items > 0
update_attribute :next_date , created_at + shipped_products.count.months
end
end
def add_line_item(order)
Spree::LineItem.create(
order: order,
#NOTE it only works with products without variants
variant: random_product.master
)
end
end
end
|
Fix specs to work with Infinity change to singleton object | # encoding: utf-8
require 'spec_helper'
require File.expand_path('../fixtures/classes', __FILE__)
describe Attribute::Comparable, '#range' do
subject { object.range }
let(:object) { described_class.new }
let(:described_class) do
Class.new(ComparableSpecs::Object) do
def type
Types::Numeric
end
end
end
it { should eql(Types::NegativeInfinity..Types::Infinity) }
end
| # encoding: utf-8
require 'spec_helper'
require File.expand_path('../fixtures/classes', __FILE__)
describe Attribute::Comparable, '#range' do
subject { object.range }
let(:object) { described_class.new }
let(:described_class) do
Class.new(ComparableSpecs::Object) do
def type
Types::Numeric
end
end
end
it { should eql(Types::NegativeInfinity.instance..Types::Infinity.instance) }
end
|
Remove old attributes from attr_accessible | require 'digest/md5'
class User < ActiveRecord::Base
self.include_root_in_json = true
devise :database_authenticatable, :recoverable, :trackable,
:validatable, :timeoutable, :lockable, # devise core model extensions
:suspendable, # in signonotron2/lib/devise/models/suspendable.rb
:strengthened # in signonotron2/lib/devise/models/strengthened.rb
attr_accessible :uid, :name, :email, :password, :password_confirmation, :twitter, :github, :beard
attr_readonly :uid
has_many :authorisations, :class_name => 'Doorkeeper::AccessToken', :foreign_key => :resource_owner_id
def to_sensible_json
to_json(:only => [:uid, :version, :name, :email, :github, :twitter])
end
def gravatar_url(opts = {})
opts.symbolize_keys!
qs = opts.select { |k, v| k == :s }.collect { |k, v| "#{k}=#{Rack::Utils.escape(v)}" }.join('&')
qs = "?" + qs unless qs == ""
"#{opts[:ssl] ? 'https://secure' : 'http://www'}.gravatar.com/avatar/" +
Digest::MD5.hexdigest(email.downcase) + qs
end
end
| require 'digest/md5'
class User < ActiveRecord::Base
self.include_root_in_json = true
devise :database_authenticatable, :recoverable, :trackable,
:validatable, :timeoutable, :lockable, # devise core model extensions
:suspendable, # in signonotron2/lib/devise/models/suspendable.rb
:strengthened # in signonotron2/lib/devise/models/strengthened.rb
attr_accessible :uid, :name, :email, :password, :password_confirmation
attr_readonly :uid
has_many :authorisations, :class_name => 'Doorkeeper::AccessToken', :foreign_key => :resource_owner_id
def to_sensible_json
to_json(:only => [:uid, :version, :name, :email, :github, :twitter])
end
def gravatar_url(opts = {})
opts.symbolize_keys!
qs = opts.select { |k, v| k == :s }.collect { |k, v| "#{k}=#{Rack::Utils.escape(v)}" }.join('&')
qs = "?" + qs unless qs == ""
"#{opts[:ssl] ? 'https://secure' : 'http://www'}.gravatar.com/avatar/" +
Digest::MD5.hexdigest(email.downcase) + qs
end
end
|
Use NL as default locale. | require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
Bundler.require(*Rails.groups)
require "udongo"
module Dummy
class Application < Rails::Application
# 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.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
Bundler.require(*Rails.groups)
require "udongo"
module Dummy
class Application < Rails::Application
# 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.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :nl
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
|
Fix matcher deprecation warning on time specs. | require 'spec_helper'
describe Likeable::Like do
before do
@time = Time.now
end
describe 'attributes' do
it 'stores target, user, and created_at' do
like = Likeable::Like.new(:target => @target, :user => @user, :time => @time)
like.user.should eq(@user)
like.target.should eq(@target)
# Times often fail equality checks due to microsec precision
like.created_at.should be_close(@time, 1)
end
it 'converts float time to propper Time object' do
like = Likeable::Like.new(:time => @time.to_f)
like.created_at.should be_close(@time, 1)
end
end
end
| require 'spec_helper'
describe Likeable::Like do
before do
@time = Time.now
end
describe 'attributes' do
it 'stores target, user, and created_at' do
like = Likeable::Like.new(:target => @target, :user => @user, :time => @time)
like.user.should eq(@user)
like.target.should eq(@target)
# Times often fail equality checks due to microsec precision
like.created_at.should be_within(1).of(@time)
end
it 'converts float time to propper Time object' do
like = Likeable::Like.new(:time => @time.to_f)
like.created_at.should be_within(1).of(@time)
end
end
end
|
Change :single_access_token :null to true | class AddSingleAccessTokenToInvisionUser < ActiveRecord::Migration
def self.up
add_column :ibf_members, :single_access_token, :string, :null => false
InvisionUser.find_each do |user|
user.update_attributes(:single_access_token => nil)
end
end
def self.down
remove_column :ibf_members, :single_access_token
end
end
| class AddSingleAccessTokenToInvisionUser < ActiveRecord::Migration
def self.up
add_column :ibf_members, :single_access_token, :string, :null => true
InvisionUser.find_each do |user|
user.update_attributes(:single_access_token => nil)
end
end
def self.down
remove_column :ibf_members, :single_access_token
end
end
|
Revert "Removes jasmine tests from running on Travis for now." | namespace :travis do
desc "Runs rspec specs on travis"
task :run_specs do
["rspec spec"].each do |cmd|
puts "Starting to run #{cmd}..."
system("export DISPLAY=:99.0 && bundle exec #{cmd}")
raise "#{cmd} failed!" unless $?.exitstatus == 0
end
end
end
task :travis => 'travis:run_specs'
| namespace :travis do
desc "Runs rspec specs and jasmine specs on travis"
task :run_specs do
["rspec spec", "rake --trace jasmine:ci"].each do |cmd|
puts "Starting to run #{cmd}..."
system("export DISPLAY=:99.0 && bundle exec #{cmd}")
raise "#{cmd} failed!" unless $?.exitstatus == 0
end
end
end
task :travis => 'travis:run_specs' |
Fix deprecation warning for Enumerable.sum | # frozen_string_literal: true
require 'csv'
class CourseWikidataCsvBuilder
def initialize(course)
@course = course
end
def generate_csv
csv_data = [CSV_HEADERS]
csv_data << stat_row if @course.course_stat && @course.home_wiki.project == 'wikidata'
CSV.generate { |csv| csv_data.each { |line| csv << line } }
end
def stat_row
hash_stats = @course
.course_stat.stats_hash['www.wikidata.org']
.merge({ 'course name' => @course.title })
CSV_HEADERS.map { |elmnt| hash_stats.fetch elmnt, '' }
end
CSV_HEADERS = [
'course name',
'claims created',
'claims changed',
'claims removed',
'items created',
'labels added',
'labels changed',
'labels removed',
'descriptions added',
'descriptions changed',
'descriptions removed',
'aliases added',
'aliases changed',
'aliases removed',
'merged from',
'merged to',
'interwiki links added',
'interwiki links removed',
'redirects created',
'reverts performed',
'restorations performed',
'items cleared',
'qualifiers added',
'other updates',
'unknown',
'no data',
'total revisions'
].freeze
end
| # frozen_string_literal: true
require 'csv'
class CourseWikidataCsvBuilder
def initialize(course)
@course = course
end
def generate_csv
csv_data = [CSV_HEADERS]
csv_data << stat_row if @course.course_stat && @course.home_wiki.project == 'wikidata'
CSV.generate { |csv| csv_data.each { |line| csv << line } }
end
def stat_row
hash_stats = @course
.course_stat.stats_hash['www.wikidata.org']
.merge({ 'course name' => @course.title })
CSV_HEADERS.map { |elmnt| hash_stats.fetch elmnt, 0 }
end
CSV_HEADERS = [
'course name',
'claims created',
'claims changed',
'claims removed',
'items created',
'labels added',
'labels changed',
'labels removed',
'descriptions added',
'descriptions changed',
'descriptions removed',
'aliases added',
'aliases changed',
'aliases removed',
'merged from',
'merged to',
'interwiki links added',
'interwiki links removed',
'redirects created',
'reverts performed',
'restorations performed',
'items cleared',
'qualifiers added',
'other updates',
'unknown',
'no data',
'total revisions'
].freeze
end
|
Add @api private to toplevel namespace | # frozen_string_literal: true
require 'timetrack/version'
require 'timetrack/parser'
# Entrypoint for gem
module Timetrack
end
| # frozen_string_literal: true
require 'timetrack/version'
require 'timetrack/parser'
# Entrypoint for gem
#
# @api private
module Timetrack
end
|
Modify Float multiply spec to be_close with a TOLERANCE multiplied by a similar scale as the value under test. | require File.dirname(__FILE__) + '/../../spec_helper'
describe "Float#*" do
it "returns self multiplied by other" do
(4923.98221 * 2).should be_close(9847.96442, TOLERANCE)
(6712.5 * 0.25).should be_close(1678.125, TOLERANCE)
(256.4096 * 0xffffffff).to_s.should == 1101270846124.03.to_s
end
end
| require File.dirname(__FILE__) + '/../../spec_helper'
describe "Float#*" do
it "returns self multiplied by other" do
(4923.98221 * 2).should be_close(9847.96442, TOLERANCE)
(6712.5 * 0.25).should be_close(1678.125, TOLERANCE)
(256.4096 * 0xffffffff).should be_close(1101270846124.03, TOLERANCE * 0xffffffff)
end
end
|
Test for network errors when retrieving comments | require 'spec_helper'
module USaidWat
module Client
describe Client do
before(:each) do
WebMock.disable_net_connect!
WebMock.reset!
root = File.expand_path("../../../test/responses", __FILE__)
stub_request(:get, "http://www.reddit.com/user/mipadi/comments.json?after=&limit=100").
to_return(:body => IO.read(File.join(root, "comments.json")))
end
let(:redditor) { Client::Redditor.new("mipadi") }
describe "#username" do
it "returns the Redditor's username" do
redditor.username.should == "mipadi"
end
end
describe "#comments" do
it "gets 100 comments" do
redditor.comments.count.should == 100
end
end
end
end
end
| require 'spec_helper'
module USaidWat
module Client
describe Client do
let(:redditor) { Client::Redditor.new("mipadi") }
describe "#username" do
it "returns the Redditor's username" do
redditor.username.should == "mipadi"
end
end
context "when Reddit is up" do
before(:each) do
WebMock.disable_net_connect!
WebMock.reset!
root = File.expand_path("../../../test/responses", __FILE__)
stub_request(:get, "http://www.reddit.com/user/mipadi/comments.json?after=&limit=100").
to_return(:body => IO.read(File.join(root, "comments.json")))
end
describe "#comments" do
it "gets 100 comments" do
redditor.comments.count.should == 100
end
end
end
context "when Reddit is down" do
before(:each) do
WebMock.disable_net_connect!
WebMock.reset!
stub_request(:get, "http://www.reddit.com/user/mipadi/comments.json?after=&limit=100").
to_return(:status => 500)
end
describe "#comments" do
it "gets 100 comments" do
expect { redditor.comments }.to raise_error(RuntimeError)
end
end
end
end
end
end
|
Add some seed data for the demo | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
| Customer.create([
{name: "3", transaction_count: 100_000_000},
{name: "O2", transaction_count: 100_000_000},
{name: "Orange", transaction_count: 100_000_000},
{name: "Talkmobile", transaction_count: 100_000_000},
{name: "T-Mobile", transaction_count: 100_000_000},
{name: "Virgin Mobile", transaction_count: 100_000_000},
{name: "Vodafone", transaction_count: 100_000_000},
{name: "Asda Mobile", transaction_count: 100_000_000},
{name: "Family Mobile", transaction_count: 100_000_000},
{name: "GiffGaff", transaction_count: 100_000_000},
{name: "Lebara Mobile", transaction_count: 100_000_000},
{name: "Tesco Mobile", transaction_count: 100_000_000}
])
|
Move hive package check into its own section and do symlink test for CentOS | require 'spec_helper'
describe 'hadoop::hive' do
context 'on Centos 6.4 x86_64' do
let(:chef_run) do
ChefSpec::Runner.new(platform: 'centos', version: 6.4) do |node|
node.automatic['domain'] = 'example.com'
node.default['hive']['hive_site']['hive.exec.local.scratchdir'] = '/tmp'
stub_command('update-alternatives --display hadoop-conf | grep best | awk \'{print $5}\' | grep /etc/hadoop/conf.chef').and_return(false)
stub_command('update-alternatives --display hive-conf | grep best | awk \'{print $5}\' | grep /etc/hive/conf.chef').and_return(false)
end.converge(described_recipe)
end
%w(mysql-connector-java postgresql-jdbc hive).each do |pkg|
it "install #{pkg} package" do
expect(chef_run).to install_package(pkg)
end
end
end
end
| require 'spec_helper'
describe 'hadoop::hive' do
context 'on Centos 6.4 x86_64' do
let(:chef_run) do
ChefSpec::Runner.new(platform: 'centos', version: 6.4) do |node|
node.automatic['domain'] = 'example.com'
node.default['hive']['hive_site']['hive.exec.local.scratchdir'] = '/tmp'
stub_command('update-alternatives --display hadoop-conf | grep best | awk \'{print $5}\' | grep /etc/hadoop/conf.chef').and_return(false)
stub_command('update-alternatives --display hive-conf | grep best | awk \'{print $5}\' | grep /etc/hive/conf.chef').and_return(false)
end.converge(described_recipe)
end
it 'install hive package' do
expect(chef_run).to install_package('hive')
end
%w(mysql-connector-java postgresql-jdbc).each do |pkg|
it "install #{pkg} package" do
expect(chef_run).to install_package(pkg)
end
it "link #{pkg} jar" do
link = chef_run.link("/usr/lib/hive/lib/#{pkg}.jar")
expect(link).to link_to("/usr/share/java/#{pkg}.jar")
end
end
end
end
|
Use the all_verbs roda plugin so we can use additional HTTP verbs | require "bugsnag"
require "rack/csrf"
require "dry-web-roda"
require "main/container"
require "roda_plugins"
module Main
class Application < Dry::Web::Roda::Application
configure do |config|
config.routes = "web/routes".freeze
config.container = Container
end
opts[:root] = Pathname(__FILE__).join("../..").realpath.dirname
use Rack::Session::Cookie, key: "app_prototype.session", secret: AppPrototype::Container.settings.session_secret
use Rack::Csrf, raise: true
use Bugsnag::Rack
plugin :error_handler
plugin :flash
plugin :view
plugin :page
def name
:main
end
route do |r|
r.root do
r.view "home"
end
r.multi_route
end
error do |e|
if ENV["RACK_ENV"] == "production"
if e.is_a?(ROM::TupleCountMismatchError)
response.status = 404
self.class["main.views.errors.error_404"].(scope: current_page)
else
Bugsnag.auto_notify e
self.class["main.views.errors.error_500"].(scope: current_page)
end
else
Bugsnag.auto_notify e
raise e
end
end
load_routes!
end
end
| require "bugsnag"
require "rack/csrf"
require "dry-web-roda"
require "main/container"
require "roda_plugins"
module Main
class Application < Dry::Web::Roda::Application
configure do |config|
config.routes = "web/routes".freeze
config.container = Container
end
opts[:root] = Pathname(__FILE__).join("../..").realpath.dirname
use Rack::Session::Cookie, key: "app_prototype.session", secret: AppPrototype::Container.settings.session_secret
use Rack::Csrf, raise: true
use Rack::MethodOverride
use Bugsnag::Rack
plugin :all_verbs
plugin :error_handler
plugin :flash
plugin :page
plugin :view
def name
:main
end
route do |r|
r.root do
r.view "home"
end
r.multi_route
end
error do |e|
if ENV["RACK_ENV"] == "production"
if e.is_a?(ROM::TupleCountMismatchError)
response.status = 404
self.class["main.views.errors.error_404"].(scope: current_page)
else
Bugsnag.auto_notify e
self.class["main.views.errors.error_500"].(scope: current_page)
end
else
Bugsnag.auto_notify e
raise e
end
end
load_routes!
end
end
|
Fix bug. Protocol not included in EM_Connector handler | # coding: utf-8
module ClientForPoslynx
module Net
class EM_Connector
class ConnectionHandler < EM::Connection
include EMC::HandlesConnection
end
end
end
end
| # coding: utf-8
module ClientForPoslynx
module Net
class EM_Connector
class ConnectionHandler < EM::Connection
include EM::Protocols::POSLynx
include EMC::HandlesConnection
end
end
end
end
|
Update SHAs of 0.5.0 tarballs | class GitDuet < Formula
desc "Pairing tool for Git"
homepage "https://github.com/git-duet/git-duet"
version "0.5.0"
if OS.mac?
url "https://github.com/git-duet/git-duet/releases/download/0.5.0/darwin_amd64.tar.gz"
sha256 "adc9fe97c99e92fdb160ad29413ec437e125d454590f41be1b91924a4c9efb09"
elsif OS.linux?
url "https://github.com/git-duet/git-duet/releases/download/0.5.0/linux_amd64.tar.gz"
sha256 "e4f767b4c41772641b9178ed3f1d45f6f5f1d3b9b8509fe7016f5376aa181474"
end
depends_on :arch => :x86_64
def install
%w[git-duet git-duet-commit git-duet-revert git-duet-install-hook git-duet-merge git-duet-pre-commit git-solo].each do |exe|
bin.install exe
end
end
test do
system "git", "duet", "-h"
end
end
| class GitDuet < Formula
desc "Pairing tool for Git"
homepage "https://github.com/git-duet/git-duet"
version "0.5.0"
if OS.mac?
url "https://github.com/git-duet/git-duet/releases/download/0.5.0/darwin_amd64.tar.gz"
sha256 "88050ceb98480a7917106180c4d81764f94db5719ad3b458b90ac7af6cee9849"
elsif OS.linux?
url "https://github.com/git-duet/git-duet/releases/download/0.5.0/linux_amd64.tar.gz"
sha256 "37ddd1285b5a58c4c3f03cc310a5b0d4af7eaa7a24ce44fd69206fe25aabd949"
end
depends_on :arch => :x86_64
def install
%w[git-duet git-duet-commit git-duet-revert git-duet-install-hook git-duet-merge git-duet-pre-commit git-solo].each do |exe|
bin.install exe
end
end
test do
system "git", "duet", "-h"
end
end
|
Write tests for Activity model - all pass | require 'rails_helper'
RSpec.describe Activity, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
| require 'rails_helper'
RSpec.describe Activity, type: :model do
let(:activity) { Activity.new(description: "Here is a description.", itinerary_id: 1, location_id: 2) }
it "has a valid description" do
expect(activity.description).to eq("Here is a description.")
end
it "has a valid itinerary ID" do
expect(activity.itinerary_id).to eq(1)
end
it "has a valid location ID" do
expect(activity.location_id).to eq(2)
end
it { should belong_to(:itinerary) }
it { should belong_to(:location) }
end
|
Switch allowed frontend origin by rails environment | # Be sure to restart your server when you modify this file.
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.
# Read more: https://github.com/cyu/rack-cors
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'tebukuro.shinosakarb.org', 'localhost:4000'
resource '*',
headers: :any,
credentials: true,
expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
methods: [:get, :post, :delete, :patch]
end
end
| # Be sure to restart your server when you modify this file.
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.
# Read more: https://github.com/cyu/rack-cors
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins Rails.env.development? ? 'localhost:4000' : 'tebukuro.shinosakarb.org'
resource '*',
headers: :any,
credentials: true,
expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
methods: [:get, :post, :delete, :patch]
end
end
|
Add aasm, comments and assignment attributes | class EdiOpsTransaction
include Mongoid::Document
include Mongoid::Timestamps
field :qualifying_reason_uri, type: String
field :enrollment_group_uri, type: String
field :submitted_timestamp, type: DateTime
field :event_key, type: String
field :event_name, type: String
field :status, type: String
end
| class EdiOpsTransaction
include Mongoid::Document
include Mongoid::Timestamps
include AASM
field :qualifying_reason_uri, type: String
field :enrollment_group_uri, type: String
field :submitted_timestamp, type: DateTime
field :event_key, type: String
field :event_name, type: String
field :assigned_to, type: String
field :resolved_by, type: String
field :aasm_state, type: String
embeds_many :comments, cascade_callbacks: true
accepts_nested_attributes_for :comments, reject_if: proc { |attribs| attribs['content'].blank? }, allow_destroy: true
index({aasm_state: 1})
aasm do
state :open, initial: true
state :assigned
state :resolved
event assign: do
transitions from: :open, to: :assigned
end
event resolve: do
transitions from: :assigned, to: :resolved
end
end
end
|
Fix typo - only output container ID | module Morph
class DockerMaintenance
def self.delete_container_and_remove_image(container)
delete_container(container)
remove_image(container_image(container))
end
def self.remove_image(image)
Rails.logger.info "Removing image #{image.id}..."
image.remove
rescue Docker::Error::ConfictError
Rails.logger.warn "Conflict removing image, skipping..."
rescue Docker::Error::NotFoundError
Rails.logger.warn "Couldn't find container image, skipping..."
end
private
def self.delete_container(container)
Rails.logger.info "Deleting container #{container}..."
container.delete
end
def self.container_image(container)
image_id = container.info["Image"].split(":").first
Docker::Image.get(image_id)
end
end
end
| module Morph
class DockerMaintenance
def self.delete_container_and_remove_image(container)
delete_container(container)
remove_image(container_image(container))
end
def self.remove_image(image)
Rails.logger.info "Removing image #{image.id}..."
image.remove
rescue Docker::Error::ConfictError
Rails.logger.warn "Conflict removing image, skipping..."
rescue Docker::Error::NotFoundError
Rails.logger.warn "Couldn't find container image, skipping..."
end
private
def self.delete_container(container)
Rails.logger.info "Deleting container #{container.id}..."
container.delete
end
def self.container_image(container)
image_id = container.info["Image"].split(":").first
Docker::Image.get(image_id)
end
end
end
|
Update upstream t3-gerrit to 0.4.20 | name "site-reviewtypo3org"
maintainer "Steffen Gebert / TYPO3 Association"
maintainer_email "steffen.gebert@typo3.org"
license "Apache 2.0"
description "Installs/configures something"
version "0.1.22"
depends "ssh", "= 0.6.6"
depends "ssl_certificates", "= 1.1.3"
depends "t3-gerrit", "= 0.4.19"
depends "gerrit", "= 0.4.5"
depends "t3-chef-vault", "= 1.0.1"
| name "site-reviewtypo3org"
maintainer "Steffen Gebert / TYPO3 Association"
maintainer_email "steffen.gebert@typo3.org"
license "Apache 2.0"
description "Installs/configures something"
version "0.1.23"
depends "ssh", "= 0.6.6"
depends "ssl_certificates", "= 1.1.3"
depends "t3-gerrit", "= 0.4.20"
depends "gerrit", "= 0.4.5"
depends "t3-chef-vault", "= 1.0.1"
|
Remove version constraint from git cookbook | name "ps2dev"
maintainer "Mathias Lafeldt"
maintainer_email "mathias.lafeldt@gmail.com"
license "Apache 2.0"
description "Installs a full-fledged PS2 development environment"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version "1.0.3"
recipe "ps2dev::default", "Installs a full-fledged PS2 development environment"
supports "ubuntu"
supports "debian"
depends "build-essential"
depends "git", "1.0.0"
| name "ps2dev"
maintainer "Mathias Lafeldt"
maintainer_email "mathias.lafeldt@gmail.com"
license "Apache 2.0"
description "Installs a full-fledged PS2 development environment"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version "1.0.3"
recipe "ps2dev::default", "Installs a full-fledged PS2 development environment"
supports "ubuntu"
supports "debian"
depends "build-essential"
depends "git"
|
Update webadmin to use bundler. | require 'facets/kernel/ergo'
RAILS_ROOT = File.dirname(File.dirname(File.expand_path(__FILE__)))
RESTART_TXT = "#{RAILS_ROOT}/tmp/restart.txt"
def get_current_revision
return `(cd #{RAILS_ROOT} && git --no-pager log -1) 2>&1`
end
get '/' do
@revision = get_current_revision
haml :index
end
post '/' do
@revision = get_current_revision
action = params[:action].ergo.to_s[/(\w+)/, 1]
revision = params[:revision].ergo.to_s[/(\w+)/, 1]
@command = nil
common_restart = %{rake RAILS_ENV=production clear && touch #{RESTART_TXT}}
common_deploy = %{rake RAILS_ENV=production db:migrate && #{common_restart}}
case action
when "deploy_and_migrate_via_update"
if revision
@command = %{git pull && git checkout #{revision} && #{common_deploy}}
else
@message = "ERROR: must specify revision to deploy via update"
end
when "restart", "start", "stop", "status"
@command = %{#{common_restart}}
end
if @command
@message = "Executing: #{@command}\n\n"
@message << `(cd #{RAILS_ROOT} && #{@command}) 2>&1`
end
haml :index
end
| require 'facets/kernel/ergo'
RAILS_ROOT = File.dirname(File.dirname(File.expand_path(__FILE__)))
RESTART_TXT = "#{RAILS_ROOT}/tmp/restart.txt"
def get_current_revision
return `(cd #{RAILS_ROOT} && git --no-pager log -1) 2>&1`
end
get '/' do
@revision = get_current_revision
haml :index
end
post '/' do
@revision = get_current_revision
action = params[:action].ergo.to_s[/(\w+)/, 1]
revision = params[:revision].ergo.to_s[/(\w+)/, 1]
@command = nil
common_restart = %{rake RAILS_ENV=production clear && bundle update --local && touch #{RESTART_TXT}}
common_deploy = %{rake RAILS_ENV=production db:migrate && #{common_restart}}
case action
when "deploy_and_migrate_via_update"
if revision
@command = %{git pull --rebase && git checkout #{revision} && #{common_deploy}}
else
@message = "ERROR: must specify revision to deploy via update"
end
when "restart", "start", "stop", "status"
@command = %{#{common_restart}}
end
if @command
@message = "Executing: #{@command}\n\n"
@message << `(cd #{RAILS_ROOT} && #{@command}) 2>&1`
end
haml :index
end
|
Add File::absolute_path? as a core_ext | # encoding: utf-8
class File
# determine whether a String path is absolute.
# @example
# File.absolute_path?('foo') #=> false
# File.absolute_path?('/foo') #=> true
# File.absolute_path?('foo/bar') #=> false
# File.absolute_path?('/foo/bar') #=> true
# File.absolute_path?('C:foo/bar') #=> false
# File.absolute_path?('C:/foo/bar') #=> true
# @param [String] - a pathname
# @return [Boolean]
def self.absolute_path?(path)
false | File.dirname(path)[/\A([A-Z]:)?#{Regexp.escape(File::SEPARATOR)}/i]
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.