Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Correct article specs (all passing) | require "rails_helper"
describe Article do
let(:user) { User.create!(username: "sampleuser", permission_level: "author", password: "password") }
let(:article) { Article.new(orig_author: :user, title: "When Awesome Groups Make Awesome Apps") }
describe '#orig_author' do
it 'must have an original author' do
... | require "rails_helper"
describe Article do
let(:user) { User.create!(username: "sampleuser", permission_level: "author", password: "password") }
let(:article) { Article.new(orig_author: user, title: "When Awesome Groups Make Awesome Apps") }
describe '#orig_author' do
it 'must have an original author' do
... |
Use export:redirector_mappings in the cron job | $: << '.'
require File.dirname(__FILE__) + "/initializers/scheduled_publishing"
# 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 ... | $: << '.'
require File.dirname(__FILE__) + "/initializers/scheduled_publishing"
# 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 ... |
Add VirtualBox Extension Pack v5.0.0-101573 | cask :v1 => 'virtualbox-extension-pack' do
version '5.0.0-101573'
sha256 'c357e36368883df821ed092d261890a95c75e50422b75848c40ad20984086a7a'
url "http://download.virtualbox.org/virtualbox/#{version.sub(%r{-.*},'')}/Oracle_VM_VirtualBox_Extension_Pack-#{version}.vbox-extpack"
name 'VirtualBox Extension Pack'
h... | |
Add an example of a free guest. | require 'noam-lemma'
# This is an example of a Ruby Lemma that publishes message and *also* uses the
# "Guest" model of connection. This Lemma will advertise that it's available on
# the local network and only begin playing messages once a server requests a
# connection from the Lemma.
publisher = Noam::Lemma.new(
... | |
Use correct method to read binary file in Ruby. | require 'test/unit'
require 'socket'
require 'net/http'
class GetTests < Test::Unit::TestCase
def setup
@server = fork {
exec 'src/dirt -c config/test.cfg -p 8000'
}
sleep 0.1
@http = Net::HTTP.start('localhost', 8000)
end
def teardown
Process.kill("TERM",... | require 'test/unit'
require 'socket'
require 'net/http'
class GetTests < Test::Unit::TestCase
def setup
@server = fork {
exec 'src/dirt -c config/test.cfg -p 8000'
}
sleep 0.1
@http = Net::HTTP.start('localhost', 8000)
end
def teardown
Process.kill("TERM",... |
Fix showing contact_mail in mails | class InvitationsMailer < ApplicationMailer
def invitation_email(submission, event_dates, event_venue, contact_email)
email = submission.email
@token = submission.invitation_token
@event_dates = event_dates
@event_venue = event_venue
@days_to_confirm = Setting.get.days_to_confirm_invitation
ma... | class InvitationsMailer < ApplicationMailer
def invitation_email(submission, event_dates, event_venue, contact_email)
email = submission.email
@token = submission.invitation_token
@event_dates = event_dates
@event_venue = event_venue
@days_to_confirm = Setting.get.days_to_confirm_invitation
@c... |
Refactor change method_missing to select_by_type | class GreekString
class Container
require 'forwardable'
extend Forwardable
def_delegators :@container, :[], :<<, :each, :map, :flat_map
def initialize(letters=nil)
@container = letters || []
end
def to_a
@container
end
def to_s(*args)
@container.flat_map { |letter... | class GreekString
class Container
require 'forwardable'
extend Forwardable
def_delegators :@container, :[], :<<, :each, :map, :flat_map
def initialize(letters=nil)
@container = letters || []
end
def to_a
@container
end
def to_s(*args)
@container.flat_map { |letter... |
Update gem version to 0.0.3 | require 'rubygems'
GEMSPEC = Gem::Specification.new do |spec|
spec.name = 'smartview'
spec.summary = 'A library for communicating with Hyperion SmartView providers'
spec.description = %{Provides a Ruby library for communicating with Hyperion SmartView providers for the purposes of retrieving metadata and d... | require 'rubygems'
GEMSPEC = Gem::Specification.new do |spec|
spec.name = 'smartview'
spec.summary = 'A library for communicating with Hyperion SmartView providers'
spec.description = %{Provides a Ruby library for communicating with Hyperion SmartView providers for the purposes of retrieving metadata and d... |
Refactor S3 deployment for single file deployment | require 'fog'
module Stevenson
module Deployer
class S3
include Deployer::Base
attr_reader :deployment_bucket_name, :deployment_key
def initialize(options)
@deployment_bucket_name, @deployment_key, @deployment_access_key, @deployment_access_secret = options["s3"]
super
e... | require 'fog'
module Stevenson
module Deployer
class S3
include Deployer::Base
attr_reader :deployment_bucket_name, :deployment_key
def initialize(options)
@deployment_bucket_name, @deployment_key, @deployment_access_key, @deployment_access_secret = options["s3"]
super
e... |
Change to case over if else | # frozen_string_literal: true
module Unparser
class Emitter
# Emiter for float literals
class Float < self
handle :float
children :value
INFINITY = ::Float::INFINITY
NEG_INFINITY = -::Float::INFINITY
private
def dispatch
if value.eql?(INFINITY)
writ... | # frozen_string_literal: true
module Unparser
class Emitter
# Emiter for float literals
class Float < self
handle :float
children :value
INFINITY = ::Float::INFINITY
NEG_INFINITY = -::Float::INFINITY
private
def dispatch
case value
when INFINITY
... |
Set the default buildpack url for the java sample to the master branch of the java buildpack repo | require_relative 'spec_helper'
describe "Java" do
before(:each) do
set_java_version(app.directory, jdk_version)
app.setup!
app.set_config("JVM_COMMON_BUILDPACK" => "https://github.com/heroku/heroku-buildpack-jvm-common/tarball/#{`git rev-parse HEAD`}")
app.heroku.put_stack(app.name, "cedar-14")
en... | require_relative 'spec_helper'
describe "Java" do
before(:each) do
set_java_version(app.directory, jdk_version)
app.setup!
app.set_config("JVM_COMMON_BUILDPACK" => "https://github.com/heroku/heroku-buildpack-jvm-common/tarball/#{`git rev-parse HEAD`}")
end
["1.7", "1.8"].each do |version|
conte... |
Use a lookup table instead of hand-crafted method to match a number | class NumberRecognizer
attr_accessor :number
def initialize(number)
@number = number
end
def valid?
valid_dutch_mobile? or valid_belgian_mobile? or valid_suriname? or valid_antilles?
end
def valid_dutch_mobile?
number =~ /^00316\d{8,8}$/
end
def valid_belgian_mobile?
number =~ /^0032... | class NumberRecognizer
KNOWN_FORMATS = {
'Dutch mobile' => [316, 8],
'Belgian mobile' => [324, 8],
'Suriname' => [597,7],
'Antilles' => [599,7]
}
attr_accessor :number
def initialize(number)
@number = number
end
def valid?
if match = KNOWN_FORMATS.find {|name, pattern| number =~ /^... |
Fix `url` stanza comment for QLStephen. | cask 'qlstephen' do
version '1.4.3'
sha256 '73f9a467ba2eb4244ffe1dbf9be435d3481a438c8ec64d2bd9bb1ba60d576a66'
# github.com/downloads/whomwah/qlstephen was verified as official when first introduced to the cask
url "https://github.com/whomwah/qlstephen/releases/download/#{version}/QLStephen.qlgenerator.#{versio... | cask 'qlstephen' do
version '1.4.3'
sha256 '73f9a467ba2eb4244ffe1dbf9be435d3481a438c8ec64d2bd9bb1ba60d576a66'
# github.com/whomwah/qlstephen was verified as official when first introduced to the cask
url "https://github.com/whomwah/qlstephen/releases/download/#{version}/QLStephen.qlgenerator.#{version}.zip"
... |
Disable garbage collector when benchmarking | module BenchPress
class Runnable
attr_reader :name, :code_block, :run_time
attr_accessor :percent_slower, :fastest
class << self
def repetitions
@repetitions ||= 1000
end
def repetitions=(times)
@repetitions = times
end
end
def initialize(name, block)
... | module BenchPress
class Runnable
attr_reader :name, :code_block, :run_time
attr_accessor :percent_slower, :fastest
class << self
def repetitions
@repetitions ||= 1000
end
def repetitions=(times)
@repetitions = times
end
end
def initialize(name, block)
... |
Remove unused topic section scope | class TopicSection < ActiveRecord::Base
belongs_to :topic
has_many :guides, through: :topic_section_guides
has_many :topic_section_guides, -> { order(position: :asc) }, dependent: :destroy
accepts_nested_attributes_for :topic_section_guides
scope :belonging_to_topic, ->(topic_id) {
where(topic_id: topic... | class TopicSection < ActiveRecord::Base
belongs_to :topic
has_many :guides, through: :topic_section_guides
has_many :topic_section_guides, -> { order(position: :asc) }, dependent: :destroy
accepts_nested_attributes_for :topic_section_guides
end
|
Add various version sizes similar to imgur. | # encoding: utf-8
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
include CarrierWave::MimeTypes
include Sprockets::Helpers::RailsHelper
process :set_content_type
version :thumb do
process resize_to_fill: [200, 200]
end
def store_dir
File.join('uploads', 'imag... | # encoding: utf-8
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
include CarrierWave::MimeTypes
include Sprockets::Helpers::RailsHelper
process :set_content_type
version :huge do
process resize_to_fit: [1024, 1024]
end
version :large do
process resize_to_fit:... |
Use outer join onto addresses when searcing for practice | module Renalware
module Patients
class PracticeSearchQuery
attr_reader :search_term
def initialize(search_term:)
@search_term = search_term
end
def call
return [] if search_term.blank?
term = "%#{search_term}%"
Practice.select(:id, :name)
... | module Renalware
module Patients
class PracticeSearchQuery
attr_reader :search_term
def initialize(search_term:)
@search_term = search_term
end
def call
return [] if search_term.blank?
term = "%#{search_term}%"
Practice.select(:id, :name)
... |
Make sure code extract is always a hash | module ActionDispatch
class ExceptionWrapper
def extract_sources
exception.backtrace.map do |trace|
file, line = trace.split(":")
line_number = line.to_i
{
code: source_fragment(file, line_number),
file: file,
line_number: line_number
}
end... | module ActionDispatch
class ExceptionWrapper
def extract_sources
exception.backtrace.map do |trace|
file, line = trace.split(":")
line_number = line.to_i
{
code: source_fragment(file, line_number) || {},
file: file,
line_number: line_number
}
... |
Include test cases for all cops, and then emit failure tags only for those with offences | require 'rexml/document'
module RuboCop
module Formatter
class JUnitFormatter < BaseFormatter
def started(target_file)
@document = REXML::Document.new.tap do |d|
d << REXML::XMLDecl.new
end
@testsuites = REXML::Element.new('testsuites', @document)
@testsuite = REXM... | require 'rexml/document'
module RuboCop
module Formatter
class JUnitFormatter < BaseFormatter
# This gives all cops - we really want all _enabled_ cops, but
# that is difficult to obtain - no access to config object here.
COPS = Cop::Cop.all
def started(target_file)
@docum... |
Add a way to disable transactional factories for a single test. | module TransactionalFactories
module ClassMethods
def suite_with_transactions
method_names = public_instance_methods(true)
tests = method_names.delete_if {|method_name| method_name !~ /^test./}
suite = TransactionalFactories::TestSuite.new(name)
tests.sort.each do
|test|
ca... | module TransactionalFactories
module ClassMethods
def suite_with_transactions
if use_transactional_factories.is_a?(FalseClass)
suite_without_transactions
else
method_names = public_instance_methods(true)
tests = method_names.delete_if {|method_name| method_name !~ /^test./}
... |
Add java_home to current session | #
# Copyright:: Copyright (c) 2018, Aerobase Inc
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... | #
# Copyright:: Copyright (c) 2018, Aerobase Inc
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... |
Add some explicit assertions to list tests | require 'test_helper'
class ListTest < Test::Unit::TestCase
def setup
Clever.api_key = "DEMO_KEY"
end
should "retrieve districts" do
VCR.use_cassette("districts") do
Clever::District.all
end
end
should "retrieve schools" do
VCR.use_cassette("schools") do
Clever::School.all
e... | require 'test_helper'
class ListTest < Test::Unit::TestCase
def setup
Clever.api_key = "DEMO_KEY"
end
should "retrieve districts" do
VCR.use_cassette("districts") do
@districts = Clever::District.all
end
@districts.count.must_equal 1
end
should "retrieve schools" do
VCR.use_casse... |
Use -k option on iostat: Display statistics in kilobytes per second instead of blocks per second | Ohai.plugin(:DiskStats) do
provides 'disk_stats'
collect_data(:linux) do
disk_stats Mash.new
so = shell_out("iostat -d")
parsing_dev = false
so.stdout.lines do |line|
next if line == "\n"
if line =~ /Device:.*/
if line !~ /^Device:\s+tps\s+kB_read\/s\s+kB_wrtn\/s\s+kB_read\s+kB_w... | Ohai.plugin(:DiskStats) do
provides 'disk_stats'
collect_data(:linux) do
disk_stats Mash.new
so = shell_out("iostat -d -k")
parsing_dev = false
so.stdout.lines do |line|
next if line == "\n"
if line =~ /Device:.*/
if line !~ /^Device:\s+tps\s+kB_read\/s\s+kB_wrtn\/s\s+kB_read\s+k... |
Test for question title validation | require 'rails_helper'
describe Question do
it "has a valid factory" do
expect(build(:question)).to be_valid
end
end | require 'rails_helper'
describe Question do
it "has a valid factory" do
expect(build(:question)).to be_valid
end
it "is invalid without a title" do
expect(build(:question, title: nil).valid?).to eq false
end
end |
Convert SeparatorItem to use Coordinates. | #
# SMELL: the attribute 'date_ranges'. Use a message instead, such as #min_and_max_date.
# SMELL: #calc_layout and #render seem to split the responsibility of retrieving dimension information.
#
module TChart
class SeparatorItem
attr_reader :y_coordinate
attr_reader :length
attr_reader :date_ranges... | #
# SMELL: the attribute 'date_ranges'. Use a message instead, such as #min_and_max_date.
# SMELL: #calc_layout and #render seem to split the responsibility of retrieving dimension information.
#
module TChart
class SeparatorItem
attr_reader :from
attr_reader :to
attr_reader :date_ranges
de... |
Edit response migration to include question_id | class CreateResponses < ActiveRecord::Migration
def change
create_table :responses do |t|
t.integer :option_id, null: false, index: true
t.integer :surveys_user_id, null: false, index: true
t.timestamps null: false
end
end
end
| class CreateResponses < ActiveRecord::Migration
def change
create_table :responses do |t|
t.integer :option_id, null: false, index: true
t.integer :question_id, null: false, index: true
t.integer :surveys_user_id, null: false, index: true
t.timestamps null: false
end
end
end
|
Remove log message for every run | # require ENV["RAILS_ENV_PATH"]
require File.expand_path(File.join(File.dirname(__FILE__), '../..', 'config', 'environment'))
require 'rubygems'
loop do
puts "Fetching at #{ Time.now.to_s(:time) }..."
EvernoteNote.sync_all
Resource.sync_all_binaries
Book.sync_all
Link.sync_all
sleep Settings.evernote.daemo... | # require ENV["RAILS_ENV_PATH"]
require File.expand_path(File.join(File.dirname(__FILE__), '../..', 'config', 'environment'))
require 'rubygems'
loop do
EvernoteNote.sync_all
Resource.sync_all_binaries
Book.sync_all
Link.sync_all
sleep Settings.evernote.daemon_frequency
end
|
Add rake to runtime deps | #encoding: utf-8
Gem::Specification.new do |gem|
gem.name = 'devtools'
gem.version = '0.0.1'
gem.authors = [ 'Markus Schirp' ]
gem.email = [ 'mbj@seonic.net' ]
gem.description = 'A metagem for dm-2 style development'
gem.summary = gem.description
gem.homepage = 'https://github... | #encoding: utf-8
Gem::Specification.new do |gem|
gem.name = 'devtools'
gem.version = '0.0.1'
gem.authors = [ 'Markus Schirp' ]
gem.email = [ 'mbj@seonic.net' ]
gem.description = 'A metagem for dm-2 style development'
gem.summary = gem.description
gem.homepage = 'https://github... |
Update APT source for builds on GCE | require 'travis/build/appliances/base'
module Travis
module Build
module Appliances
class UpdateGlibc < Base
def apply
sh.fold "fix.CVE-2015-7547" do
sh.export 'DEBIAN_FRONTEND', 'noninteractive'
sh.cmd <<-EOF
if [ ! $(uname|grep Darwin) ]; then
sudo -E apt-get -... | require 'travis/build/appliances/base'
module Travis
module Build
module Appliances
class UpdateGlibc < Base
def apply
sh.fold "fix.CVE-2015-7547" do
fix_gce_apt_src
sh.export 'DEBIAN_FRONTEND', 'noninteractive'
sh.cmd <<-EOF
if [ ! $(uname|grep Darwin)... |
Revert "Remove extension whitelist, as further heroku debugging effort." | # encoding: utf-8
class PhotoUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounte... | # encoding: utf-8
class PhotoUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounte... |
Reduce example capistrano configuration to minimum sprinkle requires | set :application, "application"
role :app, "yourhost.com"
role :web, "yourhost.com"
role :db, "yourhost.com", :primary => true
| set :user, 'root'
role :app, 'yourhost.com', :primary => true
|
Update gemspec summary and description | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'smart_polling/version'
Gem::Specification.new do |spec|
spec.name = "smart_polling"
spec.version = SmartPolling::VERSION
spec.authors = ["Mateus Del Bianco"]
spec.ema... | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'smart_polling/version'
Gem::Specification.new do |spec|
spec.name = "smart_polling"
spec.version = SmartPolling::VERSION
spec.authors = ["Mateus Del Bianco"]
spec.ema... |
Add JSON dev dependency for webmock | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/customerio/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["John Allison"]
gem.email = ["john@customer.io"]
gem.description = "A ruby client for the Customer.io event API."
gem.summary = "A ruby client for the C... | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/customerio/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["John Allison"]
gem.email = ["john@customer.io"]
gem.description = "A ruby client for the Customer.io event API."
gem.summary = "A ruby client for the C... |
Handle rake tasks in cron jobs with bundle exec. | # Use this file to easily define all of your cron jobs.
set :output, File.join(File.expand_path(File.dirname(__FILE__)), "log", "cron_log.log")
job_type :rake, "cd :path && RAILS_ENV=:environment /home/rails/.rvm/bin/rake :task :output"
job_type :find_command, "cd :path && :task :output"
# Sync with OSM but ... | # Use this file to easily define all of your cron jobs.
set :output, File.join(File.expand_path(File.dirname(__FILE__)), "log", "cron_log.log")
job_type :rake, "cd :path && RAILS_ENV=:environment bundle exec rake :task :output"
job_type :find_command, "cd :path && :task :output"
# Sync with OSM but not betwe... |
Add [] syntax for JS functions | module MrubyJs
class JsObject
def call(name, *args)
get_func(name).invoke(*args)
end
def call_constructor(name, *args)
get_func(name).invoke_constructor(*args)
end
def call_with_this(name, this_value, *args)
get_func(name).invoke_with_this(this_value, *args)
end
def ge... | module MrubyJs
class JsObject
def call(name, *args)
get_func(name).invoke(*args)
end
def call_constructor(name, *args)
get_func(name).invoke_constructor(*args)
end
def call_with_this(name, this_value, *args)
get_func(name).invoke_with_this(this_value, *args)
end
def ge... |
Use serialized_event in ActiveJob Dispatcher | require 'active_job'
module RailsEventStore
module AsyncProxyStrategy
class AfterCommit
def call(klass, event)
if ActiveRecord::Base.connection.transaction_open?
ActiveRecord::Base.
connection.
current_transaction.
add_record(AsyncRecord.new(klass, even... | require 'active_job'
module RailsEventStore
module AsyncProxyStrategy
class AfterCommit
def call(klass, serialized_event)
if ActiveRecord::Base.connection.transaction_open?
ActiveRecord::Base.
connection.
current_transaction.
add_record(AsyncRecord.new(... |
Update rubocop requirement from ~> 0.82.0 to ~> 0.83.0 | Gem::Specification.new do |spec|
spec.name = 'puppet-lint-no_cron_resources-check'
spec.version = '1.0.1'
spec.homepage = 'https://github.com/deanwilson/no_cron_resources-check'
spec.license = 'MIT'
spec.author = 'Dean Wilson'
spec.email = 'dean.wilson@gmail.com'
spec.files ... | Gem::Specification.new do |spec|
spec.name = 'puppet-lint-no_cron_resources-check'
spec.version = '1.0.1'
spec.homepage = 'https://github.com/deanwilson/no_cron_resources-check'
spec.license = 'MIT'
spec.author = 'Dean Wilson'
spec.email = 'dean.wilson@gmail.com'
spec.files ... |
Fix `url` stanza comment for GraphicConverter. | cask 'graphicconverter' do
version '9.2098'
sha256 'ae584e3e4d508eb4a6d99e8caa234466d0e88108465486ddd45cd641fc7d24df'
# lemkesoft.org was verified as official when first introduced to the cask
url "http://www.lemkesoft.info/files/graphicconverter/gc#{version.major}_build#{version.minor}.zip"
appcast 'http://... | cask 'graphicconverter' do
version '9.2098'
sha256 'ae584e3e4d508eb4a6d99e8caa234466d0e88108465486ddd45cd641fc7d24df'
# lemkesoft.info was verified as official when first introduced to the cask
url "http://www.lemkesoft.info/files/graphicconverter/gc#{version.major}_build#{version.minor}.zip"
appcast 'http:/... |
Remove possibly confusing comment about secret token | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attac... | # Be sure to restart your server when you modify this file.
Satq::Application.config.secret_key_base = ENV['RAILS_SECRET_KEY_BASE'] || '6869a8df1655c7356d86b11a572c2d98'
|
Make the rails version in the gemspec more restrictive | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "transam_audit/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "transam_audit"
s.version = TransamAudit::VERSION
s.authors = ["Julian Ray"]
s.email = ["jra... | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "transam_audit/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "transam_audit"
s.version = TransamAudit::VERSION
s.authors = ["Julian Ray"]
s.email = ["jra... |
Fix reference to refactored method | class AddRawContents < ActiveRecord::Migration[5.2]
ANNOTATABLES = [Case, TextBlock]
def up
create_table :raw_contents do |t|
t.text :content
t.references :source, polymorphic: true, index: { unique: true }
t.timestamps null: false
end
ANNOTATABLES.each do |klass|
# Copy over... | class AddRawContents < ActiveRecord::Migration[5.2]
ANNOTATABLES = [Case, TextBlock]
def up
create_table :raw_contents do |t|
t.text :content
t.references :source, polymorphic: true, index: { unique: true }
t.timestamps null: false
end
ANNOTATABLES.each do |klass|
# Copy over... |
Upgrade Rubymine EAP to v140.2694 | cask :v1 => 'rubymine-eap' do
version '139.262'
sha256 'e255b6a0f94fee55e72c9969919619c3431bf6507e678e0ac9303edc0d441072'
url "http://download.jetbrains.com/ruby/RubyMine-#{version}.dmg"
homepage 'http://confluence.jetbrains.com/display/RUBYDEV/RubyMine+EAP'
license :unknown
app 'RubyMine.app'
end
| cask :v1 => 'rubymine-eap' do
version '140.2694'
sha256 '7376d5b04b49e503c203a2b1c9034a690835ea601847753710f3c8ec53566ebb'
url "http://download.jetbrains.com/ruby/RubyMine-#{version}.dmg"
homepage 'http://confluence.jetbrains.com/display/RUBYDEV/RubyMine+EAP'
license :unknown
app 'RubyMine EAP.app'
end
|
Set minimum password score for Admin model to 3 | class Admin < ActiveRecord::Base
include PgSearch
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :authy_authenticatable, :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable,
:... | class Admin < ActiveRecord::Base
include PgSearch
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :authy_authenticatable, :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable,
:... |
Remove RSpec gem install dependency. | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rspec_lister/version'
Gem::Specification.new do |spec|
spec.name = "rspec_lister"
spec.version = RspecLister::VERSION
spec.authors = ["Anthony Panozzo"]
spec.email ... | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rspec_lister/version'
Gem::Specification.new do |spec|
spec.name = "rspec_lister"
spec.version = RspecLister::VERSION
spec.authors = ["Anthony Panozzo"]
spec.email ... |
Fix error : key must be 32 bytes | class PageletRails::Encryptor
DEFAULT_SALT = '!@#Q156^tdSXggT0&*789++8&?_|T%\/++==RqE'
attr_reader :salt
def self.encode(data, opts = {})
self.new(opts).encode data
end
def self.decode(encrypted_data, opts = {})
self.new(opts).decode encrypted_data
end
def self.get_key secret, salt
@get_k... | class PageletRails::Encryptor
DEFAULT_SALT = '!@#Q156^tdSXggT0&*789++8&?_|T%\/++==RqE'
attr_reader :salt
def self.encode(data, opts = {})
self.new(opts).encode data
end
def self.decode(encrypted_data, opts = {})
self.new(opts).decode encrypted_data
end
def self.get_key secret, salt
@get_k... |
Add monthly trend to budget statistics | class BudgetStatistics
attr_accessor :budget
def initialize(budget)
@budget=budget
end
def category_distribution
@budget.categories.map {|category| {:value => category.used_this_month.to_i, :color => category.color} }
end
end | class BudgetStatistics
attr_accessor :budget
def initialize(budget)
@budget=budget
end
def category_distribution
@budget.categories.map {|category| {:value => category.used_this_month.to_i, :color => category.color} }
end
def monthly_trend
days = (1..Date.today.day).to_a
data = calculate_... |
Disable port checking on CircleCI | require 'dockerspec'
require 'dockerspec/serverspec'
describe docker_build('.', tag: 'keywhiz') do
it { should have_entrypoint '/entrypoint.sh' }
it { should have_workdir %r{^/opt/keywhiz-} }
it { should have_expose '4444' }
it { should have_env 'KEYWHIZ_VERSION' }
describe docker_build(File.dirname(__FILE_... | require 'dockerspec'
require 'dockerspec/serverspec'
describe docker_build('.', tag: 'keywhiz') do
it { should have_entrypoint '/entrypoint.sh' }
it { should have_workdir %r{^/opt/keywhiz-} }
it { should have_expose '4444' }
it { should have_env 'KEYWHIZ_VERSION' }
describe docker_build(File.dirname(__FILE_... |
Put back accidentally committed rake removal | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/sidekiq-unique-jobs/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Mikael Henriksson"]
gem.email = ["mikael@zoolutions.se"]
gem.description = gem.summary = "The unique jobs that were removed from sidekiq"
gem.homepa... | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/sidekiq-unique-jobs/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Mikael Henriksson"]
gem.email = ["mikael@zoolutions.se"]
gem.description = gem.summary = "The unique jobs that were removed from sidekiq"
gem.homepa... |
Delete class from Peeek::Hook::Linker.classes after test | require 'peeek/hook/linker'
describe Peeek::Hook::Linker, '.classes' do
it "returns classes that inherited #{described_class}" do
klass = Class.new(described_class)
described_class.classes.should be_include(klass)
end
end
| require 'peeek/hook/linker'
describe Peeek::Hook::Linker, '.classes' do
before do
@class = Class.new(described_class)
end
after do
described_class.classes.delete(@class)
end
it "returns classes that inherited #{described_class}" do
described_class.classes.should be_include(@class)
end
end
|
Sort countries by name before output in API | class API::V1::CountriesController < API::APIController
def index
@countries = Portal::Country.all.map{ |c| {name: c.name, id: c.id} }
render :json => @countries
end
end
| class API::V1::CountriesController < API::APIController
def index
@countries = Portal::Country.all.sort_by{ |k| k["name"]}.map{ |c| {name: c.name, id: c.id} }
render :json => @countries
end
end
|
Allow to use different tag | module Rack
class IframeTransport
def initialize(app)
@app = app
end
def call(env)
dup._call(env)
end
def _call(env)
@status, @headers, @response = @app.call(env)
@request = Rack::Request.new(env)
if iframe_transport?
@headers['Content-Type'] = 'text/html'
... | module Rack
class IframeTransport
def initialize(app, tag = 'textarea')
@app = app
@tag = tag
end
def call(env)
dup._call(env)
end
def _call(env)
@status, @headers, @response = @app.call(env)
@request = Rack::Request.new(env)
if iframe_transport?
@hea... |
Add Cyberduck - Libre FTP, SFTP, WebDAV & cloud storage browser for Mac & Windows. | class Cyberduck < Cask
url 'http://cyberduck.ch/Cyberduck-4.2.1.zip'
homepage 'http://cyberduck.ch'
version '4.2.1'
end | |
Make a few tests green | module ActiveEncode
module EngineAdapters
class FfmpegAdapter
def create(encode)
new_encode = encode.class.new(encode.input, encode.options)
new_encode.id = SecureRandom.uuid
# TODO mkdir(File.join(working_dir,new_encode.id))
new_encode
end
def find(id, opts={})
... | require 'fileutils'
module ActiveEncode
module EngineAdapters
class FfmpegAdapter
def create(encode)
new_encode = encode.class.new(encode.input, encode.options)
new_encode.id = SecureRandom.uuid
new_encode.state = :running
new_encode.current_operations = []
new_encod... |
Test for meaningful type error messages. | require 'reindeer'
describe 'Reindeer types' do
it 'should constrain attributes' do
class QuietWord < Reindeer
with Reindeer::Role::TypeConstraint
def verify(val)
val =~ /^[a-z]+$/
end
meta.compose!
end
class SoftlySpoken < Reindeer
has :start, is_a: String, type_... | require 'reindeer'
describe 'Reindeer types' do
it 'should constrain attributes' do
class QuietWord < Reindeer
with Reindeer::Role::TypeConstraint
def verify(val)
val.downcase == val
end
meta.compose!
end
class SoftlySpoken < Reindeer
has :start, is_a: String, typ... |
Remove duplication from SampleFile spec | require 'spec_helper'
describe SampleFile do
describe :image do
it "should call #file on an instance of Image" do
described_class::Image.any_instance.should_receive(:file)
described_class.image
end
end
describe :image_path do
it "should call #file_path on an instance of Image" do
d... | require 'spec_helper'
describe SampleFile do
%w(Image Video).each do |class_name|
klass = const_get("SampleFile::#{class_name}")
file_method = class_name.downcase
describe file_method do
it "should call #file on an instance of #{class_name}" do
klass.any_instance.should_receive(:file)
... |
Remove host from s3 fog credentials | def storage_config
path = File.join(Rails.root.to_s, 'config/filesystem.yml')
unless File.file?(path)
return nil
end
config = YAML::load(ERB.new(File.read(path)).result)
unless Hash === config
return nil
end
config = config[Rails.env.to_s]
unless Hash === config
return nil
end
config
... | def storage_config
path = File.join(Rails.root.to_s, 'config/filesystem.yml')
unless File.file?(path)
return nil
end
config = YAML::load(ERB.new(File.read(path)).result)
unless Hash === config
return nil
end
config = config[Rails.env.to_s]
unless Hash === config
return nil
end
config
... |
Add HTTP methods to custom routes | # Here you can override or add to the pages in the core website
Rails.application.routes.draw do
# Add a route for the survey
scope '/profile/survey' do
root :to => 'user#survey', :as => :survey
match '/reset' => 'user#survey_reset', :as => :survey_reset
end
match "/help/ico-guidance-for-authorities" ... | # Here you can override or add to the pages in the core website
Rails.application.routes.draw do
# Add a route for the survey
scope '/profile/survey' do
root :to => 'user#survey', :as => :survey
get '/reset' => 'user#survey_reset', :as => :survey_reset
end
get "/help/ico-guidance-for-authorities" => r... |
Resolve remote log removed_by via removed_by_id instead | require 'virtus'
class RemoteLog
include Virtus.model(nullify_blank: true)
attribute :aggregated_at, Time
attribute :archive_verified, Boolean, default: false
attribute :archived_at, Time
attribute :archiving, Boolean, default: false
attribute :content, String
attribute :created_at, Time
attribute :id... | require 'virtus'
class RemoteLog
include Virtus.model(nullify_blank: true)
attribute :aggregated_at, Time
attribute :archive_verified, Boolean, default: false
attribute :archived_at, Time
attribute :archiving, Boolean, default: false
attribute :content, String
attribute :created_at, Time
attribute :id... |
Use have_protected_instance_method for 1.9 compat | require File.dirname(__FILE__) + '/../../spec_helper'
require 'tempfile'
describe "Tempfile#_close" do
before(:each) do
@tempfile = Tempfile.new("specs")
end
it "is protected" do
@tempfile.protected_methods.should include("_close")
end
it "closes self" do
@tempfile.send(:_close)
@tempfi... | require File.dirname(__FILE__) + '/../../spec_helper'
require 'tempfile'
describe "Tempfile#_close" do
before(:each) do
@tempfile = Tempfile.new("specs")
end
it "is protected" do
Tempfile.should have_protected_instance_method(:_close)
end
it "closes self" do
@tempfile.send(:_close)
@tem... |
Remove underscore for ActiveSupport gem | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/nacre/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Damon Allen Davison"]
gem.email = ["damon@allolex.net"]
gem.description = %q{A Ruby class for working with the Brightpearl API}
gem.summary = %q{The Nacre g... | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/nacre/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Damon Allen Davison"]
gem.email = ["damon@allolex.net"]
gem.description = %q{A Ruby class for working with the Brightpearl API}
gem.summary = %q{The Nacre g... |
Add sizes to image model | class Item < ApplicationRecord
belongs_to :user
belongs_to :section
has_attached_file :image,
storage: :s3,
s3_credentials: {access_key_id: ENV["AWS_KEY"], secret_access_key: ENV["AWS_SECRET"]},
bucket: "neverevernude"
validates :user_id, :section_id, presence: true
validates_attachment_presence ... | class Item < ApplicationRecord
belongs_to :user
belongs_to :section
has_attached_file :image,
:styles => {
:thumb => "100x100#",
:small => "150x150>",
:medium => "200x200" },
storage: :s3,
s3_credentials: {access_key_id: ENV["AWS_KEY"], secret_access_key: ENV["AWS_SECRET"]},
buc... |
Fix bug where exception is thrown when trying to edit User | class User < ActiveRecord::Base
attr_accessor :raw_password, :raw_password_confirmation
validates_uniqueness_of :username
def raw_password=(val)
if val.present?
self.hashed_password = BCrypt::Password.create(val)
end
end
# Returns whether this user has access to (i.e. can edit/delete) given p... | class User < ActiveRecord::Base
attr_accessor :raw_password, :raw_password_confirmation
validates_uniqueness_of :username
def raw_password=(val)
if val.present?
self.hashed_password = BCrypt::Password.create(val)
end
end
# Returns whether this user has access to (i.e. can edit/delete) given p... |
Test for matching ACL grants on copied file | require 'spec_helper'
describe 'Copying Files', type: :feature do
let(:image) { File.open('spec/fixtures/image.png', 'r') }
let(:original) { FeatureUploader.new }
it 'copies an existing file to the specified path' do
original.store!(image)
original.retrieve_from_store!('image.png')
original.file... | require 'spec_helper'
describe 'Copying Files', type: :feature do
let(:image) { File.open('spec/fixtures/image.png', 'r') }
let(:original) { FeatureUploader.new }
it 'copies an existing file to the specified path' do
original.store!(image)
original.retrieve_from_store!('image.png')
original.file... |
Change debug to info and make it grey | require "hipchat"
require "notifier/version"
require "notifier/configuration"
module Notifier
class << self
def configure(config_hash=nil)
if config_hash
config_hash.each do |k,v|
configuration.send("#{k}=", v) rescue nil if configuration.respond_to?("#{k}=")
end
end
... | require "hipchat"
require "notifier/version"
require "notifier/configuration"
module Notifier
class << self
def configure(config_hash=nil)
if config_hash
config_hash.each do |k,v|
configuration.send("#{k}=", v) rescue nil if configuration.respond_to?("#{k}=")
end
end
... |
Correct the name for configuration file | require 'test_bed/version'
require 'grit'
require 'pivotal-tracker'
require 'optparse'
require 'fileutils'
require 'test_bed/config'
require 'test_bed/base'
| require 'test_bed/version'
require 'grit'
require 'pivotal-tracker'
require 'optparse'
require 'fileutils'
require 'test_bed/configuration'
require 'test_bed/base'
|
Remove help from the artefact retreiver | class ArtefactRetriever
class UnsupportedArtefactFormat < StandardError; end
class RecordArchived < StandardError; end
class RecordNotFound < StandardError; end
attr_accessor :supported_formats, :content_api, :logger, :statsd
def initialize(content_api, logger, statsd, supported_formats = nil)
self.cont... | class ArtefactRetriever
class UnsupportedArtefactFormat < StandardError; end
class RecordArchived < StandardError; end
class RecordNotFound < StandardError; end
attr_accessor :supported_formats, :content_api, :logger, :statsd
def initialize(content_api, logger, statsd, supported_formats = nil)
self.cont... |
Add spec for utils for adding proxy chain | require 'spec_helper'
require 'rspec_ssltls'
describe RspecSsltls::Util do
describe '#self.open_socket' do
before :each do
proxy = double('proxy')
allow(proxy).to receive(:open).and_return(:proxy)
allow(Net::SSH::Proxy::HTTP).to receive(:new).and_return(proxy)
allow(TCPSocket).to receive(... | |
Add simple tests for OauthContainer class | require 'spec_helper'
RSpec.describe WebBouncer::OauthContainer do
pending "write it"
end
| require 'spec_helper'
require 'dry-monads'
RSpec.describe WebBouncer::OauthContainer do
include Dry::Monads::Either::Mixin
let(:container) { WebBouncer::OauthContainer }
describe 'when user rewrite container' do
class TestContainer < WebBouncer::OauthContainer
register 'oauth.base_callback' do
... |
Fix require so that tests can be run from alaveteli Rails.root. | require 'test_helper'
class AlavetelithemeTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
| require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper'))
class AlavetelithemeTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
|
Order groups by full name in search dropdown | class API::MembershipsController < API::RestfulController
def index
@group = Group.find(params[:group_id])
authorize! :show, @group
@memberships = Queries::VisibleMemberships.new(user: current_user, group: @group, limit: 5)
respond_with_collection
end
def my_memberships
@memberships = curre... | class API::MembershipsController < API::RestfulController
def index
@group = Group.find(params[:group_id])
authorize! :show, @group
@memberships = Queries::VisibleMemberships.new(user: current_user, group: @group, limit: 5)
respond_with_collection
end
def my_memberships
@memberships = curre... |
Add method Tweet to get overall average sentiment for a country | class Tweet < ActiveRecord::Base
belongs_to :trend
def get_sentiment
AlchemyAPI.search(:sentiment_analysis, :text => self.text.delete("#").delete("&"))
end
def set_sentiment
results = get_sentiment || { type: "neutral", score: 0.0 }
self.update_attributes(sentiment: results["type"] || "neutral",
... | class Tweet < ActiveRecord::Base
belongs_to :trend
def get_sentiment
AlchemyAPI.search(:sentiment_analysis, :text => self.text.delete("#").delete("&"))
end
def set_sentiment
results = get_sentiment || { type: "neutral", score: 0.0 }
self.update_attributes(sentiment: results["type"] || "neutral",
... |
Implement the mixin (oh my god, my eyes!) | require "node_module/version"
require 'live_ast/to_ruby'
require 'v8'
module NodeModule
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def node_module(*methods)
if methods.empty?
NodeModule.execute_following_methods_as_javascript!(self)
else
NodeMod... | |
Change the way current param is calculated | module Filters
class Filter
include Enumerable
attr_reader :name, :selection_policy, :selected_values
private :selection_policy, :selected_values
def initialize(name, param_value, selection_policy)
@name = name
@selection_policy = selection_policy
@selected_values = selection_polic... | module Filters
class Filter
include Enumerable
attr_reader :name, :selection_policy, :selected_values
private :selection_policy, :selected_values
def initialize(name, current_param_value, selection_policy)
@name = name
@selection_policy = selection_policy
@selected_values = selecti... |
Update Beatport Pro to v2.1.0 | class BeatportPro < Cask
version '2.0.5_124'
sha256 '8c1c7dd3bc180eef7f5d12f258241522a659aab1f6dcdc8f077cf151952d1ff2'
url "http://pro.beatport.com/mac/#{version}/beatportpro_#{version}.dmg"
homepage 'http://pro.beatport.com/'
link 'Beatport Pro.app'
end
| class BeatportPro < Cask
version '2.1.0_133'
sha256 'd668c8fb82be5a5402a2470f7f65df75d08bad84352a609ea694290e29df93e2'
url "http://pro.beatport.com/mac/#{version}/beatportpro_#{version}.dmg"
homepage 'http://pro.beatport.com/'
link 'Beatport Pro.app'
end
|
Update Air Video Server HD to 2.2.0 | cask :v1 => 'air-video-server-hd' do
version '2.1.4'
sha256 '7c516edccbc7556d798af330fada0498f9a57ddd91e325be69ad81c9357d241a'
# amazonaws.com is the official download host per the vendor homepage
url "https://s3.amazonaws.com/AirVideoHD/Download/Air+Video+Server+HD+#{version}.dmg"
name 'Air Video Server HD'... | cask :v1 => 'air-video-server-hd' do
version '2.2.0'
sha256 'f43c826dd5742d01e0586ad0e07edd2771353480482ac0b8eb9cc98da20a6f0e'
# amazonaws.com is the official download host per the vendor homepage
url "https://s3.amazonaws.com/AirVideoHD/Download/Air+Video+Server+HD+#{version}.dmg"
name 'Air Video Server HD'... |
Tidy up code a bit | # frozen_string_literal: true
module HumanAttributeValues
extend ActiveSupport::Concern
def human_attribute_value(attribute, options = {})
value = public_send(attribute)
self.class.human_attribute_value(attribute, value, options)
end
module ClassMethods
def human_attribute_value(attribute, value,... | # frozen_string_literal: true
module HumanAttributeValues
extend ActiveSupport::Concern
def human_attribute_value(attribute, options = {})
value = public_send(attribute)
self.class.human_attribute_value(attribute, value, options)
end
module ClassMethods
def human_attribute_value(attribute, value,... |
Add Canvas account ID to the JWT | module JwtHelper
def jwt_token
return unless signed_in?
attrs = {
user_id: current_user.id,
}
# Only trust these values if the current request is an LTI launch
if @lti_token
attrs[:iss] = @lti_token["iss"]
attrs[:deployment_id] = @lti_token[LtiAdvantage::Definitions::DEPLOYMENT... | module JwtHelper
def jwt_token
return unless signed_in?
attrs = {
user_id: current_user.id,
}
# Only trust these values if the current request is an LTI launch
if @lti_token
attrs[:iss] = @lti_token["iss"]
attrs[:deployment_id] = @lti_token[LtiAdvantage::Definitions::DEPLOYMENT... |
Call helper methods on helper instance. | require 'spec_helper'
module ApplicationHelper
def resource
@resource ||= FactoryGirl.create(:vacancy)
end
end
describe ApplicationHelper do
describe '#general_attribute?' do
it 'principally works' do
general_attribute?(:state).should == true
general_attribute?(:limit).should == false
en... | require 'spec_helper'
module ApplicationHelper
def resource
@resource ||= FactoryGirl.create(:vacancy)
end
end
describe ApplicationHelper do
describe '#general_attribute?' do
it 'principally works' do
helper.general_attribute?(:state).should == true
helper.general_attribute?(:limit).should =... |
Add info to comment factory | FactoryGirl.define do
factory :user do
sequence(:username) { |n| "user#{n}"}
# sequence(:email) {|n| "email#{n}@gmail.com" }
password "password"
end
factory :fluency do
end
factory :language do
end
factory :query do
sequence(:english) {|n| "Hello #{n}"}
title "Need help"
descrip... | FactoryGirl.define do
factory :user do
sequence(:username) { |n| "user#{n}"}
sequence(:email) {|n| "email#{n}@gmail.com" }
password "password"
end
factory :fluency do
end
factory :language do
end
factory :query do
sequence(:english) {|n| "Hello #{n}"}
title "Need help"
descripti... |
Update unit tests for latest version of chefspec | require 'spec_helper'
describe 'g5-postgresql::default' do
let(:chef_run) do
ChefSpec::Runner.new do |node|
node.set['postgresql']['password']['postgres'] = postgres_password
end.converge(described_recipe)
end
let(:postgres_password) { 'my_secret' }
let(:version) { chef_run.node.postgresql['vers... | require 'spec_helper'
describe 'g5-postgresql::default' do
before do
# Stub command that cookbook uses to determine if postgresql is
# already installed
stub_command('ls /var/lib/postgresql/9.3/main/recovery.conf').and_return('')
end
let(:chef_run) do
ChefSpec::SoloRunner.new do |node|
nod... |
Use to_json to generate the REST responses | require 'sinatra/base'
require 'rest/helpers'
require 'ws/ws_server'
require 'common/model'
require 'common/patches'
require 'common/util'
module Ldash
class RestServer < Sinatra::Base
set :port, 6601
helpers RestHelpers
post '/l-/session' do
data = json!
$session = Session.new
$... | require 'sinatra/base'
require 'json'
require 'rest/helpers'
require 'ws/ws_server'
require 'common/model'
require 'common/patches'
require 'common/util'
module Ldash
class RestServer < Sinatra::Base
set :port, 6601
helpers RestHelpers
post '/l-/session' do
data = json!
$session = Sess... |
Simplify the audits controller a bit more. | class AuditsController < ApplicationController
# GET /audits
# GET /audits.json
def index
if params[:start_date] and params[:end_date]
@start_date = parse_date params[:start_date]
@end_date = parse_date params[:end_date]
@audits = Audit.where("created_at >= :start_date AND created_at <= :end... | class AuditsController < ApplicationController
# GET /audits
# GET /audits.json
def index
if params[:start_date] and params[:end_date]
@start_date = parse_date params[:start_date]
@end_date = parse_date params[:end_date]
@audits = Audit.where(created_at: (@start_date..@end_date))
else
... |
Use pure delegate in Spree::Gateway, compared with delegate_belongs_to | module Spree
class Gateway < PaymentMethod
delegate_belongs_to :provider, :authorize, :purchase, :capture, :void, :credit
validates :name, :type, presence: true
preference :server, :string, default: 'test'
preference :test_mode, :boolean, default: true
def payment_source_class
CreditCard
... | module Spree
class Gateway < PaymentMethod
delegate :authorize, :purchase, :capture, :void, :credit, to: :provider
validates :name, :type, presence: true
preference :server, :string, default: 'test'
preference :test_mode, :boolean, default: true
def payment_source_class
CreditCard
end... |
Use fetch, and ff-only merge | require 'fileutils'
pulled, skipped, failed = [], [], []
root = ARGF.argv[0]
raise ArgumentError.new("Please pass a root directoy!") if root.nil?
raise ArgumentError.new("Please pass a valid root directoy!") unless File.directory?(root)
Dir.foreach(root) do |directory|
if File.directory?(directory)
FileUtils.... | require 'fileutils'
pulled, skipped, failed = [], [], []
root = ARGF.argv[0]
raise ArgumentError.new("Please pass a root directoy!") if root.nil?
raise ArgumentError.new("Please pass a valid root directoy!") unless File.directory?(root)
Dir.foreach(root) do |directory|
if File.directory?(directory)
FileUtils.... |
Remove initialization, no longer needed. | # -*- encoding: utf-8 -*-
module TTY
class Table
class Border
# A class that represents no border.
class Null < Border
# @api private
def initialize(row)
@row = row
@widths = row.map { |cell| cell.chars.to_a.size }
end
# A stub top line
#... | # -*- encoding: utf-8 -*-
module TTY
class Table
class Border
# A class that represents no border.
class Null < Border
# A stub top line
#
# @api private
def top_line
nil
end
# A stub separator line
#
# @api private
... |
Update tests to new rspec standards | require 'matrix'
require 'vector'
describe Vector do
before :each do
@v = Vector[-0.1, -0.9, -10]
end
it "has an x-coordinate" do
expect(@v.x).to eq(-0.1)
end
it "has an y-coordinate" do
expect(@v.y).to eq(-0.9)
end
it "has an z-coordinate" do
expect(@v.z).to eq(-10)
end
context "squaring... | require 'matrix'
require 'vector'
describe Vector do
before :each do
@v = Vector[-0.1, -0.9, -10]
end
context "accessing vector components" do
it "has an x-coordinate" do
expect(@v.x).to eq(-0.1)
end
it "has an y-coordinate" do
expect(@v.y).to eq(-0.9)
end
it "has an z-coordinate... |
Make actionpack a dev dependency only | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'strong_routes/version'
Gem::Specification.new do |spec|
spec.name = "strong_routes"
spec.version = StrongRoutes::VERSION
spec.authors = ["Adam Hutchison"]
spec.email ... | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'strong_routes/version'
Gem::Specification.new do |spec|
spec.name = "strong_routes"
spec.version = StrongRoutes::VERSION
spec.authors = ["Adam Hutchison"]
spec.email ... |
Use task queue for set/unset node maintenance | module ManageIQ::Providers::Openstack::InfraManager::Host::Operations
include ActiveSupport::Concern
def ironic_fog_node
connection_options = {:service => "Baremetal"}
ext_management_system.with_provider_connection(connection_options) do |service|
service.nodes.get(uid_ems)
end
end
def set_n... | module ManageIQ::Providers::Openstack::InfraManager::Host::Operations
include ActiveSupport::Concern
def ironic_fog_node
connection_options = {:service => "Baremetal"}
ext_management_system.with_provider_connection(connection_options) do |service|
service.nodes.get(uid_ems)
end
end
def set_n... |
Use generic mapping fetcher for AGO mappings | #!/usr/bin/env ruby -w
require 'csv'
require 'uri'
require 'net/http'
require 'pathname'
class FetchAgoMappings
def fetch
CSV.open(output_file, "w:utf-8") do |output_csv|
puts "Writing AGO mappings to #{output_file}"
output_csv << ['Old Url','New Url','Status']
i = 0
input_csv.sort_by {|... | #!/usr/bin/env ruby -w
require_relative "mapping_fetcher"
fetcher = MappingFetcher.new(
"https://docs.google.com/spreadsheet/pub?key=0AiP6zL-gKn64dFZ4UWJoeXR4eV9TTFk3SVl6VTQzQ2c&single=true&gid=0&output=csv",
"ago"
)
fetcher.fetch
|
Add the themes to the search path. | # Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional ... | # Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional ... |
Add issued date to medical safety alerts | class MedicalSafetyAlertPresenter < DocumentPresenter
delegate(
:alert_type,
:medical_specialism,
to: :"document.details"
)
def format_name
"Medical safety alert"
end
def finder_path
"/drug-device-alerts"
end
private
def filterable_metadata
{
alert_type: alert_type,
... | class MedicalSafetyAlertPresenter < DocumentPresenter
delegate(
:alert_type,
:medical_specialism,
:issued_date,
to: :"document.details"
)
def format_name
"Medical safety alert"
end
def finder_path
"/drug-device-alerts"
end
private
def filterable_metadata
{
alert_type: ... |
Add a require of by_daily_time_field | require 'monkey_patch_activerecord'
require 'monkey_patch_postgres'
require 'monkey_patch_redshift'
require 'partitioned/active_record_overrides'
require 'partitioned/partitioned_base/configurator.rb'
require 'partitioned/partitioned_base/configurator/data'
require 'partitioned/partitioned_base/configurator/dsl'
requi... | require 'monkey_patch_activerecord'
require 'monkey_patch_postgres'
require 'monkey_patch_redshift'
require 'partitioned/active_record_overrides'
require 'partitioned/partitioned_base/configurator.rb'
require 'partitioned/partitioned_base/configurator/data'
require 'partitioned/partitioned_base/configurator/dsl'
requi... |
Change to document windows api calls | # encoding: utf-8
require 'fiddle'
module TTY
class Prompt
class Reader
module WinAPI
include Fiddle
Handle = RUBY_VERSION >= "2.0.0" ? Fiddle::Handle : DL::Handle
CRT_HANDLE = Handle.new("msvcrt") rescue Handle.new("crtdll")
def getch
@@getch ||= Fiddle::Funct... | # encoding: utf-8
require 'fiddle'
module TTY
class Prompt
class Reader
module WinAPI
include Fiddle
Handle = RUBY_VERSION >= "2.0.0" ? Fiddle::Handle : DL::Handle
CRT_HANDLE = Handle.new("msvcrt") rescue Handle.new("crtdll")
# Get a character from the console without ec... |
Add missing end of input | require 'rails_helper'
RSpec.describe Question, type: :model do
before(:each) do
@comment= FactoryGirl.create(:comment_question)
@vote= FactoryGirl.create(:vote_question)
end
describe 'polymorphism' do
context 'FactoryGirl'do
it 'Question polymorphism is associated' do
expect(@comm... | require 'rails_helper'
RSpec.describe Question, type: :model do
before(:each) do
@comment= FactoryGirl.create(:comment_question)
@vote= FactoryGirl.create(:vote_question)
end
describe 'polymorphism' do
context 'FactoryGirl'do
it 'Question polymorphism is associated' do
expect(@comm... |
Remove direct dependency on yum | name 'omnibus'
maintainer 'Chef Software, Inc.'
maintainer_email 'cookbooks@opscode.com'
license 'Apache 2.0'
description 'Prepares a machine to be an Omnibus builder.'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '1.2.5'
supports 'cen... | name 'omnibus'
maintainer 'Chef Software, Inc.'
maintainer_email 'cookbooks@opscode.com'
license 'Apache 2.0'
description 'Prepares a machine to be an Omnibus builder.'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '1.2.5'
supports 'cen... |
Fix typo on the constraint | name 'chef-server'
version '5.1.0'
maintainer 'Chef Software, Inc.'
maintainer_email 'cookbooks@chef.io'
license 'Apache 2.0'
description 'Installs and configures Chef Server 12'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
depends 'chef-ingredient', '~ 1.1'
supports 'redhat'
supports 'cent... | name 'chef-server'
version '5.1.0'
maintainer 'Chef Software, Inc.'
maintainer_email 'cookbooks@chef.io'
license 'Apache 2.0'
description 'Installs and configures Chef Server 12'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
depends 'chef-ingredient', '~> 1.1'
supports 'redhat'
supports 'cen... |
Add more specific platform constraint. | name 'letsencrypt-boulder-server'
maintainer 'Thijs Houtenbos'
maintainer_email 'thoutenbos@schubergphilis.com'
license 'All rights reserved'
description "Installs/Configures Boulder, the ACME-based CA server by Let's Encrypt."
long_description IO.read(File.join(File.dirname(__FILE__), '... | name 'letsencrypt-boulder-server'
maintainer 'Thijs Houtenbos'
maintainer_email 'thoutenbos@schubergphilis.com'
license 'All rights reserved'
description "Installs/Configures Boulder, the ACME-based CA server by Let's Encrypt."
long_description IO.read(File.join(File.dirname(__FILE__), '... |
Update DCTVBot to handle Ctrl-C and Kill | require 'cinch'
class DCTVBot < Cinch::Bot
def initialize(*args)
super
end
end
| class DCTVBot < Cinch::Bot
def initialize(&b)
super
# Handle SIGINT (Ctrl-C)
trap "SIGINT" do
debug "Caught SIGINT, quitting..."
self.quit
end
# Handle SIGTERM (Kill Command)
trap "SIGTERM" do
debug "Caught SIGTERM, quitting..."
self.quit
end
end
end
|
Fix repo owner in version check | require_relative './version'
# Mix this module into the main application module to provide
# information about the current version, latest version,
# and whether the app is up-to-date.
#
# In config/application.rb:
#
# module OneBody
# extend VersionInfo
# end
#
module VersionInfo
GITHUB_REPO_OWNER = '... | require_relative './version'
# Mix this module into the main application module to provide
# information about the current version, latest version,
# and whether the app is up-to-date.
#
# In config/application.rb:
#
# module OneBody
# extend VersionInfo
# end
#
module VersionInfo
GITHUB_REPO_OWNER = '... |
Remove duplicate set_has_gallery from GalleriesIcon | class GalleriesIcon < ActiveRecord::Base
belongs_to :icon
belongs_to :gallery
accepts_nested_attributes_for :icon, allow_destroy: true
after_create :set_has_gallery
after_destroy :unset_has_gallery
validates :gallery_id, uniqueness: { scope: :icon_id }
def set_has_gallery
icon.update_attributes(has_... | class GalleriesIcon < ActiveRecord::Base
belongs_to :icon
belongs_to :gallery
accepts_nested_attributes_for :icon, allow_destroy: true
after_create :set_has_gallery
after_destroy :unset_has_gallery
validates :gallery_id, uniqueness: { scope: :icon_id }
def unset_has_gallery
return if icon.galleries.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.