Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Set of documentation helpers regarding applicable version. | activate :aria_current
activate :directory_indexes
activate :syntax do |syntax|
syntax.css_class = "syntax-highlight"
end
set :markdown, tables: true, autolink: true, gh_blockcode: true, fenced_code_blocks: true, with_toc_data: true, no_intra_emphasis: true
set :markdown_engine, :redcarpet
set :res_version, File.read('../RES_VERSION')
page "/", layout: "landing"
page "/docs/*", layout: "documentation"
| activate :aria_current
activate :directory_indexes
activate :syntax do |syntax|
syntax.css_class = "syntax-highlight"
end
set :markdown, tables: true, autolink: true, gh_blockcode: true, fenced_code_blocks: true, with_toc_data: true, no_intra_emphasis: true
set :markdown_engine, :redcarpet
set :res_version, File.read('../RES_VERSION')
helpers do
def version_above(version_string)
given_version = Gem::Version.new(version_string)
current_version = Gem::Version.new(config[:res_version])
current_version > given_version
end
def in_version_above(version_string, &block)
block.call if version_above(version_string)
end
def in_version_at_most(version_string, &block)
block.call unless version_above(version_string)
end
end
page "/", layout: "landing"
page "/docs/*", layout: "documentation"
|
Fix Weechat always installing to /usr/local | require 'brewkit'
class Weechat <Formula
@url='http://www.weechat.org/files/src/weechat-0.3.0.tar.bz2'
@homepage='http://www.weechat.org'
@md5='c31cfc229e964ff9257cc9c7f9e6c9bc'
depends_on 'cmake'
depends_on 'gnutls'
def install
#FIXME: Compiling perl module doesn't work
#FIXME: GnuTLS support isn't detected
system "cmake", "-DDISABLE_PERL=ON", std_cmake_parameters, "."
system "make install"
end
end
| require 'brewkit'
class Weechat <Formula
@url='http://www.weechat.org/files/src/weechat-0.3.0.tar.bz2'
@homepage='http://www.weechat.org'
@md5='c31cfc229e964ff9257cc9c7f9e6c9bc'
depends_on 'cmake'
depends_on 'gnutls'
def install
#FIXME: Compiling perl module doesn't work
#FIXME: GnuTLS support isn't detected
#NOTE: -DPREFIX has to be specified because weechat devs enjoy being non-standard
system "cmake", "-DPREFIX=#{prefix}",
"-DDISABLE_PERL=ON",
std_cmake_parameters, "."
system "make install"
end
end
|
Set Sequel's timezones to UTC | require "sequel"
Sequel.extension :inflector
require 'sequel/plugins/serialization'
Sequel::Plugins::Serialization.register_format(
:ojson,
lambda { |v| Yajl::Encoder.new.encode(v) },
lambda { |v| Yajl::Parser.new(:symbolize_keys => true).parse(v) }
)
# Sequel::Plugins::Serialization.register_format(
# :ojson,
# lambda { |v| Oj.dump(v) },
# lambda { |v| Oj.load(v, symbol_keys: true) }
# )
| require "sequel"
Sequel.extension :inflector
# See http://sequel.jeremyevans.net/rdoc/classes/Sequel/Timezones.html
# UTC is more performant than :local (or 'nil' which just fallsback to :local)
# A basic profiling run gives a 2 x performance improvement of :utc over :local
# With ~240 rows, timing ::Content.all gives:
#
# :utc ~0.04s
# :local ~0.08s
#
# DB timestamps are only shown in the editing UI & could be localized there per-user
Sequel.default_timezone = :utc
require 'sequel/plugins/serialization'
Sequel::Plugins::Serialization.register_format(
:ojson,
lambda { |v| Yajl::Encoder.new.encode(v) },
lambda { |v| Yajl::Parser.new(:symbolize_keys => true).parse(v) }
)
# Sequel::Plugins::Serialization.register_format(
# :ojson,
# lambda { |v| Oj.dump(v) },
# lambda { |v| Oj.load(v, symbol_keys: true) }
# )
|
Add bill association to activities | module ClioClient
class Activity < Resource
set_attributes(id: {type: :int, readonly: true},
created_at: {type: :datetime, readonly: true},
updated_at: {type: :datetime, readonly: true},
type: {type: :string, required: true},
date: {type: :date },
quantity: {type: :decimal, required: true},
price: {type: :decimal, required: true},
total: {type: :string, readonly: true},
note: {type: :string },
billed: {type: :boolean, readonly: true}
)
has_association :user, ClioClient::User
has_association :matter, ClioClient::Matter
has_association :activity_description, ClioClient::ActivityDescription
has_association :communication, ClioClient::Communication
private
def api
session.activities
end
end
end
| module ClioClient
class Activity < Resource
set_attributes(id: {type: :int, readonly: true},
created_at: {type: :datetime, readonly: true},
updated_at: {type: :datetime, readonly: true},
type: {type: :string, required: true},
date: {type: :date },
quantity: {type: :decimal, required: true},
price: {type: :decimal, required: true},
total: {type: :string, readonly: true},
note: {type: :string },
billed: {type: :boolean, readonly: true}
)
has_association :user, ClioClient::User
has_association :bill, ClioClient::Bill
has_association :matter, ClioClient::Matter
has_association :activity_description, ClioClient::ActivityDescription
has_association :communication, ClioClient::Communication
private
def api
session.activities
end
end
end
|
Make markdown helper safer to use | module ApplicationHelper
def home_page?
return false if user_signed_in?
# Using path because fullpath yields false negatives since it contains
# parameters too
request.path == '/'
end
def opendata_page?
request.path == '/opendata'
end
# if current path is /debates current_path_with_query_params(foo: 'bar') returns /debates?foo=bar
# notice: if query_params have a param which also exist in current path, it "overrides" (query_params is merged last)
def current_path_with_query_params(query_parameters)
url_for(request.query_parameters.merge(query_parameters))
end
def markdown(text)
# See https://github.com/vmg/redcarpet for options
render_options = {
filter_html: false,
hard_wrap: true,
link_attributes: { target: "_blank" }
}
renderer = Redcarpet::Render::HTML.new(render_options)
extensions = {
autolink: true,
fenced_code_blocks: true,
lax_spacing: true,
no_intra_emphasis: true,
strikethrough: true,
superscript: true
}
Redcarpet::Markdown.new(renderer, extensions).render(text).html_safe
end
def author_of?(authorable, user)
return false if authorable.blank? || user.blank?
authorable.author_id == user.id
end
end
| module ApplicationHelper
def home_page?
return false if user_signed_in?
# Using path because fullpath yields false negatives since it contains
# parameters too
request.path == '/'
end
def opendata_page?
request.path == '/opendata'
end
# if current path is /debates current_path_with_query_params(foo: 'bar') returns /debates?foo=bar
# notice: if query_params have a param which also exist in current path, it "overrides" (query_params is merged last)
def current_path_with_query_params(query_parameters)
url_for(request.query_parameters.merge(query_parameters))
end
def markdown(text)
return text if text.blank?
# See https://github.com/vmg/redcarpet for options
render_options = {
filter_html: false,
hard_wrap: true,
link_attributes: { target: "_blank" }
}
renderer = Redcarpet::Render::HTML.new(render_options)
extensions = {
autolink: true,
fenced_code_blocks: true,
lax_spacing: true,
no_intra_emphasis: true,
strikethrough: true,
superscript: true
}
Redcarpet::Markdown.new(renderer, extensions).render(text).html_safe
end
def author_of?(authorable, user)
return false if authorable.blank? || user.blank?
authorable.author_id == user.id
end
end
|
Fix `CommentSmile` notification type not being returned | # frozen_string_literal: true
class Appendable::Reaction < Appendable
# rubocop:disable Rails/SkipsModelValidations
after_create do
Notification.notify parent.user, self unless parent.user == user
user.increment! :smiled_count
parent.increment! :smile_count
end
before_destroy do
Notification.denotify parent&.user, self
user&.decrement! :smiled_count
parent&.decrement! :smile_count
end
# rubocop:enable Rails/SkipsModelValidations
def notification_type(*_args)
Notification::CommentSmiled if parent.instance_of?(Comment)
Notification::Smiled
end
end
| # frozen_string_literal: true
class Appendable::Reaction < Appendable
# rubocop:disable Rails/SkipsModelValidations
after_create do
Notification.notify parent.user, self unless parent.user == user
user.increment! :smiled_count
parent.increment! :smile_count
end
before_destroy do
Notification.denotify parent&.user, self
user&.decrement! :smiled_count
parent&.decrement! :smile_count
end
# rubocop:enable Rails/SkipsModelValidations
def notification_type(*_args)
return Notification::CommentSmiled if parent.instance_of?(Comment)
Notification::Smiled
end
end
|
Use the Rake FileUtils methods, now that we're hooking the verbose output. | require 'rubygems/tasks/build/task'
require 'rubygems/builder'
require 'fileutils'
module Gem
class Tasks
module Build
#
# The `build:gem` task.
#
class Gem < Task
#
# Initializes the `build:gem` task.
#
# @param [Hash] options
# Additional options.
#
def initialize(options={})
super()
yield self if block_given?
define
end
#
# Defines the `build:gem` task.
#
def define
build_task :gem
# backwards compatibility for Gem::PackageTask
task :gem => 'build:gem'
# backwards compatibility for Hoe
task :package => 'build:gem'
end
#
# Builds the `.gem` package.
#
# @param [String] path
# The path for the `.gem` package.
#
# @param [Gem::Specification] gemspec
# The gemspec to build the `.gem` package from.
#
# @api semipublic
#
def build(path,gemspec)
builder = ::Gem::Builder.new(gemspec)
FileUtils.mv builder.build, Project::PKG_DIR
end
end
end
end
end
| require 'rubygems/tasks/build/task'
require 'rubygems/builder'
require 'fileutils'
module Gem
class Tasks
module Build
#
# The `build:gem` task.
#
class Gem < Task
#
# Initializes the `build:gem` task.
#
# @param [Hash] options
# Additional options.
#
def initialize(options={})
super()
yield self if block_given?
define
end
#
# Defines the `build:gem` task.
#
def define
build_task :gem
# backwards compatibility for Gem::PackageTask
task :gem => 'build:gem'
# backwards compatibility for Hoe
task :package => 'build:gem'
end
#
# Builds the `.gem` package.
#
# @param [String] path
# The path for the `.gem` package.
#
# @param [Gem::Specification] gemspec
# The gemspec to build the `.gem` package from.
#
# @api semipublic
#
def build(path,gemspec)
builder = ::Gem::Builder.new(gemspec)
mv builder.build, Project::PKG_DIR
end
end
end
end
end
|
Rename straggling logs API config key | require 'travis/logs_api'
require 'travis/services/base'
module Travis
module Services
class FindLog < Base
register :find_log
def run(options = {})
return result_via_http if Travis.config.logs_api.enabled?
result if result
end
def final?
false
end
private def result
if params[:id]
scope(:log).find_by_id(params[:id])
elsif params[:job_id]
scope(:log).where(job_id: params[:job_id]).first
end
end
private def result_via_http
return logs_api.find_by_id(params[:id]) if params[:id]
logs_api.find_by_job_id(params[:job_id])
end
private def logs_api
@logs_api ||= Travis::LogsApi.new(
url: Travis.config.logs_api.url,
auth_token: Travis.config.logs_api.auth_token
)
end
end
end
end
| require 'travis/logs_api'
require 'travis/services/base'
module Travis
module Services
class FindLog < Base
register :find_log
def run(options = {})
return result_via_http if Travis.config.logs_api.enabled?
result if result
end
def final?
false
end
private def result
if params[:id]
scope(:log).find_by_id(params[:id])
elsif params[:job_id]
scope(:log).where(job_id: params[:job_id]).first
end
end
private def result_via_http
return logs_api.find_by_id(params[:id]) if params[:id]
logs_api.find_by_job_id(params[:job_id])
end
private def logs_api
@logs_api ||= Travis::LogsApi.new(
url: Travis.config.logs_api.url,
token: Travis.config.logs_api.token
)
end
end
end
end
|
Expand tests for LinkSnpPhenotype worker | RSpec.describe LinkSnpPhenotype do
subject do
end
describe 'scoring' do
it 'returns a non-negative score for a SNP' do
end
it 'returns a non-negative count of matched references for a SNP' do
end
it 'uses a consistent scoring scheme' do
end
end
describe 'phenotype matching' do
it 'returns a non-empty list of phenotype for a SNP' do
end
it 'returns no more than 10 phenotypes for a SNP' do
end
end
describe 'update phenotypes' do
it 'updates phenotype_snp table if more than MAX_AGE old' do
end
end
end
| RSpec.describe LinkSnpPhenotype do
setup do
# might use 'build' if db transactions are not required
@snp = FactoryGirl.create(:snp)
@worker = LinkSnpPhenotype.new
@document = {
"uuid" => UUIDTools::UUID.random_create.to_s,
"title" => "Test Driven Development And Why You Should Do It",
"authors" => [{ "forename" => "Max", "surname" => "Mustermann" }],
"mendeley_url" => "http://example.com",
"year" => "2013",
"doi" => "456",
}
end
describe 'worker' do
after :each do
LinkSnpPhenotype.clear
end
it 'does nothing if snp does not exist' do
expect(@worker).not_to receive(:score_phenotype)
@worker.perform(0)
end
it 'enqueues a task if phenotype_updated is less than MAX_AGE' do
@snp.phenotype_updated = Time.now
@worker.perform(@snp.id)
expect(LinkSnpPhenotype.jobs).not_to be_empty
expect(LinkSnpPhenotype.jobs.first['args']).to include(@snp.id)
end
it 'has no jobs if phenotype_updated is more than MAX_AGE' do
@snp.phenotype_updated = 32.days.ago
@worker.perform(@snp.id)
expect(LinkSnpPhenotype.jobs).to be_empty
end
end
describe 'scoring' do
it 'returns no more than 10 phenotypes' do
out = @worker.score_phenotype(@snp)
expect(out.length).to be <= 10
end
it 'uses a consistent scoring scheme' do
end
end
end
|
Add Teams UD feature spec | require 'spec_helper.rb'
feature 'Creating editing and deleting a team', js: true do
let(:tournament1){ FactoryGirl::create(:tournament)}
let(:tournament2){ FactoryGirl::create(:tournament)}
let(:team1) { FactoryGirl::attributes_for(:team, tournament_id: tournament1.id)}
let(:team2) { FactoryGirl::attributes_for(:team, tournament_id: tournament2.id)}
let(:user) { FactoryGirl::create(:user) }
before do
visit "#/home"
visit "#/login"
fill_in "email", with: user.email
fill_in "password", with: user.password
click_on "log-in-button"
visit "#/home/"
end
scenario "Update a team when user exists and is a tournament admin", :raceable do
TournamentAdmin.create(user_id: user.id, tournament_id: tournament1.id, status: :main)
tournament2
t1 = Team.create(team1)
#TODO: when tournament IF is done, enter properly
visit "#/teams/" + t1.id.to_s
click_on "edit-team"
fill_in "name", with: team2[:name]
fill_in "required_size", with: team2[:required_size]
click_on "save-team"
expect(page).to have_content(team2[:name])
expect(page).to have_content(team2[:required_size])
end
scenario "Delete a team when user is a tournament admin" do
TournamentAdmin.create(user_id: user.id, tournament_id: tournament1.id, status: :main)
team = Team.create(team1)
visit "#/teams/" + team.id.to_s
click_on "delete-team"
expect(Team.exists?(id: team.id)).to be false
end
end
| |
Update gem dependencies, add version constraints | Gem::Specification.new do |s|
s.name = 'vagrant_cloud'
s.version = '0.2.1'
s.summary = 'Vagrant Cloud API wrapper'
s.description = 'Very minimalistic ruby wrapper for the Vagrant Cloud API'
s.authors = ['Cargo Media']
s.email = 'hello@cargomedia.ch'
s.files = Dir['LICENSE*', 'README*', '{bin,lib}/**/*']
s.homepage = 'https://github.com/cargomedia/vagrant_cloud'
s.license = 'MIT'
s.add_runtime_dependency 'rest_client'
s.add_development_dependency 'rake'
end
| Gem::Specification.new do |s|
s.name = 'vagrant_cloud'
s.version = '0.2.1'
s.summary = 'Vagrant Cloud API wrapper'
s.description = 'Very minimalistic ruby wrapper for the Vagrant Cloud API'
s.authors = ['Cargo Media']
s.email = 'hello@cargomedia.ch'
s.files = Dir['LICENSE*', 'README*', '{bin,lib}/**/*']
s.homepage = 'https://github.com/cargomedia/vagrant_cloud'
s.license = 'MIT'
s.add_runtime_dependency 'rest-client', '~>1.7'
s.add_development_dependency 'rake', '~>10.4'
end
|
Include fakefs in spec helper | $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'putkitin'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
RSpec.configure do |config|
end
| $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'putkitin'
require 'fakefs/safe'
require 'fakefs/spec_helpers'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
RSpec.configure do |config|
end
|
Remove reference to Rack::Deflate. Seems to blow up aganist production | module FrontendServer
module Rack
def app
server = self
builder = ::Rack::Builder.new
self.class.configurations.each do |configuration|
configuration.call builder, config
end
# builder.use ::Rack::Deflater
builder.use ReverseProxy do
reverse_proxy /^\/api(\/.*)$/, "#{server.config.server}$1"
end
builder.use ::Rack::Rewrite do
rewrite '/', '/index.html'
rewrite %r{^\/?[^\.]+\/?(\?.*)?$}, '/index.html$1'
end
if development?
builder.use Rake::Pipeline::Middleware, pipeline
end
if production?
builder.use ::Rack::ETag
builder.use ::Rack::ConditionalGet
end
builder.run ::Rack::Directory.new 'site'
builder.to_app
end
def call(env)
app.call(env)
end
end
end
| module FrontendServer
module Rack
def app
server = self
builder = ::Rack::Builder.new
self.class.configurations.each do |configuration|
configuration.call builder, config
end
builder.use ReverseProxy do
reverse_proxy /^\/api(\/.*)$/, "#{server.config.server}$1"
end
builder.use ::Rack::Rewrite do
rewrite '/', '/index.html'
rewrite %r{^\/?[^\.]+\/?(\?.*)?$}, '/index.html$1'
end
if development?
builder.use Rake::Pipeline::Middleware, pipeline
end
if production?
builder.use ::Rack::ETag
builder.use ::Rack::ConditionalGet
end
builder.run ::Rack::Directory.new 'site'
builder.to_app
end
def call(env)
app.call(env)
end
end
end
|
Update Test class definition to fix yardoc issue. | ##
# Test extension.
#
# Default implementation of http://shex.io/extensions/Test/
#
# @see http://shex.io/extensions/Test/
require 'shex'
class ShEx::Test < ShEx::Extension("http://shex.io/extensions/Test/")
# (see ShEx::Extension#visit)
def visit(code: nil, matched: nil, depth: 0, **options)
str = if md = /^ *(fail|print) *\( *(?:(\"(?:[^\\"]|\\")*\")|([spo])) *\) *$/.match(code.to_s)
md[2] || case md[3]
when 's' then matched.subject
when 'p' then matched.predicate
when 'o' then matched.object
else matched.to_sxp
end.to_s
else
matched ? matched.to_sxp : 'no statement'
end
$stdout.puts str
return !md || md[1] == 'print'
end
end | ##
# Test extension.
#
# Default implementation of http://shex.io/extensions/Test/
#
# @see http://shex.io/extensions/Test/
require 'shex'
module ShEx
Test = Class.new(ShEx::Extension("http://shex.io/extensions/Test/")) do
# (see ShEx::Extension#visit)
def visit(code: nil, matched: nil, depth: 0, **options)
str = if md = /^ *(fail|print) *\( *(?:(\"(?:[^\\"]|\\")*\")|([spo])) *\) *$/.match(code.to_s)
md[2] || case md[3]
when 's' then matched.subject
when 'p' then matched.predicate
when 'o' then matched.object
else matched.to_sxp
end.to_s
else
matched ? matched.to_sxp : 'no statement'
end
$stdout.puts str
return !md || md[1] == 'print'
end
end
end
|
Add Integration Spec for user sign up feature. | require 'rails_helper'
describe "the signin process", :type => :feature do
scenario 'with valid email and password' do
sign_up_with 'valid@example.com', 'password'
expect(page).to have_content('Sign out')
end
scenario 'with invalid email' do
sign_up_with 'invalid_email', 'password'
expect(page).to have_content('Sign in')
end
scenario 'with blank password' do
sign_up_with 'valid@example.com', ''
expect(page).to have_content('Sign in')
end
end | require 'rails_helper'
describe "the signin process", :type => :feature do
scenario 'with valid email and password' do
params = { username: 'some_user', firstname: 'Some', lastname: 'User',
birthdate: '09-11-1988', email: 'some_email@mail.com', phone: '6665773'
password: '12345', password_confirmation: '12345' }
sign_up_with(params)
expect(page).to have_content('Sign out')
end
scenario 'with invalid email' do
sign_up_with 'invalid_email', 'password'
expect(page).to have_content('Sign in')
end
scenario 'with blank password' do
sign_up_with 'valid@example.com', ''
expect(page).to have_content('Sign in')
end
def sign_up_with(params)
visit sign_up_path
fill_in 'Username', with: params[:username]
fill_in 'Firstname', with: params[:firstname]
fill_in 'Lastname', with: params[:lastname]
fill_in 'Birth Date', with: params[:birthdate]
fill_in 'Email', with: params[:email]
fill_in 'Phone', with: params[:phone]
fill_in 'Password', with: params[:password]
fill_in 'Password Confirmation', with: params[:password_confirmation]
click_button 'Sign up'
end
end |
Fix BP diastolic < systolic comparison where one is a string | # frozen_string_literal: true
module Renalware
module Patients
class BloodPressureValidator < ActiveModel::Validator
include NumericRangeValidations
MIN_VALUE = 20
MAX_VALUE = 300
def validate(bp)
apply_validations(bp) if bp.present?
end
private
def apply_validations(bp)
validate_number_is_in_range(bp, :systolic, bp.systolic, MIN_VALUE, MAX_VALUE)
validate_number_is_in_range(bp, :diastolic, bp.diastolic, MIN_VALUE, MAX_VALUE)
validate_diastolic_less_than_systolic(bp)
end
def validate_diastolic_less_than_systolic(bp)
errors = bp.errors
return if errors.any?
unless bp.diastolic < bp.systolic
errors.add(:diastolic, :must_be_less_than_systolic)
end
end
end
end
end
| # frozen_string_literal: true
module Renalware
module Patients
class BloodPressureValidator < ActiveModel::Validator
include NumericRangeValidations
MIN_VALUE = 20
MAX_VALUE = 300
def validate(bp)
apply_validations(bp) if bp.present?
end
private
def apply_validations(bp)
validate_number_is_in_range(bp, :systolic, bp.systolic, MIN_VALUE, MAX_VALUE)
validate_number_is_in_range(bp, :diastolic, bp.diastolic, MIN_VALUE, MAX_VALUE)
validate_diastolic_less_than_systolic(bp)
end
def validate_diastolic_less_than_systolic(bp)
errors = bp.errors
return if errors.any?
unless bp.diastolic.to_f < bp.systolic.to_f
errors.add(:diastolic, :must_be_less_than_systolic)
end
end
end
end
end
|
Fix error in .podspec file |
Pod::Spec.new do |s|
s.name = "SwiftSafe"
s.version = "0.1"
s.summary = "Thread synchronization made easy."
s.homepage = "https://github.com/czechboy0/SwiftSafe"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Honza Dvorsky" => "https://honzadvorsky.com" }
# s.social_media_url = "https://twitter.com/czechboy0"
s.ios.deployment_target = "8.0"
s.osx.deployment_target = "10.10"
s.watchos.deployment_target = "2.0"
s.tvos.deployment_target = "9.0"
s.source = { :git => "https://github.com/czechboy0/SwiftSafe.git", :tag => "v#{s.version}" }
s.source_files = "Safe/*.swift"
end
|
Pod::Spec.new do |s|
s.name = "SwiftSafe"
s.version = "2.0.0"
s.summary = "Thread synchronization made easy."
s.homepage = "https://github.com/nodes-ios/SwiftSafe"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Honza Dvorsky" => "https://honzadvorsky.com" }
# s.social_media_url = "https://twitter.com/czechboy0"
s.ios.deployment_target = "8.0"
s.osx.deployment_target = "10.10"
s.watchos.deployment_target = "2.0"
s.tvos.deployment_target = "9.0"
s.source = { :git => "https://github.com/nodes-ios/SwiftSafe.git", :tag => "#{s.version}" }
s.source_files = "Safe/*.swift"
end
|
Fix author information to use ttlab account | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ajw2/version'
Gem::Specification.new do |spec|
spec.name = "ajw2"
spec.version = Ajw2::VERSION
spec.authors = ["dtan4"]
spec.email = ["dtanshi45@gmail.com"]
spec.summary = %q{TODO: Write a short summary. Required.}
spec.description = %q{TODO: Write a longer description. Optional.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "activesupport"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_development_dependency "guard-rspec"
spec.add_development_dependency "simplecov"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ajw2/version'
Gem::Specification.new do |spec|
spec.name = "ajw2"
spec.version = Ajw2::VERSION
spec.authors = ["fujita"]
spec.email = ["fujita@tt.cs.titech.ac.jp"]
spec.summary = %q{TODO: Write a short summary. Required.}
spec.description = %q{TODO: Write a longer description. Optional.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "activesupport"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_development_dependency "guard-rspec"
spec.add_development_dependency "simplecov"
end
|
Add a note for request.domain and request.subdomain | class SitePostsController < ApplicationController
before_action :setup_site
layout 'site_posts'
def index
@posts = @site.posts
end
def show
@post = @site.posts.find(params[:id])
end
private
def setup_site
@site = Site.find(site_id)
end
def site_id
case env['SERVER_NAME']
when /\Asite1\./
1
when /\Asite2\./
2
else
params[:site_id]
end
end
end
| class SitePostsController < ApplicationController
before_action :setup_site
layout 'site_posts'
def index
@posts = @site.posts
end
def show
@post = @site.posts.find(params[:id])
end
private
def setup_site
@site = Site.find(site_id)
end
def site_id
# NOTE: env['SERVER_NAME'] よりも、 request.domain や
# request.subdomain のほうがいいかもしれない。
# 例: http://site1.lvh.me/ の場合
# * env['SERVER_NAME'] #=> site1.lvh.me
# * request.domain #=> lvh.me
# * request.subdomain #=> site1
case env['SERVER_NAME']
when /\Asite1\./
1
when /\Asite2\./
2
else
params[:site_id]
end
end
end
|
Fix prover factory trying to create duplicate. | FactoryGirl.define do
sequence :prover_name do |n|
"prover-#{n}"
end
factory :prover do
name { 'SPASS' }
display_name { 'SPASS Prover' }
trait :with_sequenced_name do
after(:build) do |prover|
prover.name = generate :prover_name
prover.display_name = prover.name.sub('-', ' ')
end
end
end
end
| FactoryGirl.define do
sequence :prover_name do |n|
"prover-#{n}"
end
factory :prover do
name { 'SPASS' }
display_name { 'SPASS Prover' }
initialize_with do
Prover.find_by_name(name) || Prover.new(name: name)
end
trait :with_sequenced_name do
after(:build) do |prover|
prover.name = generate :prover_name
prover.display_name = prover.name.sub('-', ' ')
end
end
end
end
|
Add spec to confirm Python command exist on PATH. | require "spec_helper_#{ENV['SPEC_TARGET_BACKEND']}"
describe package('python-apt'), :if => os[:family] == 'debian' do
it { should be_installed }
end
describe package('python-dev'), :if => os[:family] == 'debian' do
it { should be_installed }
end
describe package('build-essential'), :if => os[:family] == 'debian' do
it { should be_installed }
end
| require "spec_helper_#{ENV['SPEC_TARGET_BACKEND']}"
describe package('python-apt'), :if => os[:family] == 'debian' do
it { should be_installed }
end
describe package('python-dev'), :if => os[:family] == 'debian' do
it { should be_installed }
end
describe package('build-essential'), :if => os[:family] == 'debian' do
it { should be_installed }
end
describe command('which python') do
its(:exit_status) { should eq 0 }
end
|
Make sure Typus::I18n.available_locales returns a Hash | require "test_helper"
class I18nTest < ActiveSupport::TestCase
test "t" do
assert_equal "Missing Translation", Typus::I18n.t("Missing Translation")
end
test "default_locale" do
assert_equal :en, Typus::I18n.default_locale
end
end
| require "test_helper"
class I18nTest < ActiveSupport::TestCase
test "t" do
assert_equal "Missing Translation", Typus::I18n.t("Missing Translation")
end
test "default_locale" do
assert_equal :en, Typus::I18n.default_locale
end
test "available_locales" do
assert Typus::I18n.available_locales.is_a?(Hash)
end
end
|
Fix xml to json converting (root tag) | module Converters
class XmlJson
attr_accessor :settings
def initialize(opts = nil)
@settings = {
mode: 'pretty',
}.merge(opts || {})
end
def xml_to_json(xml)
doc = Nokogiri::XML.parse(xml)
hash = Hash.from_xml(doc.to_xml(settings))
case settings[:mode]
when 'pretty'
JSON.pretty_generate(hash)
when 'one_line'
hash.to_json
else
raise 'unsupported output mode'
end
end
def json_to_xml(json)
hash = JSON.parse(json)
root = hash.keys.first
hash_for_xml = hash[root]
# TODO: implement array conversion as elements sequence without extra surrounding tag
# TODO: implement xml attributes
case settings[:mode]
when 'pretty'
hash_for_xml.to_xml(:root => root, :skip_types => true)
when 'one_line'
hash_for_xml.to_xml(:root => root, :skip_types => true, indent: 0)
else
raise 'unsupported output mode'
end
end
end
end | module Converters
class XmlJson
attr_accessor :settings
def initialize(opts = nil)
@settings = {
mode: 'pretty',
}.merge(opts || {})
end
def xml_to_json(xml)
doc = Nokogiri::XML.parse(xml)
hash = Hash.from_xml(doc.to_xml(settings))
case settings[:mode]
when 'pretty'
JSON.pretty_generate(hash)
when 'one_line'
hash.to_json
else
raise 'unsupported output mode'
end
end
def json_to_xml(json)
hash_for_xml = JSON.parse(json)
root = 'json'
# TODO: implement array conversion as elements sequence without extra surrounding tag
# TODO: implement xml attributes
case settings[:mode]
when 'pretty'
hash_for_xml.to_xml(:root => root, :skip_types => true)
when 'one_line'
hash_for_xml.to_xml(:root => root, :skip_types => true, indent: 0)
else
raise 'unsupported output mode'
end
end
end
end |
Fix test: threads being nil in ensure | # frozen_string_literal: true
module ConnectionPoolBehavior
def test_connection_pool
Thread.report_on_exception, original_report_on_exception = false, Thread.report_on_exception
emulating_latency do
begin
cache = ActiveSupport::Cache.lookup_store(store, { pool_size: 2, pool_timeout: 1 }.merge(store_options))
cache.clear
threads = []
assert_raises Timeout::Error do
# One of the three threads will fail in 1 second because our pool size
# is only two.
3.times do
threads << Thread.new do
cache.read("latency")
end
end
threads.each(&:join)
end
ensure
threads.each(&:kill)
end
end
ensure
Thread.report_on_exception = original_report_on_exception
end
def test_no_connection_pool
emulating_latency do
begin
cache = ActiveSupport::Cache.lookup_store(store, store_options)
cache.clear
threads = []
assert_nothing_raised do
# Default connection pool size is 5, assuming 10 will make sure that
# the connection pool isn't used at all.
10.times do
threads << Thread.new do
cache.read("latency")
end
end
threads.each(&:join)
end
ensure
threads.each(&:kill)
end
end
end
private
def store_options; {}; end
end
| # frozen_string_literal: true
module ConnectionPoolBehavior
def test_connection_pool
Thread.report_on_exception, original_report_on_exception = false, Thread.report_on_exception
threads = []
emulating_latency do
begin
cache = ActiveSupport::Cache.lookup_store(store, { pool_size: 2, pool_timeout: 1 }.merge(store_options))
cache.clear
assert_raises Timeout::Error do
# One of the three threads will fail in 1 second because our pool size
# is only two.
3.times do
threads << Thread.new do
cache.read("latency")
end
end
threads.each(&:join)
end
ensure
threads.each(&:kill)
end
end
ensure
Thread.report_on_exception = original_report_on_exception
end
def test_no_connection_pool
threads = []
emulating_latency do
begin
cache = ActiveSupport::Cache.lookup_store(store, store_options)
cache.clear
assert_nothing_raised do
# Default connection pool size is 5, assuming 10 will make sure that
# the connection pool isn't used at all.
10.times do
threads << Thread.new do
cache.read("latency")
end
end
threads.each(&:join)
end
ensure
threads.each(&:kill)
end
end
end
private
def store_options; {}; end
end
|
Add test for view helper Livereload script output | require "test_helper"
class LivereloadTest < TestCase
test "#livereload_script has correct output" do
output = new_renderer.livereload_script(force: true)
assert_equal(%{<script>document.write('<script src="http://' + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1"></' + 'script>')</script>}, output)
end
private
def new_renderer
renderer = Object.new
renderer.extend(Munge::Helpers::Tag)
renderer.extend(Munge::Helpers::Livereload)
renderer
end
end
| |
Fix breaking Setting object after loading this plugin. | module Pwfmt::SettingPatch
extend ActiveSupport::Concern
included do
after_save :persist_wiki_format
end
def persist_wiki_format
PwfmtFormat.persist(self, 'settings_welcome_text')
end
end
require 'setting'
Setting.__send__(:include, Pwfmt::SettingPatch)
| module Pwfmt::SettingPatch
extend ActiveSupport::Concern
included do
after_save :persist_wiki_format
end
def persist_wiki_format
PwfmtFormat.persist(self, 'settings_welcome_text')
end
end
Rails.configuration.to_prepare do
require 'setting'
Setting.__send__(:include, Pwfmt::SettingPatch)
end
|
Make the version number static | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "seasoning/version"
Gem::Specification.new do |s|
s.name = "seasoning"
s.version = Seasoning::VERSION
s.authors = ["Aaron Kalin"]
s.email = ["akalin@martinisoftware.com"]
s.homepage = "http://github.com/martinisoft/seasoning"
s.summary = %q{Updates your Rails App Pepper for Enhanced Security}
s.description = %q{A Rails 3 generator to update your existing authentication peppers for additional security.}
s.rubyforge_project = "seasoning"
s.add_dependency "active_support", "~> 3.0.0"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "seasoning"
s.version = "0.1.1"
s.authors = ["Aaron Kalin"]
s.email = ["akalin@martinisoftware.com"]
s.homepage = "http://github.com/martinisoft/seasoning"
s.summary = %q{Updates your Rails App Pepper for Enhanced Security}
s.description = %q{A Rails 3 generator to update your existing authentication peppers for additional security.}
s.rubyforge_project = "seasoning"
s.add_dependency "active_support", "~> 3.0.0"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
|
Remove printout from isolated environment spec. | # encoding: utf-8
require 'spec_helper'
describe 'isolated environment', :isolated_environment do
include FileHelper
let(:cli) { Rubocop::CLI.new }
# Configuration files above the work directory shall not disturb the
# tests. This is especially important on Windows where the temporary
# directory is under the user's home directory. On any platform we don't want
# a .rubocop.yml file in the temporary directory to affect the outcome of
# rspec.
it 'is not affected by a config file above the work directory' do
create_file('../.rubocop.yml', ['inherit_from: missing_file.yml'])
create_file('ex.rb', ['# encoding: utf-8'])
# A return value of 0 means that the erroneous config file was not read.
expect(cli.run([])).to eq(0)
end
end
| # encoding: utf-8
require 'spec_helper'
describe 'isolated environment', :isolated_environment do
include FileHelper
let(:cli) { Rubocop::CLI.new }
before(:each) { $stdout = StringIO.new }
after(:each) { $stdout = STDOUT }
# Configuration files above the work directory shall not disturb the
# tests. This is especially important on Windows where the temporary
# directory is under the user's home directory. On any platform we don't want
# a .rubocop.yml file in the temporary directory to affect the outcome of
# rspec.
it 'is not affected by a config file above the work directory' do
create_file('../.rubocop.yml', ['inherit_from: missing_file.yml'])
create_file('ex.rb', ['# encoding: utf-8'])
# A return value of 0 means that the erroneous config file was not read.
expect(cli.run([])).to eq(0)
end
end
|
Remove --enable-sse2 and --disable-debug flags | require 'formula'
class Tarsnap < Formula
url 'https://www.tarsnap.com/download/tarsnap-autoconf-1.0.29.tgz'
homepage 'http://www.tarsnap.com/'
sha256 '747510459e4af0ebbb6e267c159aa019f9337d1e07bd9a94f1aa1498081b7598'
depends_on 'lzma' => :optional
def install
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--enable-sse2"
system "make install"
end
end
| require 'formula'
class Tarsnap < Formula
url 'https://www.tarsnap.com/download/tarsnap-autoconf-1.0.29.tgz'
homepage 'http://www.tarsnap.com/'
sha256 '747510459e4af0ebbb6e267c159aa019f9337d1e07bd9a94f1aa1498081b7598'
depends_on 'lzma' => :optional
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make install"
end
end
|
Change super base controller to ActionController::Base | class Ckeditor::ApplicationController < ::ApplicationController
respond_to :html, :json
layout 'ckeditor/application'
before_filter :find_asset, :only => [:destroy]
before_filter :ckeditor_authorize!
before_filter :authorize_resource
protected
def respond_with_asset(asset)
file = params[:CKEditor].blank? ? params[:qqfile] : params[:upload]
asset.data = Ckeditor::Http.normalize_param(file, request)
callback = ckeditor_before_create_asset(asset)
if callback && asset.save
body = params[:CKEditor].blank? ? asset.to_json(:only=>[:id, :type]) : %Q"<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(#{params[:CKEditorFuncNum]}, '#{config.relative_url_root}#{Ckeditor::Utils.escape_single_quotes(asset.url_content)}');
</script>"
render :text => body
else
render :nothing => true
end
end
end
| class Ckeditor::ApplicationController < ActionController::Base
respond_to :html, :json
layout 'ckeditor/application'
before_filter :find_asset, :only => [:destroy]
before_filter :ckeditor_authorize!
before_filter :authorize_resource
protected
def respond_with_asset(asset)
file = params[:CKEditor].blank? ? params[:qqfile] : params[:upload]
asset.data = Ckeditor::Http.normalize_param(file, request)
callback = ckeditor_before_create_asset(asset)
if callback && asset.save
body = params[:CKEditor].blank? ? asset.to_json(:only=>[:id, :type]) : %Q"<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(#{params[:CKEditorFuncNum]}, '#{config.relative_url_root}#{Ckeditor::Utils.escape_single_quotes(asset.url_content)}');
</script>"
render :text => body
else
render :nothing => true
end
end
end
|
Update homepage url in gemspec | require File.expand_path("../lib/l2meter/version", __FILE__)
Gem::Specification.new do |spec|
spec.name = "l2meter"
spec.version = L2meter::VERSION
spec.authors = ["Pavel Pravosud"]
spec.email = ["pavel@pravosud.com"]
spec.summary = "L2met friendly log formatter"
spec.homepage = "https://github.com/rwz/l2meter"
spec.license = "MIT"
spec.files = Dir["LICENSE.txt", "README.md", "lib/**/**"]
spec.require_path = "lib"
end
| require File.expand_path("../lib/l2meter/version", __FILE__)
Gem::Specification.new do |spec|
spec.name = "l2meter"
spec.version = L2meter::VERSION
spec.authors = ["Pavel Pravosud"]
spec.email = ["pavel@pravosud.com"]
spec.summary = "L2met friendly log formatter"
spec.homepage = "https://github.com/heroku/l2meter"
spec.license = "MIT"
spec.files = Dir["LICENSE.txt", "README.md", "lib/**/**"]
spec.require_path = "lib"
end
|
Add range_date method to Datatable form builder | module EasyAPP
class SearchFormBuilder < BootstrapForm::FormBuilder
def initialize(object_name, object, template, options)
@datatable = options[:datatable]
super
end
def search_field(name, opts = {})
opts = opts.merge(filter_type: 'text', filter_container_id: name)
escape_strings = opts.delete(:escape_strings){ [] }
@datatable.escape_strings(escape_strings)
@datatable.search_field(opts)
content_tag(:div, '', id: name)
end
def select(name, opts = {})
opts = opts.deep_merge(filter_type: 'select')
select_field(name, opts)
end
def multi_select(name, opts = {})
opts = opts.deep_merge(filter_type: 'multi_select')
select_field(name, opts)
end
def render_datatable
@datatable.render_datatable
end
private
def select_field(name, opts = {})
escape_strings = opts.delete(:escape_strings){ [] }
opts = opts.deep_merge(filter_container_id: name, select_type: 'select2')
@datatable.escape_strings(escape_strings)
@datatable.search_field(opts)
content_tag(:div, '', id: name)
end
end
end
| module EasyAPP
class SearchFormBuilder < BootstrapForm::FormBuilder
def initialize(object_name, object, template, options)
@datatable = options[:datatable]
super
end
def search_field(name, opts = {})
opts = opts.merge(filter_type: 'text', filter_container_id: name)
escape_strings = opts.delete(:escape_strings){ [] }
@datatable.escape_strings(escape_strings)
@datatable.search_field(opts)
content_tag(:div, '', id: name)
end
def select(name, opts = {})
opts = opts.deep_merge(filter_type: 'select')
select_field(name, opts)
end
def multi_select(name, opts = {})
opts = opts.deep_merge(filter_type: 'multi_select')
select_field(name, opts)
end
def range_date(name, opts = {})
opts = opts.merge(filter_type: 'range_date', filter_container_id: name)
@datatable.search_field(opts)
content_tag(:div, '', id: name)
end
def render_datatable
@datatable.render_datatable
end
private
def select_field(name, opts = {})
escape_strings = opts.delete(:escape_strings){ [] }
opts = opts.deep_merge(filter_container_id: name, select_type: 'select2')
@datatable.escape_strings(escape_strings)
@datatable.search_field(opts)
content_tag(:div, '', id: name)
end
end
end
|
Add host_services Method for Version11 | module ManageEngine
module AppManager
module Api
class Version11
attr_reader :connect_path
###########################
# URL Response Methods
###########################
def connect_path
"/AppManager/xml/ListDashboards?apikey=%{api_key}"
end
def host_path
"/AppManager/xml/ListServer?apikey=%{api_key}&type=%{type}"
end
###########################
# Processing Methods
###########################
def connect_response_valid?(response)
doc = Nokogiri::XML response
status = doc.xpath("/AppManager-response/result/response")
return (!status[0].nil? and status[0].attr("response-code") == "4000")
end
def hosts_services(response)
host_services_list = Hash.new
doc = Nokogiri::XML response
doc.xpath("/AppManager-response/result/response/Server").each do |server_xml|
(host_services_list[server_xml.attr("Name")] = Array.new).tap do |server_monitors|
server_xml.xpath("./Service").each_with_index do |service_xml, i|
server_monitors.push service_xml.attr("TYPE")
end
end
end
host_services_list
end
def hosts(response)
self.hosts_services(response).keys
end
end
end
end
end
| module ManageEngine
module AppManager
module Api
class Version11
attr_reader :connect_path
###########################
# URL Response Methods
###########################
def connect_path
"/AppManager/xml/ListDashboards?apikey=%{api_key}"
end
def host_path
"/AppManager/xml/ListServer?apikey=%{api_key}&type=%{type}"
end
###########################
# Processing Methods
###########################
def connect_response_valid?(response)
doc = Nokogiri::XML response
status = doc.xpath("/AppManager-response/result/response")
return (!status[0].nil? and status[0].attr("response-code") == "4000")
end
def hosts_services(response)
host_services_list = Hash.new
doc = Nokogiri::XML response
doc.xpath("/AppManager-response/result/response/Server").each do |server_xml|
(host_services_list[server_xml.attr("Name")] = Array.new).tap do |server_monitors|
server_xml.xpath("./Service").each_with_index do |service_xml, i|
server_monitors.push service_xml.attr("TYPE")
end
end
end
host_services_list
end
def hosts(response)
self.hosts_services(response).keys
end
def host_services(host, response)
host_service_hash = self.hosts_services(response)
raise "No Hosts Being Monitored" if host_service_hash.empty?
raise "Non-Monitored Host: #{host}" if (host_hash = host_service_hash[host]).empty?
host_hash.uniq
end
end
end
end
end
|
Add indifferent access to hash response | require 'rest-client'
require 'json'
module Polr
API_VERSION = 'v2'
Error = Class.new StandardError
module Api
def self.api_url path = nil
%Q(#{Polr.configuration.api_url}/api/#{API_VERSION}/action/#{path})
end
def self.api_key
Polr.configuration.api_key
end
def self.process
JSON.parse yield
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH => e # API unreachable
raise Polr::Error.new 'Polr API is unreachable'
rescue RestClient::Exception => e # HTTP status error
result = (JSON.parse(e.response) rescue {})
raise Polr::Error.new(result['error'] || 'undefined error')
rescue JSON::ParserError => e # JSON error
raise Polr::Error.new e.message
end
def self.request path, params
RestClient.get( Api::api_url(path.to_s), { params: params.merge(key: Api::api_key, response_type: :json), content_type: :json, accept: :json, timeout: 10 } )
end
end
# Actions to use
def self.shorten url, **options
Api::process { Api::request(:shorten, { url: url }.merge(options)) }
end
def self.lookup url_ending, **options
Api::process { Api::request(:lookup, { url_ending: url_ending }.merge(options)) }
end
end
| require 'rest-client'
require 'json'
module Polr
API_VERSION = 'v2'
Error = Class.new StandardError
module Api
def self.api_url path = nil
%Q(#{Polr.configuration.api_url}/api/#{API_VERSION}/action/#{path})
end
def self.api_key
Polr.configuration.api_key
end
def self.process
JSON.parse(yield).with_indifferent_access
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH => e # API unreachable
raise Polr::Error.new 'Polr API is unreachable'
rescue RestClient::Exception => e # HTTP status error
result = (JSON.parse(e.response) rescue {})
raise Polr::Error.new(result['error'] || 'undefined error')
rescue JSON::ParserError => e # JSON error
raise Polr::Error.new e.message
end
def self.request path, params
RestClient.get( Api::api_url(path.to_s), { params: params.merge(key: Api::api_key, response_type: :json), content_type: :json, accept: :json, timeout: 10 } )
end
end
# Actions to use
def self.shorten url, **options
Api::process { Api::request(:shorten, { url: url }.merge(options)) }
end
def self.lookup url_ending, **options
Api::process { Api::request(:lookup, { url_ending: url_ending }.merge(options)) }
end
end
|
Edit 4.7.2 add it up | # Add it up!
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented in the file.
# I worked on this challenge [by myself, ].
# 0. total Pseudocode
# make sure all pseudocode is commented out!
# Input: array of [numbers]
# Output: sum of all the numbers (sum)
# Steps to solve the problem.
# 1) take input and define
# 2) take each number within the array and add each together
# 3) return output
# 1. total initial solution
def total(array)
array = [0]
array.each do |i|
total += i
end
end
#array.each do |i|
# sum += [i]
# 3. total refactored solution
# 4. sentence_maker pseudocode
# make sure all pseudocode is commented out!
# Input:
# Output:
# Steps to solve the problem.
# 5. sentence_maker initial solution
# 6. sentence_maker refactored solution
| # Add it up!
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented in the file.
# I worked on this challenge [by myself, ].
# 0. total Pseudocode
# make sure all pseudocode is commented out!
# Input: array of [numbers]
# Output: sum of all the numbers (sum)
# Steps to solve the problem.
# define total as 0
# take each element in the argument to the method and add them together
# return sum
# 1. total initial solution
def total(array)
total = 0
array.each { |arr| total += arr }
return total
end
#array.each do |i|
# sum += [i]
# 3. total refactored solution
# 4. sentence_maker pseudocode
# make sure all pseudocode is commented out!
# Input:
# Output:
# Steps to solve the problem.
# 5. sentence_maker initial solution
# 6. sentence_maker refactored solution
|
Replace tests have_entry with a test with stub | require 'unit/spec_helper'
module Infrataster
# Infrataster contexts
module Contexts
describe DnsContext do
subject { described_class.new(nil, nil).public_methods }
it 'should have `have_entry` method' do
is_expected.to include(:have_entry)
end
it 'should have `have_dns` method from rspec-dns' do
is_expected.to include(:have_dns)
end
end
end
end
| require 'unit/spec_helper'
module Infrataster
# Infrataster contexts
module Contexts
describe DnsContext do
let(:server) { Server.new('ns.example.com', '192.168.33.10', :dns) }
subject { described_class.new(server, nil) }
it 'should have `have_entry` method' do
matcher = double('matcher')
allow(matcher).to receive(:config)
allow(subject).to receive(:have_dns).and_return(matcher)
subject.have_entry
end
end
end
end
|
Make the dummy gem valid by giving it a summary | Gem::Specification.new do |s|
s.name = 'pre_commit_dummy_package'
s.version = '0.0.0'
s.authors = ['Anthony Sottile']
end
| Gem::Specification.new do |s|
s.name = 'pre_commit_dummy_package'
s.version = '0.0.0'
s.summary = 'dummy gem for pre-commit hooks'
s.authors = ['Anthony Sottile']
end
|
Upgrade podspec to iOS 9.0 to avoid missing methods | Pod::Spec.new do |s|
s.name = "YouboraLib"
s.version = "6.2.5"
# Metadata
s.summary = "Library required by Youbora plugins"
s.description = "<<-DESC
YouboraLib is a library created by Nice People at Work. It serves
as the shared logic for all Youbora plugins and it also allows you
to create your own plugins.
DESC"
s.homepage = "http://developer.nicepeopleatwork.com/"
s.license = { :type => "MIT", :file => "LICENSE.md" }
s.author = { "Nice People at Work" => "support@nicepeopleatwork.com" }
# Platforms
s.ios.deployment_target = "8.0"
s.tvos.deployment_target = "9.0"
# Source Location
s.source = { :git => 'https://bitbucket.org/npaw/lib-plugin-ios.git', :tag => s.version}
# Source files
s.source_files = 'YouboraLib/**/*.{h,m}'
s.public_header_files = "YouboraLib/**/*.h"
# Project settings
s.requires_arc = true
s.pod_target_xcconfig = { 'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) YOUBORALIB_VERSION=' + s.version.to_s }
end
| Pod::Spec.new do |s|
s.name = "YouboraLib"
s.version = "6.2.5"
# Metadata
s.summary = "Library required by Youbora plugins"
s.description = "<<-DESC
YouboraLib is a library created by Nice People at Work. It serves
as the shared logic for all Youbora plugins and it also allows you
to create your own plugins.
DESC"
s.homepage = "http://developer.nicepeopleatwork.com/"
s.license = { :type => "MIT", :file => "LICENSE.md" }
s.author = { "Nice People at Work" => "support@nicepeopleatwork.com" }
# Platforms
s.ios.deployment_target = "9.0"
s.tvos.deployment_target = "9.0"
# Source Location
s.source = { :git => 'https://bitbucket.org/npaw/lib-plugin-ios.git', :tag => s.version}
# Source files
s.source_files = 'YouboraLib/**/*.{h,m}'
s.public_header_files = "YouboraLib/**/*.h"
# Project settings
s.requires_arc = true
s.pod_target_xcconfig = { 'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) YOUBORALIB_VERSION=' + s.version.to_s }
end
|
Add prompt to capture tester report when failing | Then(/^.*$/) do
Cucumber.trap_interrupt
key = capture_key
fail unless pass?(key)
end
| Then(/^.*$/) do
Cucumber.trap_interrupt
key = capture_key
unless pass?(key)
print "\nDescribe the problem:\n"
puts "Notes: " + STDIN.gets.chomp
fail
end
end
|
Add missing stanzas to Adium Beta | cask :v1 => 'adium-beta' do
version '1.5.11b2'
sha256 'e7690718f14defa3bc08cd3949a4eab52e942abd47f7ac2ce7157ed7295658c6'
url "https://adiumx.cachefly.net/Adium_#{version}.dmg"
homepage 'https://beta.adium.im/'
license :oss
app 'Adium.app'
end
| cask :v1 => 'adium-beta' do
version '1.5.11b2'
sha256 'e7690718f14defa3bc08cd3949a4eab52e942abd47f7ac2ce7157ed7295658c6'
url "https://adiumx.cachefly.net/Adium_#{version}.dmg"
name 'Adium'
homepage 'https://beta.adium.im/'
license :gpl
app 'Adium.app'
zap :delete => [
'~/Library/Caches/Adium',
'~/Library/Caches/com.adiumX.adiumX',
'~/Library/Preferences/com.adiumX.adiumX.plist',
]
end
|
Make CircuitBreaker rely on ConsecutiveFailuresBasedHealth by default | module Gracefully
class CircuitBreaker
attr_reader :opened_date
def initialize(*args)
if args.size > 0
options = args.first
@try_close_after = options[:try_close_after]
end
@closed = true
end
def execute(&block)
if open? && (@try_close_after.nil? || try_close_period_passed?.!)
raise CurrentlyOpenError, "Opened at #{opened_date}"
end
clear_opened_date!
begin
v = block.call
mark_success
v
rescue => e
mark_failure
raise e
end
end
def mark_success
close!
end
def mark_failure
open!
end
def open?
closed?.!
end
def closed?
@closed
end
def try_close_period_passed?
opened_date && opened_date + @try_close_after < Time.now
end
def opened_date
@opened_date
end
def close!
@closed = true
end
def open!
@closed = false
@opened_date = Time.now
end
private
def clear_opened_date!
@opened_date = nil
end
class CurrentlyOpenError < StandardError
end
end
end
| module Gracefully
class CircuitBreaker
attr_reader :opened_date
def initialize(*args)
if args.size > 0
options = args.first
@try_close_after = options[:try_close_after]
end
@closed = true
@health = options && options[:health] || Gracefully::ConsecutiveFailuresBasedHealth.new(become_unhealthy_after_consecutive_failures: 0)
end
def execute(&block)
if open? && (@try_close_after.nil? || try_close_period_passed?.!)
raise CurrentlyOpenError, "Opened at #{opened_date}"
end
clear_opened_date!
begin
v = block.call
mark_success
v
rescue => e
mark_failure
raise e
end
end
def mark_success
@health.mark_success
update!
end
def mark_failure
@health.mark_failure
update!
end
def open?
closed?.!
end
def closed?
@closed
end
def try_close_period_passed?
opened_date && opened_date + @try_close_after < Time.now
end
def opened_date
@opened_date
end
def update!
if @health.healthy?
close!
else
open!
end
end
def close!
@closed = true
end
def open!
@closed = false
@opened_date = Time.now
end
private
def clear_opened_date!
@opened_date = nil
end
class CurrentlyOpenError < StandardError
end
end
end
|
Fix test failure do to missing YAML constant | require 'open-uri'
class Spice
attr_accessor :name
def initialize(name)
self.name = name
end
def ingredients
recipe = open("https://raw.github.com/hashrocket/spices/master/#{name}/spice.yml")
YAML.parse(recipe).to_ruby[name].map do |info|
Ingredient.new(name, info['source'], info['rails'])
end
end
def add_ingredients
ingredients.each do |ingredient|
ingredient.add
end
end
def display_usage
Spicerack::Usage.new(self.name).display_message
end
end
| require 'open-uri'
require 'yaml'
class Spice
attr_accessor :name
def initialize(name)
self.name = name
end
def ingredients
recipe = open("https://raw.github.com/hashrocket/spices/master/#{name}/spice.yml")
YAML.parse(recipe).to_ruby[name].map do |info|
Ingredient.new(name, info['source'], info['rails'])
end
end
def add_ingredients
ingredients.each do |ingredient|
ingredient.add
end
end
def display_usage
Spicerack::Usage.new(self.name).display_message
end
end
|
Fix default setting for styles | # encoding: utf-8
module Sass::Script::Functions
def settings_style(setting)
assert_type setting, :String
return_value = ActiveRecord::Base.connection.table_exists?('settings') ? Setting["#{ setting.value }"].to_s : Constant["#{ setting.value }"].to_s
Sass::Script::Parser.parse(return_value, 0, 0)
end
declare :settings_style, args: [:setting]
end
| # encoding: utf-8
module Sass::Script::Functions
def settings_style(setting)
assert_type setting, :String
return_value = ActiveRecord::Base.connection.table_exists?('settings') ? Setting["#{ setting.value }"].to_s : Constant["#{ setting.value }"]
Sass::Script::Parser.parse(return_value, 0, 0)
end
declare :settings_style, args: [:setting]
end
|
Enable auto traversal for full results list | class User < ActiveRecord::Base
has_many :access_tokens, dependent: :delete_all
has_many :reminders, dependent: :delete_all
# Public: Find or create user from github payload
#
# data - user hash returned from github
# :email - github user email (required)
# :name - github user name (required)
# :username - github user login (optional)
def self.find_or_create_from_github(data)
user = User.where(email: data[:email]).first ||
User.new(email: data[:email])
if user.name != data[:name]
user.name = data[:name]
end
if data[:username] && user.username != data[:username]
user.username = data[:username]
end
user.save! if user.changed?
user
end
def access_token
access_tokens.first || access_tokens.create
end
def github
Octokit::Client.new(:login => username, :oauth_token => github_access_token)
end
def permissions(repo_name)
Rails.cache.fetch(expires_in: 1.day) do
github.repository(repo_name).permissions
end
end
end
| class User < ActiveRecord::Base
has_many :access_tokens, dependent: :delete_all
has_many :reminders, dependent: :delete_all
# Public: Find or create user from github payload
#
# data - user hash returned from github
# :email - github user email (required)
# :name - github user name (required)
# :username - github user login (optional)
def self.find_or_create_from_github(data)
user = User.where(email: data[:email]).first ||
User.new(email: data[:email])
if user.name != data[:name]
user.name = data[:name]
end
if data[:username] && user.username != data[:username]
user.username = data[:username]
end
user.save! if user.changed?
user
end
def access_token
access_tokens.first || access_tokens.create
end
def github
Octokit::Client.new(:login => username, :oauth_token => github_access_token, :auto_traversal => true)
end
def permissions(repo_name)
Rails.cache.fetch(expires_in: 1.day) do
github.repository(repo_name).permissions
end
end
end
|
Fix post mailer class name | class GameMailer < ActionMailer::Base
default from: "uro@fantasygame.pl"
def notify_user(user, post)
@user = user
@post = post
@game = post.game
@campaign = game.campaign
mail(to: @user.email, subject: "There is new post in #{@campaign.name} : #{@game.name}")
end
end
| class PostMailer < ActionMailer::Base
default from: "uro@fantasygame.pl"
def notify_user(user, post)
@user = user
@post = post
@game = post.game
@campaign = game.campaign
mail(to: @user.email, subject: "There is new post in #{@campaign.name} : #{@game.name}")
end
end
|
Move the credits for the timestamp function into its section-header comment | #
# Ruby functions
#
# @author 'Hopper' <http://stackoverflow.com/users/1026353/hopper>
# @link http://stackoverflow.com/questions/13022461/add-timestamps-to-compiled-sass-scss
#
# =============================================================================
# Timestamp function
# =============================================================================
module Sass::Script::Functions
def timestamp()
return Sass::Script::String.new(Time.now.to_s)
end
end | #
# Ruby functions
#
# =============================================================================
# Timestamp function
#
# @author 'Hopper' <http://stackoverflow.com/users/1026353/hopper>
# @link http://stackoverflow.com/questions/13022461/add-timestamps-to-compiled-sass-scss
# =============================================================================
module Sass::Script::Functions
def timestamp()
return Sass::Script::String.new(Time.now.to_s)
end
end |
Add a recipe that cleans up ACLs for those who did the "add clients to admins group" thing | # Remove clients from the admins group
chef_group 'admins' do
remove_groups 'clients'
end
valid_nodes = search(:node, '*:*').map { |node| node.name }
search(:client, '*:*').each do |c|
if valid_nodes.include?(c.name)
# Check whether the user exists
begin
api = Cheffish.chef_server_api
api.get("#{api.root_url}/users/#{c.name}").inspect
rescue Net::HTTPServerException => e
if e.response.code == '404'
puts "Response #{e.response.code} for #{c.name}"
# If the user does NOT exist, we can just add the client to the acl
chef_acl "nodes/#{c.name}" do
rights [ :read, :update ], clients: [ c.name ]
end
next
end
end
# We will only get here if the user DOES exist. We are going to have a
# conflict between the user and client. Create a group for it, add
# the user for that group, and add the group to the acl. Bleagh.
chef_group "client_#{c.name}" do
clients c.name
end
chef_acl "nodes/#{c.name}" do
rights [ :read, :update ], groups: "client_#{c.name}"
end
end
end
| |
Increase the number of cache refreshes for taxonomy | # default cron env is "/usr/bin:/bin" which is not sufficient as govuk_env is in /usr/local/bin
env :PATH, '/usr/local/bin:/usr/bin:/bin'
# We need Rake to use our own environment
job_type :rake, "cd :path && govuk_setenv whitehall bundle exec rake :task --silent :output"
every :day, at: ['3am', '12:45pm'], roles: [:admin] do
rake "export:mappings"
end
every :hour, roles: [:backend] do
rake "rummager:index:consultations"
end
every :hour, roles: [:backend] do
rake "taxonomy:rebuild_cache"
end
| # default cron env is "/usr/bin:/bin" which is not sufficient as govuk_env is in /usr/local/bin
env :PATH, '/usr/local/bin:/usr/bin:/bin'
# We need Rake to use our own environment
job_type :rake, "cd :path && govuk_setenv whitehall bundle exec rake :task --silent :output"
every :day, at: ['3am', '12:45pm'], roles: [:admin] do
rake "export:mappings"
end
every :hour, roles: [:backend] do
rake "rummager:index:consultations"
end
every 10.minutes, roles: [:backend] do
rake "taxonomy:rebuild_cache"
end
|
Upgrade hard_reset for postgres && sqlite | #coding: utf-8
namespace :db do
desc "Hard development sqlite3 reset && seed"
task :hard_reset do
file_name = 'db/development.sqlite3'
print "[del] #{file_name}"
begin
File.delete("#{Rails.root}/#{file_name}")
print " OK\n"
rescue
print " FAIL\n"
end
puts "[rake] db:migrate && [rake] db:seed"
exec "cd #{Rails.root} && rake db:migrate && rake db:seed"
end
desc "Soft database reset && seed"
task :soft_reset do
str = "rake db:migrate VERSION=0 && rake db:migrate && rake db:seed"
puts str.gsub('rake','[rake]')
exec str
end
end
| #coding: utf-8
namespace :db do
desc "Hard development sqlite3 reset && seed"
task :hard_reset do
cmd = "rake db:drop && rake db:create && rake db:migrate && rake db:seed"
puts cmd.gsub('rake','[rake]')
exec "cd #{Rails.root} && #{cmd}"
end
desc "Soft database reset && seed"
task :soft_reset do
str = "rake db:migrate VERSION=0 && rake db:migrate && rake db:seed"
puts str.gsub('rake','[rake]')
exec str
end
end
|
Fix text positioning to work better with IM 6.3.1 | require 'rvg/rvg'
Magick::RVG.dpi = 90
rvg = Magick::RVG.new(10.cm, 3.cm).viewbox(0,0,1000,300) do |canvas|
canvas.background_fill = 'white'
canvas.g.translate(100, 60) do |grp|
grp.text.styles(:font_family=>'Verdana', :font_size=>45) do |txt|
txt.tspan("Rotation ")
txt.tspan("propogates ").rotate(20).styles(:fill=>'red') do |tsp|
tsp.tspan("to descendents").styles(:fill=>'green')
end
end
end
canvas.rect(997, 297).styles(:fill=>'none', :stroke=>'blue')
end
rvg.draw.write('tspan03.gif')
| require 'rvg/rvg'
Magick::RVG.dpi = 90
rvg = Magick::RVG.new(10.cm, 3.cm).viewbox(0,0,1000,300) do |canvas|
canvas.background_fill = 'white'
canvas.g.translate(100, 60) do |grp|
grp.text.styles(:font_family=>'Verdana', :font_size=>45) do |txt|
txt.tspan("Rotation")
txt.tspan(" propogates").rotate(20).styles(:fill=>'red') do |tsp|
tsp.tspan(" to descendents").styles(:fill=>'green')
end
end
end
canvas.rect(997, 297).styles(:fill=>'none', :stroke=>'blue')
end
rvg.draw.write('tspan03.gif')
|
Remove redundant changes to slimmer use | Frontend::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
config.assets.paths << Rails.root.join("test/javascripts")
end
require "slimmer/test"
| Frontend::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
config.assets.paths << Rails.root.join("test/javascripts")
end
|
Refactor block using one liner | require "gem_search/rendering"
module GemSearch
module Commands
class Run < Base
include Mem
include Rendering
ENABLE_SORT_OPTS = {
"a" => "downloads",
"n" => "name",
"v" => "version_downloads"
}
def call
puts_abort(options) unless valid?(options.arguments)
gems = search_gems
puts_abort("We did not find results.") if gems.size.zero?
gems_sort!(gems)
render(gems, !options["no-homepage"])
rescue => e
unexpected_error(e)
end
private
def valid?(arguments)
arguments.size > 0 && arguments.none? { |arg| arg.match(/\A-/) }
end
def search_gems
print "Searching "
gems = Request.new.search(options.arguments[0]) do
print "."
end
puts
gems
end
def gems_sort!(gems)
if sort_opt == "name"
gems.sort! { |x, y| x[sort_opt] <=> y[sort_opt] }
else
gems.sort! { |x, y| y[sort_opt] <=> x[sort_opt] }
end
end
def sort_opt
sort_opt = options["sort"] ? ENABLE_SORT_OPTS[options["sort"][0].downcase] : nil
sort_opt = "downloads" unless sort_opt
sort_opt
end
memoize :sort_opt
end
end
end
| require "gem_search/rendering"
module GemSearch
module Commands
class Run < Base
include Mem
include Rendering
ENABLE_SORT_OPTS = {
"a" => "downloads",
"n" => "name",
"v" => "version_downloads"
}
def call
puts_abort(options) unless valid?(options.arguments)
gems = search_gems
puts_abort("We did not find results.") if gems.size.zero?
gems_sort!(gems)
render(gems, !options["no-homepage"])
rescue => e
unexpected_error(e)
end
private
def valid?(arguments)
arguments.size > 0 && arguments.none? { |arg| arg.match(/\A-/) }
end
def search_gems
print "Searching "
gems = Request.new.search(options.arguments[0]) { print "." }
puts
gems
end
def gems_sort!(gems)
if sort_opt == "name"
gems.sort! { |x, y| x[sort_opt] <=> y[sort_opt] }
else
gems.sort! { |x, y| y[sort_opt] <=> x[sort_opt] }
end
end
def sort_opt
sort_opt = options["sort"] ? ENABLE_SORT_OPTS[options["sort"][0].downcase] : nil
sort_opt = "downloads" unless sort_opt
sort_opt
end
memoize :sort_opt
end
end
end
|
Fix visible_taxons to return all taxons | module Taxonomy
class TopicTaxonomy
def initialize(adapter: RedisCacheAdapter.new, tree_builder_class: Tree)
@adapter = adapter
@tree_builder_class = tree_builder_class
end
def ordered_taxons
@ordered_taxons ||= ordered_branches.select(&:visible_to_departmental_editors)
end
def all_taxons
@all_taxons ||= branches.flat_map(&:taxon_list)
end
def visible_taxons
@visible_taxons = all_taxons.select(&:visible_to_departmental_editors)
end
private
def branches
@branches ||= @adapter.taxon_data.map do |taxon_hash|
@tree_builder_class.new(taxon_hash).root_taxon
end
end
def ordered_branches
@ordered_branches ||= branches.sort_by(&:name)
end
end
end
| module Taxonomy
class TopicTaxonomy
def initialize(adapter: RedisCacheAdapter.new, tree_builder_class: Tree)
@adapter = adapter
@tree_builder_class = tree_builder_class
end
def ordered_taxons
@ordered_taxons ||= ordered_branches.select(&:visible_to_departmental_editors)
end
def all_taxons
@all_taxons ||= branches.flat_map(&:taxon_list)
end
def visible_taxons
@visible_taxons = branches.select(
&:visible_to_departmental_editors
).flat_map(&:taxon_list)
end
private
def branches
@branches ||= @adapter.taxon_data.map do |taxon_hash|
@tree_builder_class.new(taxon_hash).root_taxon
end
end
def ordered_branches
@ordered_branches ||= branches.sort_by(&:name)
end
end
end
|
Create separate method where a csv is created with colocated buildings with charter | def create_colocated_schools_ary(schools_hsh)
colocated_addresses_w_charter = []
charters_colocation = open_csv("csv/colocated-charters-and-schools.csv")
schools_hsh.each_pair do |k,v|
charter_school = v.find { |x| x[3] == "Charter"}
if charter_school != nil
colocated_addresses_w_charter << {k => v}
# v.each {|x| charters_colocation << x}
end
end
colocated_addresses_w_charter
end | def create_colocated_schools_ary(schools_hsh)
colocated_addresses_w_charter = []
charters_colocation = open_csv("csv/colocated-charters-and-schools.csv")
schools_hsh.each_pair do |k,v|
charter_school = v.find { |x| x[3] == "Charter"}
if charter_school != nil
colocated_addresses_w_charter << {k => v}
end
end
colocated_addresses_w_charter
end
def create_colocated_charters_csv(schools_hsh)
schools_hsh.each_pair do |k,v|
charter_school = v.find { |x| x[3] == "Charter"}
if charter_school != nil
v.each {|x| charters_colocation << x}
end
end
end |
Change .com to .org in the do-not-reply address | DO_NOT_REPLY = "do-not-reply@awesomefoundation.com"
ActionMailer::Base.smtp_settings = {
:address => "smtp.sendgrid.net",
:port => "25",
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => ENV['SENDGRID_DOMAIN']
}
| DO_NOT_REPLY = "do-not-reply@awesomefoundation.org"
ActionMailer::Base.smtp_settings = {
:address => "smtp.sendgrid.net",
:port => "25",
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => ENV['SENDGRID_DOMAIN']
}
|
Add jobs as Client extension | require File.expand_path('../client/endpoints.rb', __FILE__)
module MakePrintable
class Client
attr_accessor :api_key, :api_secret
def initialize
@api_key, @api_secret = [MakePrintable.configuration.api_key, MakePrintable.configuration.api_secret]
end
end
end
| require File.expand_path('../client/endpoints.rb', __FILE__)
require File.expand_path('../client/jobs.rb', __FILE__)
module MakePrintable
class Client
attr_accessor :api_key, :api_secret
def initialize
@api_key, @api_secret = [MakePrintable.configuration.api_key, MakePrintable.configuration.api_secret]
end
end
end
|
Check file exist in generate erd. | desc 'Generate Entity Relationship Diagram'
task :generate_erd do
system 'bundle exec erd --inheritance --filetype=dot --notation=bachman --direct --attributes=foreign_keys,content'
system 'dot -Tpng erd.dot > erd.png'
File.delete('erd.dot')
end | desc 'Generate Entity Relationship Diagram'
task :generate_erd do
system 'bundle exec erd --inheritance --filetype=dot --notation=bachman --direct --attributes=foreign_keys,content'
dot_file = File.join(Rails.root, 'erd.dot')
if File.exist? dot_file
system 'dot -Tpng erd.dot > erd.png'
File.delete('erd.dot')
end
end |
Test against expected width of substitution string | require 'test_helper'
describe Prawn::Emoji::Substitution do
let(:document) { Prawn::Document.new }
let(:substitution) { Prawn::Emoji::Substitution.new(document) }
subject { substitution.to_s }
describe 'full-size-space is used' do
before do
document.font_size = 12
stub(substitution).full_size_space_width { 12 }
end
it { subject.must_equal ' ' }
end
describe 'half-size-space is used' do
before do
document.font_size = 12
stub(substitution).full_size_space_width { 11.99 }
end
it { subject.must_equal Prawn::Text::NBSP }
end
end
| require 'test_helper'
describe Prawn::Emoji::Substitution do
let(:document) { Prawn::Document.new }
let(:font_size) { 12 }
let(:substitution) { Prawn::Emoji::Substitution.new(document) }
before do
document.font(font) if font
document.font_size = 12
end
subject { substitution.to_s }
describe 'When Japanese TTF font' do
let(:font) { Prawn::Emoji.root.join('test', 'fonts', 'ipag.ttf') }
it { subject.must_equal ' ' }
it { document.width_of(subject).must_equal font_size }
end
describe 'When ASCII TTF font' do
let(:font) { Prawn::Emoji.root.join('test', 'fonts', 'DejaVuSans.ttf') }
it { subject.must_match /^#{Prawn::Text::NBSP}+$/ }
it { document.width_of(subject).must_be :>=, font_size - 1 }
it { document.width_of(subject).must_be :<=, font_size + 1 }
end
describe 'When built-in AFM font' do
let(:font) { nil }
it { proc { subject }.must_raise Prawn::Errors::IncompatibleStringEncoding }
end
end
|
Update guest users create action | class GuestUsersController < ApplicationController
def index
@guest_users = GuestUser.all
end
def new
@guest_user = GuestUser.new
end
def create
end
def partial
private
def guest_user_params
params.require(:guest_user).permit(:name, :email)
end
end
| class GuestUsersController < ApplicationController
def index
@guest_users = GuestUser.all
end
def new
@guest_user = GuestUser.new
end
def create
@guest_user = GuestUser.new(guest_user_params)
if @guest_user.save
GuestsCleanupJob.set(wait: 10.seconds).perform_later(@guest_user)
redirect_to root_path
else
# flash[:notice] = @guest_user.errors.full_messages
flash[:notice] = @guest_user.errors.full_messages.to_sentence
redirect_to new_guest_users_path
end
end
def partial
private
def guest_user_params
params.require(:guest_user).permit(:name, :email)
end
end
|
Add capistrano extension file for Capistrano v3 | namespace :load do
task :defaults do
set :eye_config, -> { "config/eye.yml" }
set :eye_bin, -> { "bundle exec eye-patch" }
set :eye_roles, -> { :app }
end
end
namespace :eye do
desc "Start eye with the desired configuration file"
task :load_config do
on roles(fetch(:eye_roles)) do
within current_path do
execute "#{fetch(:eye_bin)} l #{fetch(:eye_config)}"
end
end
end
desc "Stop eye and all of its monitored tasks"
task :stop do
on roles(fetch(:eye_roles)) do
within current_path do
execute "#{fetch(:eye_bin)} stop all && #{fetch(:eye_bin)} q"
end
end
end
desc "Restart all tasks monitored by eye"
task :restart do
on roles(fetch(:eye_roles)) do
within current_path do
execute "#{fetch(:eye_bin)} r all"
end
end
end
end
if fetch(:eye_default_hooks, true)
after "deploy:stop", "eye:stop"
after "deploy:start", "eye:load_config"
before "deploy:restart", "eye:restart"
end
before "eye:restart", "eye:load_config"
| |
Work around an ActiveModel bug | module HashBuilder
# Renders templates with '.json_builder' extension.
#
# If the template is a normal view, it will render a JSON string.
# If the template however is a partial, it renders a Hash so that
# json_builder files can use partials.
class Template
def self.default_format
Mime::JSON
end
def self.call (template)
render_code = <<-RUBY
(HashBuilder.build_with_env(scope: self, locals: local_assigns) do
#{template.source}
end)
RUBY
if !is_partial?(template)
render_code = "JSON.generate(#{render_code})"
end
render_code
end
def self.is_partial? (template)
template.virtual_path.split("/").last.start_with?("_")
end
end
end
if defined?(Rails)
ActionView::Template.register_template_handler :json_builder, HashBuilder::Template
end
| module HashBuilder
# Renders templates with '.json_builder' extension.
#
# If the template is a normal view, it will render a JSON string.
# If the template however is a partial, it renders a Hash so that
# json_builder files can use partials.
class Template
def self.default_format
Mime::JSON
end
def self.call (template)
render_code = <<-RUBY
HashBuilder.build_with_env(scope: self, locals: local_assigns) do
#{template.source}
end
RUBY
if !is_partial?(template)
# ActiveModel defines #as_json in a way, that is not compatible
# with JSON.
if defined?(ActiveModel)
render_code = "ActiveSupport::JSON.encode(#{render_code})"
else
render_code = "JSON.generate(#{render_code})"
end
end
render_code
end
def self.is_partial? (template)
template.virtual_path.split("/").last.start_with?("_")
end
end
end
if defined?(ActionView)
ActionView::Template.register_template_handler :json_builder, HashBuilder::Template
end
|
Fix CVE-2020-8130 issue with rake | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'test_changes/description'
require 'test_changes/summary'
require 'test_changes/version'
Gem::Specification.new do |spec|
spec.name = "test_changes"
spec.version = TestChanges::VERSION
spec.authors = ["George Mendoza"]
spec.email = ["gsmendoza@gmail.com"]
spec.summary = TestChanges::SUMMARY
spec.description = TestChanges::DESCRIPTION
spec.homepage = "https://github.com/gsmendoza/test_changes"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "slop", '~> 4.2.0'
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec"
spec.add_development_dependency "rubocop"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'test_changes/description'
require 'test_changes/summary'
require 'test_changes/version'
Gem::Specification.new do |spec|
spec.name = "test_changes"
spec.version = TestChanges::VERSION
spec.authors = ["George Mendoza"]
spec.email = ["gsmendoza@gmail.com"]
spec.summary = TestChanges::SUMMARY
spec.description = TestChanges::DESCRIPTION
spec.homepage = "https://github.com/gsmendoza/test_changes"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "slop", '~> 4.2.0'
spec.add_development_dependency 'rake', '~> 13.0.1', '>= 12.3.3'
spec.add_development_dependency "rspec"
spec.add_development_dependency "rubocop"
end
|
Add additional parameters for Kubernetes | require 'sensu-plugins-kubernetes/version'
require 'sensu-plugin/check/cli'
require 'kubeclient'
module Sensu
module Plugins
module Kubernetes
class CLI < Sensu::Plugin::Check::CLI
option :api_server,
description: 'URL to API server',
short: '-s URL',
long: '--api-server',
default: ENV['KUBERNETES_MASTER']
option :api_version,
description: 'API version',
short: '-v VERSION',
long: '--api-version',
default: 'v1'
def get_client(cli)
api_server = cli.config[:api_server]
api_version = cli.config[:api_version]
begin
Kubeclient::Client.new(api_server, api_version)
rescue
warning 'Unable to connect to Kubernetes API server'
end
end
end
end
end
end
| require 'sensu-plugins-kubernetes/version'
require 'sensu-plugin/check/cli'
require 'kubeclient'
module Sensu
module Plugins
module Kubernetes
class CLI < Sensu::Plugin::Check::CLI
option :api_server,
description: 'URL to API server',
short: '-s URL',
long: '--api-server',
default: ENV['KUBERNETES_MASTER']
option :api_version,
description: 'API version',
short: '-v VERSION',
long: '--api-version',
default: 'v1'
option :ca_file,
description: 'CA file to use',
long: '--ca-file CA-FILE'
option :bearer_token,
description: 'Kubernetes serviceaccount token',
long: '--bearer-token TOKEN'
option :bearer_token_file,
description: 'Kubernetes serviceaccount token file',
long: '--bearer-token-file TOKEN-FILE'
def get_client(cli)
api_server = cli.config[:api_server]
api_version = cli.config[:api_version]
ssl_options = {}
auth_options = {}
if cli.config.key?(:ca_file)
ssl_options[:ca_file] = cli.config[:ca_file]
end
if cli.config.key?(:bearer_token)
auth_options[:bearer_token] = cli.config[:bearer_token]
elsif cli.config.key?(:bearer_token_file)
auth_options[:bearer_token_file] =
cli.config[:bearer_token_file]
end
begin
Kubeclient::Client.new api_server, api_version,
ssl_options: ssl_options,
auth_options: auth_options
rescue
warning 'Unable to connect to Kubernetes API server'
end
end
end
end
end
end
|
Remove unused model_class attribute from SlugGenerator | module FriendlyId
# The default slug generator offers functionality to check slug strings for
# uniqueness and, if necessary, appends a sequence to guarantee it.
class SlugGenerator
attr_accessor :model_class
def initialize(scope)
@scope = scope
end
def available?(slug)
!@scope.exists?(slug)
end
def add(slug)
slug
end
def generate(candidates)
candidates.each {|c| return add c if available?(c)}
nil
end
end
end | module FriendlyId
# The default slug generator offers functionality to check slug strings for
# uniqueness and, if necessary, appends a sequence to guarantee it.
class SlugGenerator
def initialize(scope)
@scope = scope
end
def available?(slug)
!@scope.exists?(slug)
end
def add(slug)
slug
end
def generate(candidates)
candidates.each {|c| return add c if available?(c)}
nil
end
end
end |
Add rake tasks for running unit and functional tests | require File.expand_path('../spec_suite_configuration', __FILE__)
require 'ostruct'
class DefinesSpecSuiteTasks
extend Rake::DSL
def self.configuration
@configuration ||= SpecSuiteConfiguration.build
end
def self.call
desc 'Run all tests'
task :spec do
results = []
DefinesSpecSuiteTasks.configuration.each_matching_suite.each do |suite|
puts "=== Running #{suite.desc} tests ================================================"
results << suite.run
puts
end
if results.any? { |result| not result.success? }
raise 'Spec suite failed!'
end
end
namespace :spec do
DefinesSpecSuiteTasks.configuration.each_matching_suite do |suite|
desc "Run #{suite.desc} tests"
task suite.name => "appraisal:#{suite.appraisal_name}:install" do
result = suite.run
if not result.success?
raise "#{suite.desc} suite failed!"
end
end
end
end
namespace :travis do
desc 'Regenerate .travis.yml'
task :regenerate_config do
DefinesSpecSuiteTasks.configuration.generate_travis_config
end
end
end
end
| require File.expand_path('../spec_suite_configuration', __FILE__)
require 'ostruct'
class DefinesSpecSuiteTasks
extend Rake::DSL
def self.configuration
@configuration ||= SpecSuiteConfiguration.build
end
def self.call
desc 'Run all tests'
task :spec do
results = []
DefinesSpecSuiteTasks.configuration.each_matching_suite.each do |suite|
puts "=== Running #{suite.desc} tests ================================================"
results << suite.run
puts
end
if results.any? { |result| not result.success? }
raise 'Spec suite failed!'
end
end
namespace :spec do
DefinesSpecSuiteTasks.configuration.each_matching_suite do |suite|
desc "Run #{suite.desc} tests"
task suite.name => "appraisal:#{suite.appraisal_name}:install" do
result = suite.run
if not result.success?
raise "#{suite.desc} suite failed!"
end
end
end
unless ruby_18?
require 'rspec/core/rake_task'
desc "Run the unit tests"
RSpec::Core::RakeTask.new(:unit) do |t|
t.pattern = 'spec/suites/rspec_2/unit/**/*_spec.rb'
end
desc "Run the functional (API) tests"
RSpec::Core::RakeTask.new(:functional) do |t|
t.pattern = 'spec/suites/rspec_2/functional/**/*_spec.rb'
end
end
end
namespace :travis do
desc 'Regenerate .travis.yml'
task :regenerate_config do
DefinesSpecSuiteTasks.configuration.generate_travis_config
end
end
end
def self.ruby_18?
RUBY_VERSION =~ /^1\.8/
end
end
|
Use fail instead of raise to throw exceptions | name :bsa
require_helpers :get_field_as_float
execute do
weight = get_field_as_float :weight_in_kg
height = get_field_as_float :height_in_m
raise FieldError.new('weight', 'must be greater than zero') if weight <= 0
raise FieldError.new('height', 'must be greater than zero') if height <= 0
{
value: ((weight * (height * 100)) / 3600) ** 0.5,
units: 'm^2'
}
end
| name :bsa
require_helpers :get_field_as_float
execute do
weight = get_field_as_float :weight_in_kg
height = get_field_as_float :height_in_m
fail FieldError.new('weight', 'must be greater than zero') if weight <= 0
fail FieldError.new('height', 'must be greater than zero') if height <= 0
{
value: ((weight * (height * 100)) / 3600) ** 0.5,
units: 'm^2'
}
end
|
Add 'mingo_id' as a proper spec helper. | # Helper to run a set of specs several times under different conditions.
def branch(*args, &block)
args.map { |sym| ActiveSupport::StringInquirer.new sym.to_s }.each(&block)
end
| # Helper to run a set of specs several times under different conditions.
def branch(*args, &block)
args.map { |sym| ActiveSupport::StringInquirer.new sym.to_s }.each(&block)
end
def mingo_id
last_response.headers['mingo_id'].to_i
end
|
Use report instead of alert, as suggested by @ejaubaud | require 'resolv'
class NameResolver < Scout::Plugin
OPTIONS=<<-EOS
nameserver:
default: 8.8.8.8
resolve_address:
default: google.com
EOS
def build_report
resolver = Resolv::DNS.new(:nameserver => [option(:nameserver)])
begin
result = resolver.getaddress(option(:resolve_address))
rescue Resolv::ResolvError => err
alert('Failed to resolve', err)
end
end
end
| class NameResolver < Scout::Plugin
needs 'resolv'
OPTIONS=<<-EOS
nameserver:
default: 8.8.8.8
resolve_address:
default: google.com
EOS
def build_report
resolver = Resolv::DNS.new(:nameserver => [option(:nameserver)])
begin
resolver.getaddress(option(:resolve_address))
rescue Resolv::ResolvError, Resolv::ResolvTimeout => err
report(:resolved? => 0, :result => err)
else
report(:resolved? => 1)
end
end
end
|
Add basic SearchOrders service spec | require 'spec_helper'
describe SearchOrders do
let!(:distributor) { create(:distributor_enterprise) }
let!(:order1) { create(:order, distributor: distributor) }
let!(:order2) { create(:order, distributor: distributor) }
let!(:order3) { create(:order, distributor: distributor) }
let(:enterprise_user) { distributor.owner }
describe '#orders' do
let(:params) { {} }
let(:service) { SearchOrders.new(params, enterprise_user) }
it 'returns orders' do
expect(service.orders.count).to eq 3
end
end
describe '#pagination_data' do
let(:params) { { per_page: 15, page: 1 } }
let(:service) { SearchOrders.new(params, enterprise_user) }
it 'returns pagination data' do
expect(service.pagination_data).to eq pagination_data
end
end
def pagination_data
{
results: 3,
pages: 1,
page: 1,
per_page: 15
}
end
end
| |
Change serverspec to check for application title - rubygems | require 'spec_helper'
describe 'Sheldon 6artisans webserver' do
it 'has nginx installed' do
expect(package 'nginx').to be_installed
end
it 'is running' do
expect(service 'nginx').to be_enabled
expect(service 'nginx').to be_running
end
xit 'responds to request with response from rails app' do
#think about adding domains to host file
expect(command 'curl http://www.fofrslevy.cz').to return_stdout(/.*<title>Fofrslevy.cz<\/title>.*/)
end
end
| require 'spec_helper'
describe 'Sheldon 6artisans webserver' do
it 'has nginx installed' do
expect(package 'nginx').to be_installed
end
it 'is running' do
expect(service 'nginx').to be_enabled
expect(service 'nginx').to be_running
end
xit 'responds to request with response from rails app' do
#think about adding domains to host file
expect(command 'curl http://localhost').to return_stdout(/.*<title>RubyGems.org | your community gem host<\/title>.*/)
end
end
|
Add more specs for activity session exporter | require 'rails_helper'
describe CsvExporter::ActivitySession do
include_context 'Activity Progress Report'
let(:csv_exporter) { CsvExporter::ActivitySession.new }
describe '#model_data' do
subject { csv_exporter.model_data(mr_kotter, filters) }
context 'filtering by classroom ID' do
let(:filters) { { 'classroom_id' => sweathogs.id } }
it 'retrieves filtered activity sessions' do
expect(subject.size).to eq(sweathogs_sessions.size)
end
end
context 'unfiltered' do
let(:filters) { {} }
it 'retrieves activity sessions without any filters' do
expect(subject.to_a).to eq(all_sessions)
end
end
end
end | require 'rails_helper'
describe CsvExporter::ActivitySession do
include_context 'Activity Progress Report'
let(:csv_exporter) { CsvExporter::ActivitySession.new }
describe '#header_row' do
it 'returns an array of headers' do
expect(csv_exporter.header_row).to eq(['app', 'activity', 'date', 'time_spent', 'standard', 'score', 'student'])
end
end
describe '#data_row' do
it 'returns an array of row data' do
expected_row = [
horshack_session.activity.classification.name,
horshack_session.activity.name,
horshack_session.completed_at.to_formatted_s(:quill_default),
horshack_session.time_spent,
horshack_session.activity.topic.name_prefix,
horshack_session.percentage,
horshack_session.user.name
]
expect(csv_exporter.data_row(horshack_session)).to eq(expected_row)
end
end
describe '#model_data' do
subject { csv_exporter.model_data(mr_kotter, filters) }
context 'filtering by classroom ID' do
let(:filters) { { 'classroom_id' => sweathogs.id } }
it 'retrieves filtered activity sessions' do
expect(subject.size).to eq(sweathogs_sessions.size)
end
end
context 'unfiltered' do
let(:filters) { {} }
it 'retrieves activity sessions without any filters' do
expect(subject.to_a).to eq(all_sessions)
end
end
end
end |
Refactor launch! method to separate part of code to get_action method | require 'restaurant'
class Guide
def initialize(path = nil)
# locate the restaurant text file at path
Restaurant.filepath = path
if Restaurant.file_usable?
puts "Found restaurant file."
# or create a new file
elsif Restaurant.create_file
puts "Created restaurant file."
# exit if create fails
else
puts "Exiting. \n\n"
exit!
end
end
def launch!
introduction
# introduction
# action loop
result = nil
until result == :quit
# what do you want to do? (list, find, add, quit)
print "> "
user_response = gets.chomp
# do that action
result = do_action user_response
end
# conclusion
conclusion
end
def do_action(action)
case action
when 'list'
puts "Listing..."
when 'find'
puts "Finding..."
when 'add'
puts "Adding..."
when 'quit'
return :quit
else
puts "\nI don't understand that command.\n"
end
end
def introduction
puts "\n\n<<< Welcome to the food finder >>>\n\n"
puts "This is an interactive guide to help you find the food you crave.\n\n"
end
def conclusion
puts "\n<<< Goodbye and Bon Appetit! >>>\n\n\n"
end
end
| require 'restaurant'
class Guide
class Config
@@actions = ['list', 'find', 'add', 'quit']
def self.actions; @@actions; end
end
def initialize(path = nil)
# locate the restaurant text file at path
Restaurant.filepath = path
if Restaurant.file_usable?
puts "Found restaurant file."
# or create a new file
elsif Restaurant.create_file
puts "Created restaurant file."
# exit if create fails
else
puts "Exiting. \n\n"
exit!
end
end
def launch!
introduction
# introduction
# action loop
result = nil
until result == :quit
action = get_action
result = do_action action
end
# conclusion
conclusion
end
def get_action
action = nil
# Keep asking for user input until we get a valid action
until Guide::Config.actions.include? action
puts "Actions: " + Guide::Config.actions.join(", ") if action
print "> "
user_response = gets.chomp
action = user_response.downcase.strip
end
return action
end
def do_action(action)
case action
when 'list'
puts "Listing..."
when 'find'
puts "Finding..."
when 'add'
puts "Adding..."
when 'quit'
return :quit
else
puts "\nI don't understand that command.\n"
end
end
def introduction
puts "\n\n<<< Welcome to the food finder >>>\n\n"
puts "This is an interactive guide to help you find the food you crave.\n\n"
end
def conclusion
puts "\n<<< Goodbye and Bon Appetit! >>>\n\n\n"
end
end
|
Fix -v/--version option in Ruby 1.8.7 | # encoding: utf-8
module Apiary
module Command
# Run commands
class Runner
def self.run(cmd, options)
Apiary::Command.const_get(cmd.capitalize).send(:execute, options)
end
end
end
end
| # encoding: utf-8
module Apiary
module Command
# Run commands
class Runner
def self.run(cmd, options)
Apiary::Command.const_get(cmd.to_s.capitalize).send(:execute, options)
end
end
end
end
|
Create patch /items/:id to have ability to update item information | Rails.application.routes.draw do
get '/items', to: 'items#index'
get '/items/new', to: 'items#new', as: 'new_item'
post '/items', to: 'items#create'
get '/items/:id', to: 'items#show', as: 'item'
get '/items/:id/edit', to: 'items#edit'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| Rails.application.routes.draw do
get '/items', to: 'items#index'
get '/items/new', to: 'items#new', as: 'new_item'
post '/items', to: 'items#create'
get '/items/:id', to: 'items#show', as: 'item'
get '/items/:id/edit', to: 'items#edit'
patch '/items/:id', to: 'items#update'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
Fix Order reference in OrderDecorator | Order.class_eval do
token_resource
# Associates the specified user with the order and destroys any previous association with guest user if
# necessary.
def associate_user!(user)
self.user = user
self.email = user.email
# disable validations since this can cause issues when associating an incomplete address during the address step
save(:validate => false)
end
end
| Spree::Order.class_eval do
token_resource
# Associates the specified user with the order and destroys any previous association with guest user if
# necessary.
def associate_user!(user)
self.user = user
self.email = user.email
# disable validations since this can cause issues when associating an incomplete address during the address step
save(:validate => false)
end
end
|
Remove spec test to verify nginx start (which we no longer do) | # encoding: utf-8
describe 'et_nginx::default' do
before do
stub_command('which nginx').and_return(nil)
end
let(:chef_run) do
ChefSpec::SoloRunner.new.converge(described_recipe)
end
shared_examples_for 'default recipe' do
it 'starts the service' do
expect(chef_run).to start_service('nginx')
end
end
context 'unmodified attributes' do
it 'includes the package recipe' do
expect(chef_run).to include_recipe('et_nginx::package')
end
it 'does not include a module recipe' do
expect(chef_run).to_not include_recipe('module_http_stub_status')
end
it_behaves_like 'default recipe'
end
context 'installs modules based on attributes' do
it 'includes a module recipe when specified' do
chef_run.node.set['nginx']['modules'] = ['module_http_ssl']
chef_run.converge(described_recipe)
expect(chef_run).to include_recipe('et_nginx::module_http_geoip')
end
end
end
| # encoding: utf-8
describe 'et_nginx::default' do
before do
stub_command('which nginx').and_return(nil)
end
let(:chef_run) do
ChefSpec::SoloRunner.new.converge(described_recipe)
end
shared_examples_for 'default recipe' do
end
context 'unmodified attributes' do
it 'includes the package recipe' do
expect(chef_run).to include_recipe('et_nginx::package')
end
it 'does not include a module recipe' do
expect(chef_run).to_not include_recipe('module_http_stub_status')
end
it_behaves_like 'default recipe'
end
context 'installs modules based on attributes' do
it 'includes a module recipe when specified' do
chef_run.node.set['nginx']['modules'] = ['module_http_ssl']
chef_run.converge(described_recipe)
expect(chef_run).to include_recipe('et_nginx::module_http_geoip')
end
end
end
|
Add tests for the games list | require 'discordrb/games'
describe Discordrb::Games do
describe Discordrb::Games::Game do
it 'should initialize without errors' do
hash = {
id: 123,
name: 'Pokémon Super Mystery Dungeon',
executables: []
}
Discordrb::Games::Game.new(hash)
end
it 'should contain the given values' do
hash = {
id: 123,
name: 'Pokémon Super Mystery Dungeon',
executables: []
}
game = Discordrb::Games::Game.new(hash)
game.id.should eq(123)
game.name.should eq('Pokémon Super Mystery Dungeon')
game.executables.should eq([])
end
end
it 'should contain FFXI as the zeroth element' do
game = Discordrb::Games.games[0]
game.id.should eq(0)
game.name.should eq('FINAL FANTASY XI')
end
describe 'find_game' do
it 'should return a Game when it is given one' do
hash = {
id: 123,
name: 'Pokémon Super Mystery Dungeon',
executables: []
}
game = Discordrb::Games::Game.new(hash)
game.should be(Discordrb::Games.find_game(game))
end
it 'should find a game by name' do
game = Discordrb::Games.find_game('FINAL FANTASY XI')
game.id.should eq(0)
game.name.should eq('FINAL FANTASY XI')
end
it 'should find a game by ID' do
game = Discordrb::Games.find_game(0)
game.id.should eq(0)
game.name.should eq('FINAL FANTASY XI')
game = Discordrb::Games.find_game('0')
game.id.should eq(0)
game.name.should eq('FINAL FANTASY XI')
end
it 'should return nil if a game is not found' do
Discordrb::Games.find_game('this game does not exist').should be(nil)
end
end
end
| |
Use build.root instead of root in verbose output of Task::PublishPDF | module Texas
module Build
module Task
class PublishPDF < Base
def master_file
build.master_file
end
def build_path
build.__path__
end
def dest_file
build.dest_file
end
def run
run_pdflatex
copy_pdf_file_to_dest_dir
end
def copy_pdf_file_to_dest_dir
tmp_file = File.join(build_path, "#{File.basename(master_file, '.tex')}.pdf")
FileUtils.mkdir_p File.dirname(dest_file)
FileUtils.copy tmp_file, dest_file
verbose {
file = File.join(build_path, "master.log")
output = `grep "Output written on" #{file}`
numbers = output.scan(/\((\d+?) pages\, (\d+?) bytes\)\./).flatten
@page_count = numbers.first.to_i
"Written PDF in #{dest_file.gsub(root, '')} (#{@page_count} pages)".green
}
end
def run_pdflatex
verbose { "Running pdflatex in #{build_path} ..." }
Dir.chdir build_path
`pdflatex #{File.basename(master_file)}`
`pdflatex #{File.basename(master_file)}`
end
end
end
end
end
| module Texas
module Build
module Task
class PublishPDF < Base
def master_file
build.master_file
end
def build_path
build.__path__
end
def dest_file
build.dest_file
end
def run
run_pdflatex
copy_pdf_file_to_dest_dir
end
def copy_pdf_file_to_dest_dir
tmp_file = File.join(build_path, "#{File.basename(master_file, '.tex')}.pdf")
FileUtils.mkdir_p File.dirname(dest_file)
FileUtils.copy tmp_file, dest_file
verbose {
file = File.join(build_path, "master.log")
output = `grep "Output written on" #{file}`
numbers = output.scan(/\((\d+?) pages\, (\d+?) bytes\)\./).flatten
@page_count = numbers.first.to_i
"Written PDF in #{dest_file.gsub(build.root, '')} (#{@page_count} pages)".green
}
end
def run_pdflatex
verbose { "Running pdflatex in #{build_path} ..." }
Dir.chdir build_path
`pdflatex #{File.basename(master_file)}`
`pdflatex #{File.basename(master_file)}`
end
end
end
end
end
|
Add script to make graph from datatypes_conf.xml | #!/usr/bin/env ruby
require 'libxml'
require 'graphviz'
include LibXML
doc = XML::Parser.file("#{ARGV[0]}").parse
g = GraphViz.new( :G, :type => :digraph )
parent_nodes = {}
subtype_nodes = {}
doc.find("//datatype").each do |datatype|
type_spec = datatype.attributes['type']
parent = type_spec.match(/galaxy.datatypes.([^\:]*)/).captures.first
subtype = type_spec.match(/galaxy.datatypes.([^\:]*):(.*)/).captures.last
extension = datatype.attributes['extension']
if !parent_nodes[parent]
parent_nodes[parent] = g.add_nodes(parent)
end
if !subtype_nodes[subtype]
subtype_nodes[subtype] = g.add_nodes(subtype)
g.add_edge(parent_nodes[parent],subtype_nodes[subtype])
end
# require 'byebug';byebug
extnode=g.add_nodes(extension)
g.add_edge(subtype_nodes[subtype],extnode)
# parent_nodes[parent].add_nodes(subtype)
end
puts g.to_s | |
Remove the requirement of an item on ItemAssets to allow them to be saved before the item is saved | module Tenon
class ItemAsset < ActiveRecord::Base
# Validations
validates_presence_of :asset
validates_presence_of :item
# Relationships
belongs_to :asset
belongs_to :item, polymorphic: true
accepts_nested_attributes_for :asset
after_save :reprocess_asset
def reprocess_asset
asset.reload.attachment.reprocess! if asset_id_changed?
end
end
end
| module Tenon
class ItemAsset < ActiveRecord::Base
# Validations
validates_presence_of :asset
# Relationships
belongs_to :asset
belongs_to :item, polymorphic: true
accepts_nested_attributes_for :asset
after_save :reprocess_asset
def reprocess_asset
asset.reload.attachment.reprocess! if asset_id_changed?
end
end
end
|
Create helper to hide gift fields if it's not a gift | module Spree
module BaseHelper
def item_shipping_address(item)
address = tag(:br)
address << content_tag(:b, t(:ship_to, scope: :subscriptions))
address << content_tag(:span, " #{ item.ship_address.to_s }")
address if item.product_subscription?
end
end
end
| module Spree
module BaseHelper
def item_shipping_address(item)
address = tag(:br)
address << content_tag(:b, t(:ship_to, scope: :subscriptions))
address << content_tag(:span, " #{ item.ship_address.to_s }")
address if item.product_subscription?
end
def is_a_gift(gift)
'display: none;' unless gift
end
end
end
|
Move attribute changes to after_replace_fields | class Api::V1::PostResource < JSONAPI::Resource
before_create :set_author_as_current_user
before_update :set_editor_as_current_user
attributes :banner_url,
:content,
:slug,
:title,
:group_slug,
:tags
attribute :published_at, format: :iso8601
attribute :updated_at, format: :iso8601
has_one :author, class_name: 'User'
has_one :editor, class_name: 'User'
has_one :group
filter :group
def group_slug
@model.group.slug
end
def tags
@model.tag_list
end
def tags=(tags)
@model.tag_list = tags
end
private
def self.apply_filter(records, filter, value, options)
case filter
when :group
records.where(group_id: value)
else
return super(records, filter, value, options)
end
end
def set_author_as_current_user
@model.author = context[:current_user]
end
def set_editor_as_current_user
@model.editor = context[:current_user]
end
end
| class Api::V1::PostResource < JSONAPI::Resource
after_replace_fields :set_author_as_current_user
after_replace_fields :set_editor_as_current_user
attributes :banner_url,
:content,
:slug,
:title,
:group_slug,
:tags
attribute :published_at, format: :iso8601
attribute :updated_at, format: :iso8601
has_one :author, class_name: 'User'
has_one :editor, class_name: 'User'
has_one :group
filter :group
def group_slug
@model.group.slug
end
def tags
@model.tag_list
end
def tags=(tags)
@model.tag_list = tags
end
private
def self.apply_filter(records, filter, value, options)
case filter
when :group
records.where(group_id: value)
else
return super(records, filter, value, options)
end
end
def set_author_as_current_user
@model.author ||= context[:current_user]
end
def set_editor_as_current_user
@model.editor = context[:current_user]
end
end
|
Refactor JoystickAxisMoved specs a bit. |
# Prefer local library over installed version.
$:.unshift( File.join( File.dirname(__FILE__), "..", "lib" ) )
$:.unshift( File.join( File.dirname(__FILE__), "..", "ext", "rubygame" ) )
require 'rubygame'
include Rubygame::Events
describe JoystickAxisMoved do
it "should have a joystick id" do
JoystickAxisMoved.new.should respond_to(:joystick_id)
end
it "should accept positive integers for joystick id"
it "should reject all except positive integers for joystick id"
it "joystick id should be read-only"
it "should have an axis number" do
JoystickAxisMoved.new.should respond_to(:axis)
end
it "should accept positive integers for axis number"
it "should reject all except positive integers for axis number"
it "axis number should be read-only"
it "should have a value" do
JoystickAxisMoved.new.should respond_to(:value)
end
it "should only accept numbers for value"
it "should reject non-numeric values"
it "should convert values to float"
it "should only accept values from -1.0 to 1.0"
it "should reject values outside of range"
it "value should be read-only"
end
|
# Prefer local library over installed version.
$:.unshift( File.join( File.dirname(__FILE__), "..", "lib" ) )
$:.unshift( File.join( File.dirname(__FILE__), "..", "ext", "rubygame" ) )
require 'rubygame'
include Rubygame::Events
describe JoystickAxisMoved do
before :each do
@event = JoystickAxisMoved.new
end
it "should have a joystick id" do
@event.should respond_to(:joystick_id)
end
it "should accept positive integers for joystick id"
it "should reject all except positive integers for joystick id"
it "joystick id should be read-only"
it "should have an axis number" do
@event.should respond_to(:axis)
end
it "should accept positive integers for axis number"
it "should reject all except positive integers for axis number"
it "axis number should be read-only"
it "should have a value" do
@event.should respond_to(:value)
end
it "should only accept numbers for value"
it "should reject non-numeric values"
it "should convert values to float"
it "should only accept values from -1.0 to 1.0"
it "should reject values outside of range"
it "value should be read-only"
end
|
Add spec for matching an empty string | require File.expand_path('../../../spec_helper', __FILE__)
require 'strscan'
describe "StringScanner#scan" do
before :each do
@s = StringScanner.new("This is a test")
end
it "returns the matched string" do
@s.scan(/\w+/).should == "This"
@s.scan(/.../).should == " is"
@s.scan(//).should == ""
@s.scan(/\s+/).should == " "
end
it "treats ^ as matching from the beginning of the current position" do
@s.scan(/\w+/).should == "This"
@s.scan(/^\d/).should be_nil
@s.scan(/^\s/).should == " "
end
it "returns nil if there's no match" do
@s.scan(/\d/).should == nil
end
it "returns nil when there is no more to scan" do
@s.scan(/[\w\s]+/).should == "This is a test"
@s.scan(/\w+/).should be_nil
end
it "raises a TypeError if pattern isn't a Regexp" do
lambda { @s.scan("aoeu") }.should raise_error(TypeError)
lambda { @s.scan(5) }.should raise_error(TypeError)
lambda { @s.scan(:test) }.should raise_error(TypeError)
lambda { @s.scan(mock('x')) }.should raise_error(TypeError)
end
end
| require File.expand_path('../../../spec_helper', __FILE__)
require 'strscan'
describe "StringScanner#scan" do
before :each do
@s = StringScanner.new("This is a test")
end
it "returns the matched string" do
@s.scan(/\w+/).should == "This"
@s.scan(/.../).should == " is"
@s.scan(//).should == ""
@s.scan(/\s+/).should == " "
end
it "treats ^ as matching from the beginning of the current position" do
@s.scan(/\w+/).should == "This"
@s.scan(/^\d/).should be_nil
@s.scan(/^\s/).should == " "
end
it "returns nil if there's no match" do
@s.scan(/\d/).should == nil
end
it "returns nil when there is no more to scan" do
@s.scan(/[\w\s]+/).should == "This is a test"
@s.scan(/\w+/).should be_nil
end
it "returns an empty string when the pattern matches empty" do
@s.scan(/.*/).should == "This is a test"
@s.scan(/.*/).should == ""
@s.scan(/./).should be_nil
end
it "raises a TypeError if pattern isn't a Regexp" do
lambda { @s.scan("aoeu") }.should raise_error(TypeError)
lambda { @s.scan(5) }.should raise_error(TypeError)
lambda { @s.scan(:test) }.should raise_error(TypeError)
lambda { @s.scan(mock('x')) }.should raise_error(TypeError)
end
end
|
Install package via run context resource collection | #!/usr/bin/env ruby
require 'chef/run_context'
require 'chef/client'
require 'chef/recipe'
require 'chef/resource'
require 'chef/providers'
$client = nil
def rebuild_node
Chef::Config[:solo] = true
$client = Chef::Client.new
$client.run_ohai
$client.build_node
end
def run_chef
rebuild_node
Chef::Log.level = :debug
run_context = Chef::RunContext.new($client.node, {})
# @recipe = Chef::Recipe.new(nil, nil, run_context)
runrun = Chef::Runner.new(run_context).converge
Chef::Log.level = :debug
runrun
install_package('gitg', run_context)
end
def install_package(package_name, run_context)
package = Chef::Resource::Package.new(package_name, run_context)
package.run_action(:install)
end
puts 'Hello chef run context world'
run_chef
| #!/usr/bin/env ruby
require 'chef/run_context'
require 'chef/client'
require 'chef/recipe'
require 'chef/resource'
require 'chef/providers'
$client = nil
def rebuild_node
Chef::Config[:solo] = true
$client = Chef::Client.new
$client.run_ohai
$client.build_node
end
def run_chef
rebuild_node
Chef::Log.level = :debug
run_context = Chef::RunContext.new($client.node, {})
# @recipe = Chef::Recipe.new(nil, nil, run_context)
Chef::Log.level = :debug
add_package_to_run_context('gitg', run_context)
runrun = Chef::Runner.new(run_context).converge
runrun
end
def install_package(package_name, run_context)
package = Chef::Resource::Package.new(package_name, run_context)
package.run_action(:install)
end
def add_package_to_run_context(package_name, run_context)
package = Chef::Resource::Package.new(package_name, run_context)
run_context.resource_collection.insert(package)
end
puts 'Hello chef run context world'
run_chef
|
Add GPS 2.3 solution to the file | # Your Names
# 1) Stephanie Major
# 2)
# We spent [#] hours on this challenge.
# Bakery Serving Size portion calculator.
def serving_size_calc(item_to_make, num_of_ingredients)
library = {"cookie" => 1, "cake" => 5, "pie" => 7}
error_counter = 3
library.each do |food|
if library[food] != library[item_to_make]
error_counter += -1
end
end
if error_counter > 0
raise ArgumentError.new("#{item_to_make} is not a valid input")
end
serving_size = library.values_at(item_to_make)[0]
remaining_ingredients = num_of_ingredients % serving_size
case remaining_ingredients
when 0
return "Calculations complete: Make #{num_of_ingredients / serving_size} of #{item_to_make}"
else
return "Calculations complete: Make #{num_of_ingredients / serving_size} of #{item_to_make}, you have #{remaining_ingredients} leftover ingredients. Suggested baking items: TODO: MAKE THIS FEATURE"
end
end
p serving_size_calc("pie", 7)
p serving_size_calc("pie", 8)
p serving_size_calc("cake", 5)
p serving_size_calc("cake", 7)
p serving_size_calc("cookie", 1)
p serving_size_calc("cookie", 10)
p serving_size_calc("THIS IS AN ERROR", 5)
# Reflection
| # Your Names
# 1) Stephanie Major
# 2)Kenton Lin
# We spent 1 hours on this challenge.
# Bakery Serving Size portion calculator.
def serving_size_calc(item_to_make, count_of_serving)
baked_goods = {"cookie" => 1, "cake" => 5, "pie" => 7}
raise ArgumentError.new("#{item_to_make} is not a valid input") if baked_goods.has_key?(item_make) == false
serving_size = baked_goods[item_to_make]
portion_left_over = count_of_serving % serving_size
if portion_left_over == 0
return "Make #{count_of_serving / serving_size} of #{item_to_make}"
else
return "Make #{count_of_serving / serving_size} of #{item_to_make}, you have #{portion_left_over} leftover ingredients. Suggested baking items: TODO: MAKE THIS FEATURE"
end
end
p serving_size_calc("pie", 7)
p serving_size_calc("pie", 8)
p serving_size_calc("cake", 5)
p serving_size_calc("cake", 7)
p serving_size_calc("cookie", 1)
p serving_size_calc("cookie", 10)
# p serving_size_calc("THIS IS AN ERROR", 5)
# Reflection
|
Use swift version 4.0 for podspec | Pod::Spec.new do |s|
s.name = 'FDChessboardView'
s.version = '1.0.0'
s.license = 'MIT'
s.summary = 'A view controller for chess boards'
s.homepage = 'https://github.com/fulldecent/FDChessboardView'
s.authors = { 'William Entriken' => 'github.com@phor.net' }
s.source = { :git => 'https://github.com/fulldecent/FDChessboardView.git', :tag => s.version }
s.ios.deployment_target = '8.0'
s.source_files = 'Source/*.swift'
s.resource_bundles = {
'FDChessboardView' => ['Resources/**/*.{png}']
}
end
| Pod::Spec.new do |s|
s.name = 'FDChessboardView'
s.version = '1.0.0'
s.license = 'MIT'
s.summary = 'A view controller for chess boards'
s.homepage = 'https://github.com/fulldecent/FDChessboardView'
s.authors = { 'William Entriken' => 'github.com@phor.net' }
s.source = { :git => 'https://github.com/fulldecent/FDChessboardView.git', :tag => s.version }
s.ios.deployment_target = '8.0'
s.source_files = 'Source/*.swift'
s.resource_bundles = {
'FDChessboardView' => ['Resources/**/*.{png}']
}
s.swift_version = '4.0'
end
|
Make cache validity check private | module LokalebasenSettingsClient
class SettingsCache
attr_reader :cache
attr_accessor :cache_time
private :cache
def initialize
@cache_time = 60 * 60 # 1 Hour
@cache = {}
end
def cached(&block)
return @cache[:value] if cache_valid?
new_value = yield
@cache = {
value: new_value,
expires: Time.now + cache_time
}
new_value
rescue Exception => exception
@cache[:expires] = Time.now + cache_time if @cache.is_a?(Hash)
raise exception
end
def last_cached_value
@cache[:value]
end
def cache_valid?
!@cache.nil? &&
!@cache[:expires].nil? &&
@cache[:expires] > Time.now
end
end
end
| module LokalebasenSettingsClient
class SettingsCache
attr_reader :cache
attr_accessor :cache_time
private :cache
def initialize
@cache_time = 60 * 60 # 1 Hour
@cache = {}
end
def cached(&block)
return @cache[:value] if cache_valid?
new_value = yield
@cache = {
value: new_value,
expires: Time.now + cache_time
}
new_value
rescue Exception => exception
@cache[:expires] = Time.now + cache_time if @cache.is_a?(Hash)
raise exception
end
def last_cached_value
@cache[:value]
end
private
def cache_valid?
!@cache.nil? &&
!@cache[:expires].nil? &&
@cache[:expires] > Time.now
end
end
end
|
Update RSpec's 'filter_run' config syntax | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'enumerate_it'
require 'active_support/all'
require 'active_record'
Dir['./spec/support/**/*.rb'].each { |f| require f }
I18n.config.enforce_available_locales = false
I18n.load_path = Dir['spec/i18n/*.yml']
RSpec.configure do |config|
config.filter_run_including focus: true
config.run_all_when_everything_filtered = true
end
| $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'enumerate_it'
require 'active_support/all'
require 'active_record'
Dir['./spec/support/**/*.rb'].each { |f| require f }
I18n.config.enforce_available_locales = false
I18n.load_path = Dir['spec/i18n/*.yml']
RSpec.configure do |config|
config.filter_run :focus
config.run_all_when_everything_filtered = true
end
|
Fix a typo and narrow the begin block that hid the typo. | module Kakasi
module Lib
if defined?(::FFI::Platform)
LIBPREFIX = ::FFI::Platform::LIBPREFIX
LIBSUFFIX = ::FFI::Platform::LIBSUFFIX
else
LIBPREFIX =
case RbConfig::CONFIG['host_os']
when /mingw|mswin/i
''.freeze
when /cygwin/i
'cyg'.freeze
else
'lib'.freeze
end
LIBSUFFIX =
case RbConfig::CONFIG['host_os']
when /darwin/i
'dylib'.freeze
when /mingw|mswin|cygwin/i
'dll'.freeze
else
'so'.freeze
end
end
DEFLIBPATH =
begin
[RbConfig::CONFIG['libir']] |
case RbConfig::CONFIG['host_os']
when /mingw|mswin/i
[]
else
%w[/lib /usr/lib]
end
end.freeze
def self.map_library_name(name)
"#{LIBPREFIX}#{name}.#{LIBSUFFIX}"
end
def self.try_load(libpath = LIBPATH)
basename = map_library_name('kakasi')
(libpath | DEFLIBPATH).each { |dir|
begin
filename = File.join(dir, basename)
yield filename
return filename
rescue LoadError, StandardError
next
end
}
yield basename
return basename
end
end
end
| module Kakasi
module Lib
if defined?(::FFI::Platform)
LIBPREFIX = ::FFI::Platform::LIBPREFIX
LIBSUFFIX = ::FFI::Platform::LIBSUFFIX
else
LIBPREFIX =
case RbConfig::CONFIG['host_os']
when /mingw|mswin/i
''.freeze
when /cygwin/i
'cyg'.freeze
else
'lib'.freeze
end
LIBSUFFIX =
case RbConfig::CONFIG['host_os']
when /darwin/i
'dylib'.freeze
when /mingw|mswin|cygwin/i
'dll'.freeze
else
'so'.freeze
end
end
DEFLIBPATH =
begin
[RbConfig::CONFIG['libdir']] |
case RbConfig::CONFIG['host_os']
when /mingw|mswin/i
[]
else
%w[/lib /usr/lib]
end
end.freeze
def self.map_library_name(name)
"#{LIBPREFIX}#{name}.#{LIBSUFFIX}"
end
def self.try_load(libpath = LIBPATH)
basename = map_library_name('kakasi')
(libpath | DEFLIBPATH).each { |dir|
filename = File.join(dir, basename)
begin
yield filename
rescue LoadError, StandardError
next
end
return filename
}
yield basename
return basename
end
end
end
|
Fix a bug that doesn't follow a redirect chain | require 'curb'
require 'digest'
require 'tempfile'
module Sufeed
def self.checksum(url)
file = Tempfile.new('sufeed')
redirected = location(url)
puts "Redirected to #{redirected}" if url != redirected
Curl::Easy.download(redirected, file.path)
sha256 = Digest::SHA2.file(file.path).hexdigest
return sha256
end
end
| require 'curb'
require 'digest'
require 'tempfile'
module Sufeed
def self.checksum(url)
file = Tempfile.new('sufeed')
Curl::Easy.download(url, file.path) do |curl|
curl.follow_location = true
end
sha256 = Digest::SHA2.file(file.path).hexdigest
return sha256
end
end
|
Load all stripe event webhooks | require 'braintree'
require 'stripe'
require 'stripe_event'
require 'pay/engine'
require 'pay/billable'
# Subscription backends
require_relative 'pay/subscription/stripe'
require_relative 'pay/subscription/braintree'
# Webhook processors
require_relative 'pay/stripe/charge_succeeded'
require_relative 'pay/stripe/charge_refunded'
require_relative 'pay/stripe/subscription_canceled'
require_relative 'pay/stripe/subscription_renewing'
module Pay
# Define who owns the subscription
mattr_accessor :billable_class
mattr_accessor :billable_table
mattr_accessor :braintree_gateway
@@billable_class = 'User'
@@billable_table = @@billable_class.tableize
mattr_accessor :business_name
mattr_accessor :business_address
mattr_accessor :send_emails
@@send_emails = true
def self.setup
yield self
end
class Error < StandardError;
end
end
| require 'braintree'
require 'stripe'
require 'stripe_event'
require 'pay/engine'
require 'pay/billable'
# Subscription backends
require_relative 'pay/subscription/stripe'
require_relative 'pay/subscription/braintree'
# Webhook processors
require_relative 'pay/stripe/charge_refunded'
require_relative 'pay/stripe/charge_succeeded'
require_relative 'pay/stripe/customer_deleted'
require_relative 'pay/stripe/customer_updated'
require_relative 'pay/stripe/source_deleted'
require_relative 'pay/stripe/subscription_deleted'
require_relative 'pay/stripe/subscription_renewing'
require_relative 'pay/stripe/subscription_updated'
module Pay
# Define who owns the subscription
mattr_accessor :billable_class
mattr_accessor :billable_table
mattr_accessor :braintree_gateway
@@billable_class = 'User'
@@billable_table = @@billable_class.tableize
mattr_accessor :business_name
mattr_accessor :business_address
mattr_accessor :send_emails
@@send_emails = true
def self.setup
yield self
end
class Error < StandardError;
end
end
|
Fix for URL formatting from MarkdownRenderer | class ImportContacts
class MoreInfoUrl
include Virtus.value_object
class MarkdownRenderer
URL_PART = %Q{[%{url}](%{url_title})}
DESCRIPTION_PART = %Q{%{url_description}}
delegate :url, :description, :title, to: :@more_info_url
def initialize(more_info_url)
@more_info_url = more_info_url
end
def url_part
if url.present? && title.present?
URL_PART % { url: url, url_title: title }
end
end
def description_part
DESCRIPTION_PART % { url_description: description }
end
def render
[url_part, description_part].compact.join("\n")
end
end
attribute :url, String
attribute :title, String
attribute :description, String
def to_markdown
MarkdownRenderer.new(self).render
end
end
end
| class ImportContacts
class MoreInfoUrl
include Virtus.value_object
class MarkdownRenderer
URL_PART = %Q{[%{url_title}](%{url})}
DESCRIPTION_PART = %Q{%{url_description}}
delegate :url, :description, :title, to: :@more_info_url
def initialize(more_info_url)
@more_info_url = more_info_url
end
def url_part
if url.present? && title.present?
URL_PART % { url: url, url_title: title }
end
end
def description_part
DESCRIPTION_PART % { url_description: description }
end
def render
[url_part, description_part].compact.join("\n")
end
end
attribute :url, String
attribute :title, String
attribute :description, String
def to_markdown
MarkdownRenderer.new(self).render
end
end
end
|
Remove useless private access modifier at service | module SlackMessageServices
class RemindMembersWhoForgetOrdering < Base
def self.call
return unless order && some_members_have_not_ordered_lunch?
content = format_content
send_message(content)
end
private
def self.format_content
username_string = members_have_not_ordered_lunch.map { |member| "@#{member}" }
"Hey #{username_string.join(', ')}! You haven't ordered lunch yet. Please order now!"
end
def self.members_have_not_ordered_lunch
@members_have_not_ordered_lunch ||= all_members - members_ordered_lunch
end
def self.some_members_have_not_ordered_lunch?
all_members.count > members_ordered_lunch.count
end
def self.order
@order ||= Order.today.first
end
def self.members_ordered_lunch
@members_ordered_lunch ||= order.order_items.pluck(:username).uniq
end
def self.all_members
@all_members ||= GetListMembersService.call
end
end
end
| module SlackMessageServices
class RemindMembersWhoForgetOrdering < Base
def self.call
return unless order && some_members_have_not_ordered_lunch?
content = format_content
send_message(content)
end
def self.format_content
username_string = members_have_not_ordered_lunch.map { |member| "@#{member}" }
"Hey #{username_string.join(', ')}! You haven't ordered lunch yet. Please order now!"
end
def self.members_have_not_ordered_lunch
@members_have_not_ordered_lunch ||= all_members - members_ordered_lunch
end
def self.some_members_have_not_ordered_lunch?
all_members.count > members_ordered_lunch.count
end
def self.order
@order ||= Order.today.first
end
def self.members_ordered_lunch
@members_ordered_lunch ||= order.order_items.pluck(:username).uniq
end
def self.all_members
@all_members ||= GetListMembersService.call
end
end
end
|
Add features to sites table. | class UpdateSites < ActiveRecord::Migration
def self.up
change_table :sites do |t|
t.string :secondary_host, :limit => 255
t.integer :max_admins, :max_people, :max_groups
t.boolean :import_export, :cms, :pictures, :publications, :default => true
t.boolean :active, :default => true
end
end
def self.down
change_table :sites do |t|
t.remove :secondary_host
t.remove :max_admins, :max_people, :max_groups
t.remove :import_export, :cms, :pictures, :publications
t.remove :active
end
end
end
| |
Upgrade Mini Metro to alpha10 | class MiniMetro < Cask
url 'http://static.dinopoloclub.com/minimetro/builds/alpha9/MiniMetro-alpha9e-osx.zip'
homepage 'http://dinopoloclub.com/minimetro/'
version 'Alpha 9e'
sha256 'd2261a4e2ab6d71114af99524fa86c590b66f880c32c8546d556a2b80cc0be16'
link 'MiniMetro-alpha9e-osx.app', :target => 'Mini Metro.app'
end
| class MiniMetro < Cask
url 'http://static.dinopoloclub.com/minimetro/builds/alpha10/MiniMetro-alpha10-osx.zip'
homepage 'http://dinopoloclub.com/minimetro/'
version 'Alpha 10'
sha256 '7453b2edff9dc91416f7ad376830da38b15e02c03eae7573ddb9e526ce9309ee'
link 'MiniMetro-alpha10-osx.app', :target => 'Mini Metro.app'
end
|
Add documentation for AR::Dirty module | module Mobility
module Backend
module ActiveRecord::Dirty
include ActiveModel::Dirty
# @param [Class] backend_class Class of backend
def self.included(backend_class)
backend_class.extend(ActiveModel::Dirty::ClassMethods)
backend_class.extend(ClassMethods)
end
module ClassMethods
def setup_model(model_class, attributes, **options)
super
method_name_regex = /\A(#{attributes.join('|'.freeze)})_([a-z]{2}(_[a-z]{2})?)(=?|\??)\z/.freeze
mod = Module.new do
define_method :has_attribute? do |attr_name|
super(attr_name) || !!method_name_regex.match(attr_name)
end
end
model_class.class_eval do
extend mod
method_name = ::ActiveRecord::VERSION::STRING < '5.1' ? :changes_applied : :changes_internally_applied
define_method method_name do
@previously_changed = changes
super()
end
def clear_changes_information
@previously_changed = ActiveSupport::HashWithIndifferentAccess.new
super
end
def previous_changes
(@previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new).merge(super)
end
end
end
end
end
end
end
| module Mobility
module Backend
=begin
Dirty tracking for AR models. See {Mobility::Backend::ActiveModel::Dirty} for
details on usage.
=end
module ActiveRecord::Dirty
include ActiveModel::Dirty
# @param [Class] backend_class Class of backend
def self.included(backend_class)
backend_class.extend(ActiveModel::Dirty::ClassMethods)
backend_class.extend(ClassMethods)
end
# Adds hook after {Backend::Setup#setup_model} to patch AR so that it
# handles changes to translated attributes just like normal attributes.
module ClassMethods
# (see Mobility::Backend::Setup#setup_model)
def setup_model(model_class, attributes, **options)
super
method_name_regex = /\A(#{attributes.join('|'.freeze)})_([a-z]{2}(_[a-z]{2})?)(=?|\??)\z/.freeze
mod = Module.new do
define_method :has_attribute? do |attr_name|
super(attr_name) || !!method_name_regex.match(attr_name)
end
end
model_class.class_eval do
extend mod
method_name = ::ActiveRecord::VERSION::STRING < '5.1' ? :changes_applied : :changes_internally_applied
define_method method_name do
@previously_changed = changes
super()
end
def clear_changes_information
@previously_changed = ActiveSupport::HashWithIndifferentAccess.new
super
end
def previous_changes
(@previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new).merge(super)
end
end
end
end
end
end
end
|
Update library version to 0.6 | Pod::Spec.new do |s|
s.name = "IGIdenticon"
s.version = "0.5"
s.summary = "Swift identicon generator"
s.description = "This library is a port of [identicon](https://github.com/donpark/identicon) library that generates identicon."
s.homepage = "https://github.com/Seaburg/IGIdenticon"
s.screenshots = "https://raw.github.com/seaburg/IGIdenticon/master/Screenshot/screenshot.png"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Evgeniy Yurtaev" => "evgeniyyurt@gmail.com" }
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/seaburg/IGIdenticon.git", :tag => "0.5" }
s.source_files = "Identicon/*.swift"
s.framework = "CoreGraphics"
s.requires_arc = true
end
| Pod::Spec.new do |s|
s.name = "IGIdenticon"
s.version = "0.6"
s.summary = "Swift identicon generator"
s.description = "This library is a port of [identicon](https://github.com/donpark/identicon) library that generates identicon."
s.homepage = "https://github.com/Seaburg/IGIdenticon"
s.screenshots = "https://raw.github.com/seaburg/IGIdenticon/master/Screenshot/screenshot.png"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Evgeniy Yurtaev" => "evgeniyyurt@gmail.com" }
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/seaburg/IGIdenticon.git", :tag => "0.6" }
s.source_files = "Identicon/*.swift"
s.framework = "CoreGraphics"
s.requires_arc = true
end
|
Change to fix tty dependency. | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'static_deploy/version'
Gem::Specification.new do |spec|
spec.name = "static_deploy"
spec.version = StaticDeploy::VERSION
spec.authors = ["Piotr Murach"]
spec.email = ["pmurach@gmail.com"]
spec.description = %q{Automated deployment to GitHub pages}
spec.summary = %q{Provides rake tasks for publishing your static site to github pages to any remote repository}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "tty"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'static_deploy/version'
Gem::Specification.new do |spec|
spec.name = "static_deploy"
spec.version = StaticDeploy::VERSION
spec.authors = ["Piotr Murach"]
spec.email = ["pmurach@gmail.com"]
spec.description = %q{Automated deployment to GitHub pages}
spec.summary = %q{Provides rake tasks for publishing your static site to github pages to any remote repository}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "tty", "0.2.0"
spec.add_development_dependency "bundler", "~> 1.3"
end
|
Change update PWS task logging for enhanced clarity | #!/usr/bin/env ruby
# encoding: utf-8
require 'open3'
require 'fileutils'
puts "Buildpack name: #{ENV['BUILDPACK_NAME']}\n"
_, status = Open3.capture2e('cf', 'api', ENV['CF_API'])
raise 'cf target failed' unless status.success?
_, status = Open3.capture2e('cf','auth', ENV['USERNAME'], ENV['PASSWORD'])
raise 'cf auth failed' unless status.success?
puts "Original Buildpacks\n==================="
system('cf', 'buildpacks')
orig_filename = Dir.glob("pivotal-buildpacks-cached/#{ENV['BUILDPACK_NAME']}*.zip").first
filename = orig_filename.gsub(/\+\d+\.zip$/, '.zip')
FileUtils.mv(orig_filename, filename)
puts filename
_, status = Open3.capture2e('cf', 'update-buildpack', "#{ENV['BUILDPACK_NAME']}_buildpack", '-p', "#{filename}")
raise 'cf update-buildpack failed' unless status.success?
| #!/usr/bin/env ruby
# encoding: utf-8
require 'open3'
require 'fileutils'
puts "Buildpack name: #{ENV['BUILDPACK_NAME']}\n"
_, status = Open3.capture2e('cf', 'api', ENV['CF_API'])
raise 'cf target failed' unless status.success?
_, status = Open3.capture2e('cf','auth', ENV['USERNAME'], ENV['PASSWORD'])
raise 'cf auth failed' unless status.success?
puts "Original Buildpacks\n==================="
system('cf', 'buildpacks')
orig_filename = Dir.glob("pivotal-buildpacks-cached/#{ENV['BUILDPACK_NAME']}*.zip").first
filename = orig_filename.gsub(/\+\d+\.zip$/, '.zip')
FileUtils.mv(orig_filename, filename)
puts "\ncf update-buildpack #{ENV['BUILDPACK_NAME']}_buildpack -p #{filename}"
_, status = Open3.capture2e('cf', 'update-buildpack', "#{ENV['BUILDPACK_NAME']}_buildpack", '-p', "#{filename}")
raise 'cf update-buildpack failed' unless status.success?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.