hexsha
stringlengths
40
40
size
int64
2
1.01M
content
stringlengths
2
1.01M
avg_line_length
float64
1.5
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
1
91b22b37c9cd5192858763f9da81a9d87f7452b1
1,685
require 'rails_helper' RSpec.describe NotifyBillingChanges, type: :service do let(:organization) { create(:organization_without_groups, active_users_count: active_users_count) } let(:active_users_initial_count) { 10 } let(:billable_users_count) { 10 } let(:active_users_count) { 20 } subject(:context) do NotifyBillingChanges.call( organization: organization, active_users_initial_count: active_users_initial_count, billable_users_count: billable_users_count, ) end describe '#call' do before do allow(BillingChangesMailer).to receive_message_chain(:notify, :deliver_later) end context 'with billable users' do let(:billable_users_count) { 10 } context 'with an increase in active users' do let(:active_users_count) { 15 } let(:active_users_initial_count) { 10 } it 'calls the BillingChangesMailer' do expect(BillingChangesMailer).to receive(:notify).with( organization.id, 5, ) expect(context).to be_a_success end end context 'without an increase in active users' do let(:active_users_count) { 9 } let(:active_users_initial_count) { 10 } it 'does not call the BillingChangesMailer' do expect(BillingChangesMailer).not_to receive(:notify) expect(context).to be_a_success end end end context 'with zero billable users' do let(:billable_users_count) { 0 } it 'does not call the BillingChangesMailer' do expect(BillingChangesMailer).not_to receive(:notify) expect(context).to be_a_success end end end end
29.051724
101
0.67181
f7100ca4af945c9a2d128a37fa2cafa91390b363
1,215
# This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # Require this file using `require "spec_helper"` to ensure that it is only # loaded once. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration require_relative "../lib/octopolo" Octopolo.instance_variable_set(:@config, Octopolo::Config.new({:deploy_branch => "master"})) RSpec.configure do |config| config.deprecation_stream = 'log/deprecations.log' config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.filter_run :focus # environment restoration lifted from facter project # https://github.com/puppetlabs/facter/commit/6e29ff7165b8bb63d1deeff6502a0195fa3974e5 config.before :each do # Store any environment variables away to be restored later @old_env = {} ENV.each_key {|k| @old_env[k] = ENV[k]} end config.after :each do # Restore environment variables after execution of each test @old_env.each_pair {|k, v| ENV[k] = v} to_remove = ENV.keys.reject {|key| @old_env.include? key } to_remove.each {|key| ENV.delete key } end end
39.193548
92
0.745679
ed8cfa1a5530594e64f13084a7df411e4ffc7753
24
Pagy::VARS[:items] = 10
12
23
0.625
874b25a4f45a51c11269e1596be79f2e7e9bcd2b
586
Warden::Manager.after_authentication do |user, auth, options| if user.respond_to?(:need_two_factor_authentication?) if auth.session(options[:scope])[:need_two_factor_authentication] = user.need_two_factor_authentication?(auth.request) tfa_cookie = auth.cookies.signed["tfa_token"] unless tfa_cookie.presence && User.serialize_tfa_from_cookie(*tfa_cookie) code = user.generate_two_factor_code user.second_factor_pass_code = Digest::MD5.hexdigest(code) user.save user.send_two_factor_authentication_code(code) end end end end
41.857143
122
0.749147
87ae2fd6cc4ffe5ce568c13f0aefae795c37a02e
20,837
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Layout::RescueEnsureAlignment, :config do it 'accepts the modifier form' do expect_no_offenses('test rescue nil') end context 'rescue with begin' do it 'registers an offense' do expect_offense(<<~RUBY) begin something rescue ^^^^^^ `rescue` at 3, 4 is not aligned with `begin` at 1, 0. error end RUBY expect_correction(<<~RUBY) begin something rescue error end RUBY end context 'as RHS of assignment' do let(:cop_config) do { 'EnforcedStyle' => 'require_parentheses' } end context 'when `EnforcedStyleAlignWith: start_of_line` of `Layout/BeginEndAlignment` cop' do let(:other_cops) do { 'Layout/BeginEndAlignment' => { 'EnforcedStyleAlignWith' => 'start_of_line' } } end it 'accepts multi-line, aligned' do expect_no_offenses(<<~RUBY) x ||= begin 1 rescue 2 end RUBY end it 'accepts multi-line, indented' do expect_no_offenses(<<~RUBY) x ||= begin 1 rescue 2 end RUBY end it 'registers an offense and corrects for incorrect alignment' do expect_offense(<<~RUBY) x ||= begin 1 rescue ^^^^^^ `rescue` at 3, 6 is not aligned with `x ||= begin` at 1, 0. 2 end RUBY # Except for `rescue`, it will be aligned by `Layout/BeginEndAlignment` auto-correction. expect_correction(<<~RUBY) x ||= begin 1 rescue 2 end RUBY end end context 'when `EnforcedStyleAlignWith: begin` of `Layout/BeginEndAlignment` cop' do let(:other_cops) do { 'Layout/BeginEndAlignment' => { 'EnforcedStyleAlignWith' => 'begin' } } end it 'accepts multi-line, aligned' do expect_no_offenses(<<~RUBY) x ||= begin 1 rescue 2 end RUBY end it 'accepts multi-line, indented' do expect_no_offenses(<<~RUBY) x ||= begin 1 rescue 2 end RUBY end it 'registers an offense and corrects for incorrect alignment' do expect_offense(<<~RUBY) x ||= begin 1 rescue ^^^^^^ `rescue` at 3, 0 is not aligned with `begin` at 1, 6. 2 end RUBY # Except for `rescue`, it will be aligned by `Layout/BeginEndAlignment` auto-correction. expect_correction(<<~RUBY) x ||= begin 1 rescue 2 end RUBY end end end end context 'rescue with def' do it 'registers an offense' do expect_offense(<<~RUBY) def test something rescue ^^^^^^ `rescue` at 3, 4 is not aligned with `def test` at 1, 0. error end RUBY expect_correction(<<~RUBY) def test something rescue error end RUBY end end context 'rescue with defs' do it 'registers an offense' do expect_offense(<<~RUBY) def Test.test something rescue ^^^^^^ `rescue` at 3, 4 is not aligned with `def Test.test` at 1, 0. error end RUBY expect_correction(<<~RUBY) def Test.test something rescue error end RUBY end end context 'rescue with class' do it 'registers an offense when rescue used with class' do expect_offense(<<~RUBY) class C something rescue ^^^^^^ `rescue` at 3, 4 is not aligned with `class C` at 1, 0. error end RUBY expect_correction(<<~RUBY) class C something rescue error end RUBY end end context 'rescue with module' do it 'registers an offense when rescue used with module' do expect_offense(<<~RUBY) module M something rescue ^^^^^^ `rescue` at 3, 4 is not aligned with `module M` at 1, 0. error end RUBY expect_correction(<<~RUBY) module M something rescue error end RUBY end end context 'ensure with begin' do it 'registers an offense when ensure used with begin' do expect_offense(<<~RUBY) begin something ensure ^^^^^^ `ensure` at 3, 4 is not aligned with `begin` at 1, 0. error end RUBY expect_correction(<<~RUBY) begin something ensure error end RUBY end end context 'ensure with def' do it 'registers an offense' do expect_offense(<<~RUBY) def test something ensure ^^^^^^ `ensure` at 3, 4 is not aligned with `def test` at 1, 0. error end RUBY expect_correction(<<~RUBY) def test something ensure error end RUBY end end context 'ensure with defs' do it 'registers an offense' do expect_offense(<<~RUBY) def Test.test something ensure ^^^^^^ `ensure` at 3, 4 is not aligned with `def Test.test` at 1, 0. error end RUBY expect_correction(<<~RUBY) def Test.test something ensure error end RUBY end end context 'ensure with class' do it 'registers an offense' do expect_offense(<<~RUBY) class C something ensure ^^^^^^ `ensure` at 3, 4 is not aligned with `class C` at 1, 0. error end RUBY expect_correction(<<~RUBY) class C something ensure error end RUBY end end context 'ensure with module' do it 'registers an offense when ensure used with module' do expect_offense(<<~RUBY) module M something ensure ^^^^^^ `ensure` at 3, 4 is not aligned with `module M` at 1, 0. error end RUBY expect_correction(<<~RUBY) module M something ensure error end RUBY end end it 'accepts end being misaligned' do expect_no_offenses(<<~RUBY) def method1 'foo' end def method2 'bar' rescue 'baz' end RUBY end it 'accepts rescue and ensure on the same line' do expect_no_offenses('begin; puts 1; rescue; ensure; puts 2; end') end it 'accepts correctly aligned rescue' do expect_no_offenses(<<~RUBY) begin something rescue error end RUBY end it 'accepts correctly aligned ensure' do expect_no_offenses(<<~RUBY) begin something ensure error end RUBY end it 'accepts correctly aligned rescue in assigned begin-end block' do expect_no_offenses(<<-RUBY) foo = begin bar rescue BazError qux end RUBY end context '>= Ruby 2.5', :ruby25 do it 'accepts aligned rescue in do-end block' do expect_no_offenses(<<~RUBY) [1, 2, 3].each do |el| el.to_s rescue StandardError => _exception next end RUBY end it 'accepts aligned rescue do-end block assigned to local variable' do expect_no_offenses(<<~RUBY) result = [1, 2, 3].map do |el| el.to_s rescue StandardError => _exception next end RUBY end it 'accepts aligned rescue in do-end block assigned to instance variable' do expect_no_offenses(<<~RUBY) @instance = [].map do |_| rescue StandardError => _ end RUBY end it 'accepts aligned rescue in do-end block assigned to class variable' do expect_no_offenses(<<~RUBY) @@class = [].map do |_| rescue StandardError => _ end RUBY end it 'accepts aligned rescue in do-end block assigned to global variable' do expect_no_offenses(<<~RUBY) $global = [].map do |_| rescue StandardError => _ end RUBY end it 'accepts aligned rescue in do-end block assigned to class' do expect_no_offenses(<<~RUBY) CLASS = [].map do |_| rescue StandardError => _ end RUBY end it 'accepts aligned rescue in do-end block on multi-assignment' do expect_no_offenses(<<~RUBY) a, b = [].map do |_| rescue StandardError => _ end RUBY end it 'accepts aligned rescue in do-end block on operation assignment' do expect_no_offenses(<<~RUBY) a += [].map do |_| rescue StandardError => _ end RUBY end it 'accepts aligned rescue in do-end block on and-assignment' do expect_no_offenses(<<~RUBY) a &&= [].map do |_| rescue StandardError => _ end RUBY end it 'accepts aligned rescue in do-end block on or-assignment' do expect_no_offenses(<<~RUBY) a ||= [].map do |_| rescue StandardError => _ end RUBY end it 'accepts aligned rescue in assigned do-end block starting on newline' do expect_no_offenses(<<~RUBY) valid = proc do |bar| baz rescue qux end RUBY end it 'accepts aligned rescue in do-end block in a method' do expect_no_offenses(<<~RUBY) def foo [1, 2, 3].each do |el| el.to_s rescue StandardError => _exception next end end RUBY end context 'rescue with do-end block' do it 'registers an offense' do expect_offense(<<~RUBY) def foo [1, 2, 3].each do |el| el.to_s rescue StandardError => _exception ^^^^^^ `rescue` at 4, 0 is not aligned with `[1, 2, 3].each do` at 2, 2. next end end RUBY expect_correction(<<~RUBY) def foo [1, 2, 3].each do |el| el.to_s rescue StandardError => _exception next end end RUBY end end context 'rescue in do-end block assigned to local variable' do it 'registers an offense' do expect_offense(<<~RUBY) result = [1, 2, 3].map do |el| rescue StandardError => _exception ^^^^^^ `rescue` at 2, 2 is not aligned with `result` at 1, 0. end RUBY expect_correction(<<~RUBY) result = [1, 2, 3].map do |el| rescue StandardError => _exception end RUBY end end context 'rescue in do-end block assigned to instance variable' do it 'registers an offense' do expect_offense(<<~RUBY) @instance = [1, 2, 3].map do |el| rescue StandardError => _exception ^^^^^^ `rescue` at 2, 2 is not aligned with `@instance` at 1, 0. end RUBY expect_correction(<<~RUBY) @instance = [1, 2, 3].map do |el| rescue StandardError => _exception end RUBY end end context 'rescue in do-end block assigned to class variable' do it 'registers an offense' do expect_offense(<<~RUBY) @@class = [].map do |_| rescue StandardError => _ ^^^^^^ `rescue` at 2, 2 is not aligned with `@@class` at 1, 0. end RUBY expect_correction(<<~RUBY) @@class = [].map do |_| rescue StandardError => _ end RUBY end end context 'rescue in do-end block assigned to global variable' do it 'registers an offense' do expect_offense(<<~RUBY) $global = [].map do |_| rescue StandardError => _ ^^^^^^ `rescue` at 2, 2 is not aligned with `$global` at 1, 0. end RUBY expect_correction(<<~RUBY) $global = [].map do |_| rescue StandardError => _ end RUBY end end context 'rescue in do-end block assigned to class' do it 'registers an offense' do expect_offense(<<~RUBY) CLASS = [].map do |_| rescue StandardError => _ ^^^^^^ `rescue` at 2, 2 is not aligned with `CLASS` at 1, 0. end RUBY expect_correction(<<~RUBY) CLASS = [].map do |_| rescue StandardError => _ end RUBY end end context 'rescue in do-end block on multi-assignment' do it 'registers an offense' do expect_offense(<<~RUBY) a, b = [].map do |_| rescue StandardError => _ ^^^^^^ `rescue` at 2, 2 is not aligned with `a, b` at 1, 0. end RUBY expect_correction(<<~RUBY) a, b = [].map do |_| rescue StandardError => _ end RUBY end end context 'rescue in do-end block on operation assignment' do it 'registers an offense' do expect_offense(<<~RUBY) a += [].map do |_| rescue StandardError => _ ^^^^^^ `rescue` at 2, 2 is not aligned with `a` at 1, 0. end RUBY expect_correction(<<~RUBY) a += [].map do |_| rescue StandardError => _ end RUBY end end context 'rescue in do-end block on and-assignment' do it 'registers an offense' do expect_offense(<<~RUBY) a &&= [].map do |_| rescue StandardError => _ ^^^^^^ `rescue` at 2, 2 is not aligned with `a` at 1, 0. end RUBY expect_correction(<<~RUBY) a &&= [].map do |_| rescue StandardError => _ end RUBY end end context 'rescue in do-end block on or-assignment' do it 'registers an offense' do expect_offense(<<~RUBY) a ||= [].map do |_| rescue StandardError => _ ^^^^^^ `rescue` at 2, 2 is not aligned with `a` at 1, 0. end RUBY expect_correction(<<~RUBY) a ||= [].map do |_| rescue StandardError => _ end RUBY end end context 'rescue in assigned do-end block starting on newline' do it 'registers an offense' do expect_offense(<<~RUBY) valid = proc do |bar| baz rescue ^^^^^^ `rescue` at 4, 4 is not aligned with `proc do` at 2, 2. qux end RUBY expect_correction(<<~RUBY) valid = proc do |bar| baz rescue qux end RUBY end end end describe 'excluded file' do subject(:cop) { described_class.new(config) } let(:config) do RuboCop::Config.new('Layout/RescueEnsureAlignment' => { 'Enabled' => true, 'Exclude' => ['**/**'] }) end it 'processes excluded files with issue' do expect_no_offenses(<<~RUBY, 'foo.rb') begin foo rescue bar end RUBY end end context 'allows inline access modifier' do let(:cop_config) do { 'Style/AccessModifierDeclarations' => { 'EnforcedStyle' => 'inline' } } end shared_examples 'access modifier' do |modifier| context 'rescue with def' do it 'registers an offense' do expect_offense(<<~RUBY) #{modifier} def test 'foo' rescue ^^^^^^ `rescue` at 3, 2 is not aligned with `#{modifier} def test` at 1, 0. 'baz' end RUBY expect_correction(<<~RUBY) #{modifier} def test 'foo' rescue 'baz' end RUBY end it 'correct alignment' do expect_no_offenses(<<~RUBY) #{modifier} def test 'foo' rescue 'baz' end RUBY end end context 'rescue with defs' do it 'registers an offense' do expect_offense(<<~RUBY) #{modifier} def Test.test 'foo' rescue ^^^^^^ `rescue` at 3, 2 is not aligned with `#{modifier} def Test.test` at 1, 0. 'baz' end RUBY expect_correction(<<~RUBY) #{modifier} def Test.test 'foo' rescue 'baz' end RUBY end it 'correct alignment' do expect_no_offenses(<<~RUBY) #{modifier} def Test.test 'foo' rescue 'baz' end RUBY end end context 'ensure with def' do it 'registers an offense' do expect_offense(<<~RUBY) #{modifier} def test 'foo' ensure ^^^^^^ `ensure` at 3, 2 is not aligned with `#{modifier} def test` at 1, 0. 'baz' end RUBY expect_correction(<<~RUBY) #{modifier} def test 'foo' ensure 'baz' end RUBY end it 'correct alignment' do expect_no_offenses(<<~RUBY) #{modifier} def test 'foo' ensure 'baz' end RUBY end end context 'ensure with defs' do it 'registers an offense' do expect_offense(<<~RUBY) #{modifier} def Test.test 'foo' ensure ^^^^^^ `ensure` at 3, 2 is not aligned with `#{modifier} def Test.test` at 1, 0. 'baz' end RUBY expect_correction(<<~RUBY) #{modifier} def Test.test 'foo' ensure 'baz' end RUBY end it 'correct alignment' do expect_no_offenses(<<~RUBY) #{modifier} def Test.test 'foo' ensure 'baz' end RUBY end end end context 'with private modifier' do include_examples 'access modifier', 'private' end context 'with private_class_method modifier' do include_examples 'access modifier', 'private_class_method' end context 'with public_class_method modifier' do include_examples 'access modifier', 'public_class_method' end end context 'allows inline expression before' do context 'rescue' do it 'registers an offense' do expect_offense(<<~RUBY) def test 'foo'; rescue; 'baz' ^^^^^^ `rescue` at 2, 9 is not aligned with `def test` at 1, 0. end def test begin 'foo'; rescue; 'baz' ^^^^^^ `rescue` at 7, 11 is not aligned with `begin` at 6, 2. end end RUBY expect_no_corrections end end context 'ensure' do it 'registers an offense' do expect_offense(<<~RUBY) def test 'foo'; ensure; 'baz' ^^^^^^ `ensure` at 2, 9 is not aligned with `def test` at 1, 0. end def test begin 'foo'; ensure; 'baz' ^^^^^^ `ensure` at 7, 11 is not aligned with `begin` at 6, 2. end end RUBY expect_no_corrections end end end end
23.46509
98
0.484427
1c1656219fbf8dc2ecffdc6452cdd0672804af73
2,491
# frozen_string_literal: false # # shell/builtin-command.rb - # $Release Version: 0.7 $ # $Revision: 65505 $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require_relative "filter" class Shell class BuiltInCommand < Filter def wait? false end def active? true end end class Void < BuiltInCommand def initialize(sh, *opts) super sh end def each(rs = nil) # do nothing end end class Echo < BuiltInCommand def initialize(sh, *strings) super sh @strings = strings end def each(rs = nil) rs = @shell.record_separator unless rs for str in @strings yield str + rs end end end class Cat < BuiltInCommand def initialize(sh, *filenames) super sh @cat_files = filenames end def each(rs = nil) if @cat_files.empty? super else for src in @cat_files @shell.foreach(src, rs){|l| yield l} end end end end class Glob < BuiltInCommand def initialize(sh, pattern) super sh @pattern = pattern end def each(rs = nil) if @pattern[0] == ?/ @files = Dir[@pattern] else prefix = @shell.pwd+"/" @files = Dir[prefix+@pattern].collect{|p| p.sub(prefix, "")} end rs = @shell.record_separator unless rs for f in @files yield f+rs end end end class AppendIO < BuiltInCommand def initialize(sh, io, filter) super sh @input = filter @io = io end def input=(filter) @input.input=filter for l in @input @io << l end end end class AppendFile < AppendIO def initialize(sh, to_filename, filter) @file_name = to_filename io = sh.open(to_filename, "a") super(sh, io, filter) end def input=(filter) begin super ensure @io.close end end end class Tee < BuiltInCommand def initialize(sh, filename) super sh @to_filename = filename end def each(rs = nil) to = @shell.open(@to_filename, "w") begin super{|l| to << l; yield l} ensure to.close end end end class Concat < BuiltInCommand def initialize(sh, *jobs) super(sh) @jobs = jobs end def each(rs = nil) while job = @jobs.shift job.each{|l| yield l} end end end end
16.831081
68
0.549177
1a82bb9ffe03c0e45d0af5313f28719086a6e1e9
448
# class TagCounter attr_reader :tags_count def initialize @tags_count = {} end # common_tag - used for ? def count_tags(file, _common_tag = nil) SourceReader.new(file).each_card do |tags, _front, _back| register_tags(tags) end file.rewind @tags_count end def register_tags(tags) tags.each do |tag| count = @tags_count[tag] || 0 count += 1 @tags_count[tag] = count end end end
16.592593
61
0.631696
117cbe4e467cd20b2dce5a252fd3fad4a7b1f387
1,646
# # Be sure to run `pod lib lint JSLabel.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'JSLabel' s.version = '0.1.0' s.summary = 'A simple designable subclass on UILabel with extra features.' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC This CocoaPod provides the ability to use a UILabel with extra feautures you can set from Xcode. DESC s.homepage = 'https://github.com/imjog/JSLabel' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'Jogendra Singh' => 'imjog24@gmail.com' } s.source = { :git => 'https://github.com/imjog/JSLabel.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/jogendra_iitbhu' s.ios.deployment_target = '8.0' s.source_files = 'JSLabel/Classes/**/*' # s.resource_bundles = { # 'JSLabel' => ['JSLabel/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' end
38.27907
97
0.642163
1dd49bd703be300644d27c0eeca35f67a94bb34c
570
cask 'unity' do version '2018.2.5f1,3071d1717b71' sha256 '831e7109280b20f26ebe3f2562a2ea9590684afb9a38b5cabd61818328628cc7' url "https://netstorage.unity3d.com/unity/#{version.after_comma}/MacEditorInstaller/Unity.pkg" appcast 'https://unity3d.com/get-unity/download/archive' name 'Unity Editor' homepage 'https://unity3d.com/unity/' pkg 'Unity.pkg' uninstall quit: 'com.unity3d.UnityEditor5.x', pkgutil: 'com.unity3d.UnityEditor5.x', delete: '/Applications/Unity/Unity.app', rmdir: '/Applications/Unity' end
33.529412
96
0.712281
7970c462d36fb0adc510b115aff3a21ee9836a2a
8,221
class UserMailer < ApplicationMailer def welcome(user) if user.email.present? mail({to: user.email, subject: "Thank you for registering."}) do |format| format.text end end end def plan_shopping_completed(user, hbx_enrollment, plan_decorator) if user.email.present? mail({to: user.email, subject: "Your #{Settings.site.short_name} Enrollment Confirmation"}) do |format| format.html { render "plan_shopping_completed", :locals => { :user => user, :enrollment => hbx_enrollment, :plan => plan_decorator } } end end end def invitation_email(email, person_name, invitation) if email.present? mail({to: email, subject: "Invitation from your Employer to Sign up for Health Insurance at #{Settings.site.short_name} "}) do |format| format.html { render "invitation_email", :locals => { :person_name => person_name, :invitation => invitation }} end end end def send_employee_open_enrollment_invitation(email, census_employee, invitation) plan_years = census_employee.employer_profile.plan_years.published_or_renewing_published.select{|py| py.coverage_period_contains?(census_employee.earliest_eligible_date)} if email.present? mail({to: email, subject: "Invitation from your Employer to Sign up for Health Insurance at #{Settings.site.short_name} "}) do |format| if census_employee.hired_on > TimeKeeper.date_of_record format.html { render "invite_future_employee_for_open_enrollment", :locals => { :census_employee => census_employee, :invitation => invitation }} elsif census_employee.hired_on <= TimeKeeper.date_of_record && plan_years.any?{|py| py.employees_are_matchable?} format.html { render "invite_initial_employee_for_open_enrollment", :locals => { :census_employee => census_employee, :invitation => invitation }} end end end end def renewal_invitation_email(email, census_employee, invitation) mail({to: email, subject: "Enroll Now: Your Health Plan Open Enrollment Period has Begun"}) do |format| format.html { render "renewal_invitation_email", :locals => { :census_employee => census_employee, :invitation => invitation }} end end def initial_employee_invitation_email(email, census_employee, invitation) mail({to: email, subject: "Enroll Now: Your Health Plan Open Enrollment Period has Begun"}) do |format| format.html { render "initial_employee_invitation_email", :locals => { :census_employee => census_employee, :invitation => invitation }} end end def agent_invitation_email(email, person_name, invitation) if email.present? mail({to: email, subject: "DCHealthLink Support Invitation "}) do |format| format.html { render "agent_invitation_email", :locals => { :person_name => person_name, :invitation => invitation }} end end end def broker_invitation_email(email, person_name, invitation) if email.present? mail({to: email, subject: "Invitation to create your Broker account on #{Settings.site.short_name} "}) do |format| format.html { render "broker_invitation_email", :locals => { :person_name => person_name, :invitation => invitation }} end end end def message_to_broker(person, broker, params) if broker.email_address.present? mail({to: broker.email_address, subject: params[:subject], from: person.user.email}) do |format| format.html { render "message_to_broker", :locals => { :person => person, :broker => broker, :message_body => params[:body] }} end end end def send_employee_ineligibility_notice(email, first_name) if email.present? message = mail({to: email, subject: "#{Settings.site.short_name} - Assistance Enrolling in Employer-sponsored Health Insurance", from: 'no-reply@individual.dchealthlink.com'}) do |format| format.html {render "employee_ineligibility_notice", locals: {first_name: first_name}} end end end def new_client_notification(agent_email, first_name, name, role, insured_email, is_person) if agent_email.present? subject = "New Client Notification -[#{name}] email provided - [#{insured_email}]" mail({to: agent_email, subject: subject, from: 'no-reply@individual.dchealthlink.com'}) do |format| format.html { render "new_client_notification", :locals => { first_name: first_name, :role => role, name: name}} end end end def generic_consumer_welcome(first_name, hbx_id, email) if email.present? message = mail({to: email, subject: "DC HealthLink", from: 'no-reply@individual.dchealthlink.com'}) do |format| format.html {render "generic_consumer", locals: {first_name: first_name, hbx_id: hbx_id}} end end end def generic_notice_alert(first_name, notice_subject, email,files_to_attach={}) files_to_attach.each do |file_name, file_path| attachments["#{file_name}"] = File.read(file_path) end message = mail({to: email, subject: "You have a new message from Be Well NM", from: 'no-reply@individual.dchealthlink.com'}) do |format| format.html {render "generic_notice_alert", locals: {first_name: first_name, notice_subject: notice_subject}} end end def generic_notice_alert_to_ba_and_ga(first_name, email, employer_name) if email.present? message = mail({to: email, subject: "You have a new message from Be Well NM", from: 'no-reply@individual.dchealthlink.com'}) do |format| format.html {render "generic_notice_alert_to_broker_and_ga", locals: {first_name: first_name, employer_name: employer_name}} end end end def employer_invoice_generation_notification(employer,subject) message = mail({to: employer.email, subject: subject, from: 'no-reply@individual.dchealthlink.com'}) do |format| format.html {render "employer_invoice_generation", locals: {first_name: employer.person.first_name}} end end def broker_registration_guide(user) attachments['Broker Registration Guide.pdf'] = File.read('public/new_broker_registration.pdf') mail({to: user[:email], subject: "Broker Registration Guide"}) do |format| format.html { render "broker_registration_guide", :locals => { :first_name => user[:first_name]}} end end def broker_denied_notification(broker_role) if broker_role.email_address.present? mail({to: broker_role.email_address, subject: "Broker application denied"}) do |format| format.html { render "broker_denied", :locals => { :applicant_name => broker_role.person.full_name }} end end end def broker_application_confirmation(person) if person.emails.find_by(kind: 'work').address.present? mail({to: person.emails.find_by(kind: 'work').try(:address) , subject: "Thank you for submitting your broker application to #{Settings.site.short_name}"}) do |format| format.html { render "broker_application_confirmation", :locals => { :person => person }} end end end def broker_pending_notification(broker_role,unchecked_carriers) subject_sufix = unchecked_carriers.present? ? ", missing carrier appointments" : ", has all carrier appointments" subject_prefix = broker_role.training || broker_role.training == true ? "Completed NAHU Training" : "Needs to Complete NAHU training" subject="#{subject_prefix}#{subject_sufix}" mail({to: broker_role.email_address, subject: subject}) do |format| if broker_role.training && unchecked_carriers.present? format.html { render "broker_pending_completed_training_missing_carrier", :locals => { :applicant_name => broker_role.person.full_name ,:unchecked_carriers => unchecked_carriers}} elsif !broker_role.training && !unchecked_carriers.present? format.html { render "broker_pending_missing_training_completed_carrier", :locals => { :applicant_name => broker_role.person.full_name , :unchecked_carriers => unchecked_carriers}} elsif !broker_role.training && unchecked_carriers.present? format.html { render "broker_pending_missing_training_and_carrier", :locals => { :applicant_name => broker_role.person.full_name , :unchecked_carriers => unchecked_carriers}} end end end end
50.746914
193
0.720107
bfc36538a1553de05b342b99e123ebac161ed13f
418
### # Copyright (c) 2015, Upnext Technologies Sp. z o.o. # All rights reserved. # # This source code is licensed under the BSD 3-Clause License found in the # LICENSE.txt file in the root directory of this source tree. ### class AddCorrelationIdToUsers < ActiveRecord::Migration def change add_column :admins, :correlation_id, :string add_column :mobile_devices, :correlation_id, :string end end
27.866667
74
0.729665
f72d2696f741f107b16aac87132e2cfc052d0088
842
module Wor module Paginate module Adapters class Base attr_reader :page def initialize(content, page, limit) @content = content @page = page.to_i @limit = limit.to_i raise Wor::Paginate::Exceptions::InvalidPageNumber if @page <= 0 raise Wor::Paginate::Exceptions::InvalidLimitNumber if @limit <= 0 end def adapt? required_methods.all? { |method| @content.respond_to? method } end %i[required_methods paginated_content count total_count next_page].each do |method| define_method(method) { raise NotImplementedError } end delegate :total_pages, to: :paginated_content def next_page return nil if page >= total_pages page + 1 end end end end end
25.515152
91
0.602138
bb1ba3c2e039efe2a4b913c52fbacba1fea5ec15
550
require 'test_helper' class UserMailerTest < ActionMailer::TestCase test "account_activation" do user = users(:michael) user.activation_token = User.new_token mail = UserMailer.account_activation(user) assert_equal "Account activation", mail.subject assert_equal [user.email], mail.to assert_equal ["noreply@example.com"], mail.from assert_match user.name, mail.body.encoded assert_match user.activation_token, mail.body.encoded assert_match CGI.escape(user.email), mail.body.encoded end end
34.375
59
0.732727
9148f5275b6fdae4e6ef5249d972d2634ba12490
139
module ApplicationHelper def render_errors_for(item) render partial: 'layouts/shared/form_errors', locals: { item: item } end end
19.857143
72
0.748201
184b5f42ff8fa3ac6609ce114e6dfedff4bb86f0
3,378
# == Schema Information # # Table name: inwork # # fnavgwkhrs :decimal(6, 2) default(0.0), not null # fcpro_id :string(7) default(""), not null, primary key # fcpro_name :string(16) default(""), not null # fccomments :string(54) default(""), not null # fdept :string(2) default(""), not null # flabcost :decimal(17, 5) default(0.0), not null # fnavgque :decimal(7, 1) default(0.0), not null # flschedule :boolean default(FALSE), not null # fnmax1 :integer default(0), not null # fnmax2 :integer default(0), not null # fnmax3 :integer default(0), not null # fnmaxque :decimal(7, 1) default(0.0), not null # fnpctutil :decimal(6, 1) default(0.0), not null # fnqueallow :decimal(8, 2) default(0.0), not null # fnstd1 :integer default(0), not null # fnstd2 :integer default(0), not null # fnstd3 :integer default(0), not null # fnstd_prod :decimal(11, 6) default(0.0), not null # fnstd_set :decimal(7, 2) default(0.0), not null # fnsumdur :decimal(9, 1) default(0.0), not null # fovrhdcost :decimal(17, 5) default(0.0), not null # fscheduled :string(1) default(""), not null # fspandays :integer default(0), not null # fnpque :decimal(7, 1) default(0.0), not null # flconstrnt :boolean default(FALSE), not null # identity_column :integer not null # timestamp_column :binary # fac :string(20) default(""), not null # fcstdormax :string(8) default(""), not null # fndbrmod :integer default(0), not null # fnloadcapc :decimal(6, 2) default(0.0), not null # fnmaxcapload :decimal(4, 1) default(0.0), not null # flaltset :boolean default(FALSE), not null # fcsyncmisc :string(20) default(""), not null # QueueHrs :decimal(9, 2) default(0.0), not null # ConstBuff :decimal(5, 1) default(0.0), not null # ResGroup :string(15) default(""), not null # flBFLabor :boolean default(FALSE), not null # CycleUnits :decimal(13, 3) default(0.0), not null # SimOpsType :string(10) default(""), not null # Size :decimal(13, 3) default(0.0), not null # CanBreak :boolean default(FALSE), not null # SizeUM :string(3) default("0"), not null # class M2m::WorkCenter < M2m::Base self.table_name = 'inwork' self.primary_key = 'fcpro_id' alias_attribute :work_center_id, :fcpro_id alias_attribute :capacity_constraint, :flconstrnt scope :name_like, lambda { |names| likes = names.map { |n| "(inwork.fcpro_name like \'%#{n}%\')" } { :conditions => likes.join(" OR ") } } scope :work_center_ids, lambda { |ids| { :conditions => ['inwork.fcpro_id in (?)', ids] } } def name fcpro_name.titleize.strip end def short_name @short_name ||= self.name[0..2] + '-' + self.work_center_id end @@cache = {} def self.cached_lookup(id) return nil unless id.present? @@cache[id] ||= M2m::WorkCenter.find(id) end end
39.741176
72
0.551214
f76fd8f9ab1919b3e4af04f0eecea3229567687a
531
module Arboreta class Statement attr_accessor :comparison, :subject, :left_method, :right_method def initialize(args) @comparison = args['comparison'] @subject = args['subject'] @left_method = args['left_method'] @right_method = args['right_method'] end def execute! Arboreta::Comparisons.send(comparison, {left: left, right: right}) end def left subject.arboreta_send(left_method) end def right subject.arboreta_send(right_method) end end end
20.423077
72
0.661017
4a04fa270c2077172ac9a1675368257860912a1e
6,148
class ApplicationController < ActionController::Base protect_from_forgery helper :pagination before_filter :reset_current_user before_filter :set_current_user after_filter :reset_current_user before_filter :set_title before_filter :normalize_search before_filter :set_started_at_session before_filter :api_check before_filter :set_safe_mode # before_filter :secure_cookies_check layout "default" force_ssl :if => :ssl_login? helper_method :show_moderation_notice? rescue_from Exception, :with => :rescue_exception rescue_from User::PrivilegeError, :with => :access_denied rescue_from SessionLoader::AuthenticationFailure, :with => :authentication_failed rescue_from Danbooru::Paginator::PaginationError, :with => :render_pagination_limit protected def show_moderation_notice? CurrentUser.can_approve_posts? && (cookies[:moderated].blank? || Time.at(cookies[:moderated].to_i) < 20.hours.ago) end def ssl_login? cookies[:ssl_login].present? end def enable_cors response.headers["Access-Control-Allow-Origin"] = "*" end def require_reportbooru_key unless params[:key] == Danbooru.config.reportbooru_key render(text: "forbidden", status: 403) return false end end def api_check if !CurrentUser.is_anonymous? && !request.get? && !request.head? if CurrentUser.user.token_bucket.nil? TokenBucket.create_default(CurrentUser.user) CurrentUser.user.reload end throttled = CurrentUser.user.token_bucket.throttled? headers["X-Api-Limit"] = CurrentUser.user.token_bucket.token_count.to_s if throttled respond_to do |format| format.json do render json: {success: false, reason: "too many requests"}.to_json, status: 429 end format.xml do render xml: {success: false, reason: "too many requests"}.to_xml(:root => "response"), status: 429 end format.html do render :template => "static/too_many_requests", :status => 429 end end return false end end return true end def rescue_exception(exception) @exception = exception if exception.is_a?(::ActiveRecord::StatementInvalid) && exception.to_s =~ /statement timeout/ if Rails.env.production? NewRelic::Agent.notice_error(exception, :uri => request.original_url, :referer => request.referer, :request_params => params, :custom_params => {:user_id => CurrentUser.user.id, :user_ip_addr => CurrentUser.ip_addr}) end @error_message = "The database timed out running your query." render :template => "static/error", :status => 500 elsif exception.is_a?(::ActiveRecord::RecordNotFound) @error_message = "That record was not found" render :template => "static/error", :status => 404 elsif exception.is_a?(NotImplementedError) flash[:notice] = "This feature isn't available: #{@exception.message}" respond_to do |fmt| fmt.html { redirect_to :back } fmt.json { render template: "static/error", status: 501 } fmt.xml { render template: "static/error", status: 501 } end else render :template => "static/error", :status => 500 end end def render_pagination_limit @error_message = "You can only view up to #{Danbooru.config.max_numbered_pages} pages. Please narrow your search terms." render :template => "static/error", :status => 410 end def authentication_failed respond_to do |fmt| fmt.html do render :text => "authentication failed", :status => 401 end fmt.xml do render :xml => {:sucess => false, :reason => "authentication failed"}.to_xml(:root => "response"), :status => 401 end fmt.json do render :json => {:success => false, :reason => "authentication failed"}.to_json, :status => 401 end end end def access_denied(exception = nil) previous_url = params[:url] || request.fullpath respond_to do |fmt| fmt.html do if CurrentUser.is_anonymous? if request.get? redirect_to new_session_path(:url => previous_url), :notice => "Access denied" else redirect_to new_session_path, :notice => "Access denied" end else render :template => "static/access_denied", :status => 403 end end fmt.xml do render :xml => {:success => false, :reason => "access denied"}.to_xml(:root => "response"), :status => 403 end fmt.json do render :json => {:success => false, :reason => "access denied"}.to_json, :status => 403 end fmt.js do render :nothing => true, :status => 403 end end end def set_current_user session_loader = SessionLoader.new(session, cookies, request, params) session_loader.load end def reset_current_user CurrentUser.user = nil CurrentUser.ip_addr = nil CurrentUser.mobile_mode = false end def set_started_at_session if session[:started_at].blank? session[:started_at] = Time.now end end User::Roles.each do |role| define_method("#{role}_only") do if !CurrentUser.user.is_banned_or_ip_banned? && CurrentUser.user.__send__("is_#{role}?") true else access_denied() false end end end def set_title @page_title = Danbooru.config.app_name + "/#{params[:controller]}" end def normalize_search if request.get? if params[:search].blank? params[:search] = {} end if params[:search].is_a?(Hash) changed = params[:search].reject! {|k,v| v.blank?} unless changed.nil? redirect_to url_for(params) end end end end def set_safe_mode CurrentUser.set_safe_mode(request) end def secure_cookies_check if request.ssl? Rails.application.config.session_store :cookie_store, :key => '_danbooru_session', :secure => true else Rails.application.config.session_store :cookie_store, :key => '_danbooru_session', :secure => false end end end
29.84466
224
0.657775
380e788f16e9ef399f18d1ff5853fff7e1af2199
1,819
=begin #SendinBlue API #SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :-------------: | ------------- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | | 406 | Error. Not Acceptable | OpenAPI spec version: 3.0.0 Contact: contact@sendinblue.com Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.18 =end require 'spec_helper' require 'json' require 'date' # Unit tests for SibApiV3Sdk::CreateUpdateFolder # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'CreateUpdateFolder' do before do # run before each test @instance = SibApiV3Sdk::CreateUpdateFolder.new end after do # run after each test end describe 'test an instance of CreateUpdateFolder' do it 'should create an instance of CreateUpdateFolder' do expect(@instance).to be_instance_of(SibApiV3Sdk::CreateUpdateFolder) end end describe 'test attribute "name"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
43.309524
839
0.698186
5d940c27dc1ced52f426ae22f35908cf1ac595f9
504
# frozen_string_literal: true require "rails_helper" RSpec.describe ExampleService, type: :service do describe "#execute" do it "returns a ServiceResult" do service = ExampleService.new("Hello, world!") result = service.execute expect(result).to be_a(ServiceResult) end it "transforms the message to uppercase" do service = ExampleService.new("Hello, world!") result = service.execute expect(result.payload).to eq("HELLO, WORLD!") end end end
22.909091
51
0.684524
e24ae91228c4de73e98e1eb270cb1004a0db282c
427
class FormFieldBuilder::LabelOnly < FormFieldBuilder::Decorated def form_field name_for_key, content, css_class, options={ } defaults = { required: false, id: nil } options = defaults.merge(options) label_node = build_label_node name_for_key, options "<#{tag} class='#{css_class}'>#{label_node}</#{tag}>".html_safe end def label name, options={ } build_form_field(name, options) { |*| "" } end end
32.846154
67
0.690867
ed59bb98cfc3f66cb050f7a04b7938600bd976ad
146
require_relative './collection' require_relative './digestable_notification' module Trubl class DigestableNotifications < Collection end end
18.25
44
0.821918
286b3b999f0f2dfba071a97df79f77385a58b04f
1,203
class Goreleaser < Formula desc "Deliver Go binaries as fast and easily as possible" homepage "https://goreleaser.com/" url "https://github.com/goreleaser/goreleaser/archive/v0.93.1.tar.gz" sha256 "cdb339ced74dc25513e6533e5ec385f41d7b542c57a86ce9d2cc7e1b5c51e8f9" bottle do cellar :any_skip_relocation sha256 "0b4aa520381ae8d9fd428ab1c57040515c17dd8a13535f8f9d7b76bb948b1564" => :mojave sha256 "b79ca013bd74d660a2f8325282dfc58f18884fe2d9f3b538d2786918c42cf368" => :high_sierra sha256 "0fc46598f1166fcd8492552fc1435051bb473e3760ce8c1efa830caa286c549d" => :sierra end depends_on "go" => :build def install ENV["GOPATH"] = HOMEBREW_CACHE/"go_cache" (buildpath/"src/github.com/goreleaser/goreleaser").install buildpath.children cd "src/github.com/goreleaser/goreleaser" do system "go", "build", "-ldflags", "-X main.version=#{version}", "-o", bin/"goreleaser" prefix.install_metafiles end end test do assert_match version.to_s, shell_output("#{bin}/goreleaser -v 2>&1") assert_match "config created", shell_output("#{bin}/goreleaser init 2>&1") assert_predicate testpath/".goreleaser.yml", :exist? end end
37.59375
93
0.738986
f76776437189cb658a9f659494556e6d8b1c05e6
32
class Warehouse < Account end
10.666667
26
0.75
4a267d9f31ca21752b2e5618afb11db52dfc820a
1,258
require 'segment/analytics' module Cartodb # Development info: https://segment.com/docs/libraries/ruby/quickstart class SegmentTracker def initialize @api_key = Cartodb.config[:segment]['api_key'] @analytics = Segment::Analytics.new(write_key: @api_key) end def enabled? !@api_key.blank? end def track_event(user_id, event, properties) return unless enabled? return if user_id.blank? begin @analytics.track( user_id: user_id, event: event, properties: properties ) rescue => e Rollbar.report_message('EventTracker: segment event tracking error', 'error', { user_id: user_id, event: event, properties: properties, error_message: e.inspect }) end end def flush begin @analytics.flush rescue => e Rollbar.report_message('EventTracker: segment flushing error', 'error', { error_message: e.inspect }) end end end end
29.255814
115
0.504769
6a252269946a5c90e97644a447e1c2880e186fe5
179
class AddTimestampsToChanges < ActiveRecord::Migration[5.0] def change add_column :changes, :created_at, :datetime add_column :changes, :updated_at, :datetime end end
25.571429
59
0.75419
3345845a1710ffa2402108351776b99d5781f648
3,247
module Fastlane module Actions class PodPushAction < Action def self.run(params) if params[:repo] repo = params[:repo] command = "pod repo push #{repo}" else command = 'pod trunk push' end if params[:path] command << " '#{params[:path]}'" end if params[:sources] sources = params[:sources].join(",") command << " --sources='#{sources}'" end if params[:allow_warnings] command << " --allow-warnings" end if params[:use_libraries] command << " --use-libraries" end result = Actions.sh(command.to_s) UI.success("Successfully pushed Podspec ⬆️ ") return result end ##################################################### # @!group Documentation ##################################################### def self.description "Push a Podspec to Trunk or a private repository" end def self.details "" end def self.available_options [ FastlaneCore::ConfigItem.new(key: :path, description: "The Podspec you want to push", optional: true, verify_block: proc do |value| UI.user_error!("Couldn't find file at path '#{value}'") unless File.exist?(value) UI.user_error!("File must be a `.podspec` or `.podspec.json`") unless value.end_with?(".podspec", ".podspec.json") end), FastlaneCore::ConfigItem.new(key: :repo, description: "The repo you want to push. Pushes to Trunk by default", optional: true), FastlaneCore::ConfigItem.new(key: :allow_warnings, description: "Allow warnings during pod push", optional: true, is_string: false), FastlaneCore::ConfigItem.new(key: :use_libraries, description: "Allow lint to use static libraries to install the spec", optional: true, is_string: false), FastlaneCore::ConfigItem.new(key: :sources, description: "The sources of repos you want the pod spec to lint with, separated by commas", optional: true, is_string: false, verify_block: proc do |value| UI.user_error!("Sources must be an array.") unless value.kind_of?(Array) end) ] end def self.output end def self.return_value nil end def self.authors ["squarefrog"] end def self.is_supported?(platform) [:ios, :mac].include? platform end end end end
34.913978
155
0.440407
79c6bfe3fc7e8791e7be555c6d6cdc4c72c49100
649
require 'spec_helper_system' describe "installation tasks" do let(:test_path) do proj_root + 'spec' + 'fixtures' + 'mymodule' end it "check puppet_install works" do puppet_install() end it 'check puppet_master_install works' do puppet_master_install() puppet_module_install(:source => test_path, :module_name => 'mymodule') puppet_agent do |r| r.stderr.should == '' r.exit_code.should == 0 end end it 'try puppet_agent with debug enabled' do puppet_agent(:debug => true) do |r| r.stderr.should == '' r.stdout.should =~ /Debug:/ r.exit_code.should == 0 end end end
20.935484
75
0.64869
4aaf1b544dc54ed0e9fc6ea980760610c9194f12
187
module GoogleSignIn::UrlHelper def callback_url GoogleSignIn::Engine.routes.url_helpers.callback_url( host: request.host_with_port, protocol: request.protocol ) end end
23.375
62
0.764706
037300db7c40c963f8a2990e05d20497511e3379
184
class UserSerializer def initialize(user_object) @user = user_object end def to_serialized_json @user.to_json(:except => [:password_digest, :created_at, :updated_at]) end end
18.4
72
0.76087
f77475004f8f32fd75ef3cb815e1e1fff3c7d3b6
123
class Farm < ApplicationRecord belongs_to :owner has_one :housing has_one :food has_one :bird has_one :breed end
15.375
30
0.747967
61278e5e6c531524e611f082c8e595617477b5a1
630
require 'router' module Shig class Web module Dispatcher attr_accessor :router attr_accessor :base_module_path def _router self.router ||= Router.new end def connect(path, dest) self._router.add(path, dest) end def base(module_path) self.base_module_path = module_path end def dispatch(c) path = c.req.path_info dest = self._router.match(path) if dest klass = Module.const_get("#{self.base_module_path}::#{dest}") klass.call(c) else nil end end end end end
17.5
71
0.566667
116da6e971b1681f116d9c3553f4895fcdc62b8f
1,543
# encoding: UTF-8 class Cabocha < Formula desc "Yet Another Japanese Dependency Structure Analyzer" homepage "https://taku910.github.io/cabocha/" url "https://googledrive.com/host/0B4y35FiV1wh7cGRCUUJHVTNJRnM/cabocha-0.69.tar.bz2" sha1 "9196098628c5d1f0b83b371a03352b6652c04001" bottle do sha1 "c6d6a98dedfe7466c454101174b3d5cbc2752f9b" => :yosemite sha1 "de55a785d8dcce5696a36f69b67168c913405259" => :mavericks sha1 "40106c50d68d5bd03941946378679ff490ae679a" => :mountain_lion end depends_on "crf++" depends_on "mecab" # To see which dictionaries are available, run: # ls `mecab-config --libs-only-L`/mecab/dic/ depends_on "mecab-ipadic" => :recommended depends_on "mecab-jumandic" => :optional depends_on "mecab-unidic" => :optional option "charset=", "choose default charset: EUC-JP, CP932, UTF8" option "posset=", "choose default posset: IPA, JUMAN, UNIDIC" def install ENV["LIBS"] = "-liconv" inreplace "Makefile.in" do |s| s.change_make_var! "CFLAGS", ENV.cflags s.change_make_var! "CXXFLAGS", ENV.cflags end charset = ARGV.value("charset") || "UTF8" posset = ARGV.value("posset") || "IPA" args = %W[ --disable-dependency-tracking --prefix=#{prefix} --with-charset=#{charset} --with-posset=#{posset} ] system "./configure", *args system "make", "install" end test do result = `echo "CaboCha はフリーソフトウェアです。" | cabocha | md5`.chomp assert_equal "a5b8293e6ebcb3246c54ecd66d6e18ee", result end end
29.113208
86
0.690214
03e36fd35524ab596b9778cfd84c6434e40b6c6d
1,779
require 'spec_helper' require 'nokogiri' module Gitlab describe Asciidoc do let(:input) { '<b>ascii</b>' } let(:context) { {} } let(:html) { 'H<sub>2</sub>O' } context "without project" do it "should convert the input using Asciidoctor and default options" do expected_asciidoc_opts = { safe: :secure, backend: :html5, attributes: described_class::DEFAULT_ADOC_ATTRS } expect(Asciidoctor).to receive(:convert) .with(input, expected_asciidoc_opts).and_return(html) expect( render(input, context) ).to eql html end context "with asciidoc_opts" do let(:asciidoc_opts) { { safe: :safe, attributes: ['foo'] } } it "should merge the options with default ones" do expected_asciidoc_opts = { safe: :safe, backend: :html5, attributes: described_class::DEFAULT_ADOC_ATTRS + ['foo'] } expect(Asciidoctor).to receive(:convert) .with(input, expected_asciidoc_opts).and_return(html) render(input, context, asciidoc_opts) end end end context "with project in context" do let(:context) { { project: create(:project) } } it "should filter converted input via HTML pipeline and return result" do filtered_html = '<b>ASCII</b>' allow(Asciidoctor).to receive(:convert).and_return(html) expect_any_instance_of(HTML::Pipeline).to receive(:call) .with(html, context) .and_return(output: Nokogiri::HTML.fragment(filtered_html)) expect( render('foo', context) ).to eql filtered_html end end def render(*args) described_class.render(*args) end end end
26.954545
79
0.609331
e87e3066802ea2c6677aac0e6457f21cc56bc9bf
4,350
# frozen_string_literal: true module EE # CI::JobArtifact EE mixin # # This module is intended to encapsulate EE-specific model logic # and be prepended in the `Ci::JobArtifact` model module Ci::JobArtifact include ::Gitlab::Utils::StrongMemoize extend ActiveSupport::Concern SECURITY_REPORT_FILE_TYPES = %w[sast secret_detection dependency_scanning container_scanning cluster_image_scanning dast coverage_fuzzing api_fuzzing].freeze prepended do # After destroy callbacks are often skipped because of FastDestroyAll. # All destroy callbacks should be implemented in `Ci::JobArtifacts::DestroyBatchService` # See https://gitlab.com/gitlab-org/gitlab/-/issues/297472 after_destroy :log_geo_deleted_event LICENSE_SCANNING_REPORT_FILE_TYPES = %w[license_scanning].freeze DEPENDENCY_LIST_REPORT_FILE_TYPES = %w[dependency_scanning].freeze METRICS_REPORT_FILE_TYPES = %w[metrics].freeze CONTAINER_SCANNING_REPORT_TYPES = %w[container_scanning].freeze CLUSTER_IMAGE_SCANNING_REPORT_TYPES = %w[cluster_image_scanning].freeze DAST_REPORT_TYPES = %w[dast].freeze REQUIREMENTS_REPORT_FILE_TYPES = %w[requirements].freeze COVERAGE_FUZZING_REPORT_TYPES = %w[coverage_fuzzing].freeze API_FUZZING_REPORT_TYPES = %w[api_fuzzing].freeze BROWSER_PERFORMANCE_REPORT_FILE_TYPES = %w[browser_performance performance].freeze scope :security_reports, -> (file_types: SECURITY_REPORT_FILE_TYPES) do requested_file_types = *file_types with_file_types(requested_file_types & SECURITY_REPORT_FILE_TYPES) end scope :license_scanning_reports, -> do with_file_types(LICENSE_SCANNING_REPORT_FILE_TYPES) end scope :dependency_list_reports, -> do with_file_types(DEPENDENCY_LIST_REPORT_FILE_TYPES) end scope :container_scanning_reports, -> do with_file_types(CONTAINER_SCANNING_REPORT_TYPES) end scope :cluster_image_scanning_reports, -> do with_file_types(CLUSTER_IMAGE_SCANNING_REPORT_TYPES) end scope :dast_reports, -> do with_file_types(DAST_REPORT_TYPES) end scope :metrics_reports, -> do with_file_types(METRICS_REPORT_FILE_TYPES) end scope :coverage_fuzzing_reports, -> do with_file_types(COVERAGE_FUZZING_REPORT_TYPES) end scope :api_fuzzing_reports, -> do with_file_types(API_FUZZING_REPORT_TYPES) end delegate :validate_schema?, to: :job end class_methods do extend ::Gitlab::Utils::Override override :associated_file_types_for def associated_file_types_for(file_type) return LICENSE_SCANNING_REPORT_FILE_TYPES if LICENSE_SCANNING_REPORT_FILE_TYPES.include?(file_type) return BROWSER_PERFORMANCE_REPORT_FILE_TYPES if BROWSER_PERFORMANCE_REPORT_FILE_TYPES.include?(file_type) super end end def log_geo_deleted_event ::Geo::JobArtifactDeletedEventStore.new(self).create! end # Ideally we would have a method to return an instance of # parsed report regardless of the `file_type` but this will # require more effort so we can have this security reports # specific method here for now. def security_report(validate: false) strong_memoize(:security_report) do next unless file_type.in?(SECURITY_REPORT_FILE_TYPES) signatures_enabled = project.licensed_feature_available?(:vulnerability_finding_signatures) report = ::Gitlab::Ci::Reports::Security::Report.new(file_type, job.pipeline, nil).tap do |report| each_blob do |blob| ::Gitlab::Ci::Parsers.fabricate!(file_type, blob, report, signatures_enabled, validate: (validate && validate_schema?)).parse! end rescue StandardError report.add_error('ParsingError') end # This will remove the duplicated findings within the artifact itself ::Security::MergeReportsService.new(report).execute end end # This method is necessary to remove the reference to the # security report object which allows GC to free the memory # slots in vm_heap occupied for the report object and it's # dependents. def clear_security_report clear_memoization(:security_report) end end end
36.25
161
0.731724
ff5e1d3bacfa51ab3830078720b6ef8ce4aa1685
1,096
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/google_ads/v0/enums/ad_customizer_placeholder_field.proto require 'google/protobuf' Google::Protobuf::DescriptorPool.generated_pool.build do add_message "google.ads.googleads.v0.enums.AdCustomizerPlaceholderFieldEnum" do end add_enum "google.ads.googleads.v0.enums.AdCustomizerPlaceholderFieldEnum.AdCustomizerPlaceholderField" do value :UNSPECIFIED, 0 value :UNKNOWN, 1 value :INTEGER, 2 value :PRICE, 3 value :DATE, 4 value :STRING, 5 end end module Google module Ads module GoogleAds module V0 module Enums AdCustomizerPlaceholderFieldEnum = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v0.enums.AdCustomizerPlaceholderFieldEnum").msgclass AdCustomizerPlaceholderFieldEnum::AdCustomizerPlaceholderField = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v0.enums.AdCustomizerPlaceholderFieldEnum.AdCustomizerPlaceholderField").enummodule end end end end end
35.354839
235
0.77646
bff442b7134394a183a719baf2e678a5a910b019
5,398
# # Be sure to run `pod spec lint PFPageControl.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see https://guides.cocoapods.org/syntax/podspec.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |spec| # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # These will help people to find your library, and whilst it # can feel like a chore to fill in it's definitely to your advantage. The # summary should be tweet-length, and the description more in depth. # spec.name = "PFPageControl" spec.version = "1.1.0" spec.summary = "iOS 14 inspired UIPageControl with extra features" # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! spec.description = <<-DESC This is a page control inspired by the iOS 14 UIPageControl that you can use in your < iOS 14 projects. It comes with some extra customizability options. DESC spec.homepage = "https://github.com/profico/PFPageControl" # spec.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif" # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Licensing your code is important. See https://choosealicense.com for more info. # CocoaPods will detect a license file if there is a named LICENSE* # Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'. # # spec.license = "MIT (example)" spec.license = { :type => "MIT", :file => "LICENSE" } # ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Specify the authors of the library, with email addresses. Email addresses # of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also # accepts just a name if you'd rather not provide an email address. # # Specify a social_media_url where others can refer to, for example a twitter # profile URL. # spec.author = { "Ivan Ferenčak" => "iferencak@profico.hr" } # Or just: spec.author = "Ivan Ferenčak" # spec.authors = { "Ivan Ferenčak" => "iferencak@profico.hr" } spec.social_media_url = "https://twitter.com/ferencakIvan" # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # If this Pod runs only on iOS or OS X, then specify the platform and # the deployment target. You can optionally include the target after the platform. # # spec.platform = :ios spec.platform = :ios, "12.0" spec.swift_versions = "5" # When using multiple platforms # spec.ios.deployment_target = "5.0" # spec.osx.deployment_target = "10.7" # spec.watchos.deployment_target = "2.0" # spec.tvos.deployment_target = "9.0" # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Specify the location from where the source should be retrieved. # Supports git, hg, bzr, svn and HTTP. # spec.source = { :git => "https://github.com/profico/PFPageControl.git", :tag => "#{spec.version}" } # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # CocoaPods is smart about how it includes source code. For source files # giving a folder will include any swift, h, m, mm, c & cpp files. # For header files it will include any header in the folder. # Not including the public_header_files will make all headers public. # spec.source_files = "PFPageControl/**/*.{h,m,swift}" # spec.exclude_files = "Classes/Exclude" # spec.public_header_files = "Classes/**/*.h" # ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # A list of resources included with the Pod. These are copied into the # target bundle with a build phase script. Anything else will be cleaned. # You can preserve files from being cleaned, please don't preserve # non-essential files like tests, examples and documentation. # # spec.resource = "icon.png" # spec.resources = "Resources/*.png" # spec.preserve_paths = "FilesToSave", "MoreFilesToSave" # ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Link your library with frameworks, or libraries. Libraries do not include # the lib prefix of their name. # # spec.framework = "SomeFramework" # spec.frameworks = "SomeFramework", "AnotherFramework" # spec.library = "iconv" # spec.libraries = "iconv", "xml2" # ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # If your library depends on compiler flags you can set them in the xcconfig hash # where they will only apply to your library. If you depend on other Podspecs # you can include multiple dependencies to ensure it works. # spec.requires_arc = true # spec.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" } # spec.dependency "JSONKit", "~> 1.4" end
38.557143
155
0.608559
38af2787c133cfebdec58ed2c2496208fe2227ea
464
class AccountActivationsController < ApplicationController def edit user = User.find_by(email: params[:email]) if user && !user.activated? && user.authenticated?(:activation, params[:id]) user.activate log_in user flash[:success] = "Account activated!" redirect_to user else flash[:danger] = "Invalid activation link" redirect_to root_url end end end
30.933333
84
0.592672
ab6028d984b85ed541f175e593fedb4ad2edebfb
1,707
# frozen_string_literal: true module Operations # {Liability} is a balance sheet operation class Liability < Operation belongs_to :member validates :member_id, presence: { if: ->(liability) { liability.account.scope == 'member' } } validates :member_id, absence: { if: ->(liability) { liability.account.scope != 'member' } } # Notify third party trading engine about member balance update. after_commit on: :create do AMQPQueue.enqueue(:events_processor, subject: :operation, payload: as_json_for_events_processor) end def as_json_for_events_processor { code: code, currency: currency_id, member_id: member_id, reference_id: reference_id, reference_type: reference_type&.downcase, debit: debit, credit: credit } end end end # == Schema Information # Schema version: 20190110164859 # # Table name: liabilities # # id :integer not null, primary key # code :integer not null # currency_id :string(255) not null # member_id :integer # reference_id :integer # reference_type :string(255) # debit :decimal(32, 16) default(0.0), not null # credit :decimal(32, 16) default(0.0), not null # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_liabilities_on_currency_id (currency_id) # index_liabilities_on_member_id (member_id) # index_liabilities_on_reference_type_and_reference_id (reference_type,reference_id) #
29.947368
86
0.611013
fffd3b4ba634bdf6661b0b0b9935a62d321031d0
1,121
=begin #ORY Keto #A cloud native access control server providing best-practice patterns (RBAC, ABAC, ACL, AWS IAM Policies, Kubernetes Roles, ...) via REST APIs. The version of the OpenAPI document: v0.0.0-alpha.1 Contact: hi@ory.sh Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.2.2 =end require 'spec_helper' require 'json' require 'date' # Unit tests for OryHydraClient::SwaggerHealthStatus # Automatically generated by openapi-generator (https://openapi-generator.tech) # Please update as you see appropriate describe 'SwaggerHealthStatus' do before do # run before each test @instance = OryHydraClient::SwaggerHealthStatus.new end after do # run after each test end describe 'test an instance of SwaggerHealthStatus' do it 'should create an instance of SwaggerHealthStatus' do expect(@instance).to be_instance_of(OryHydraClient::SwaggerHealthStatus) end end describe 'test attribute "status"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
26.690476
144
0.749331
11484423349afca0567b7ef4ff225e73de5364f6
641
cask 'jaxx' do version '1.3.9' sha256 '0e1756d95c68e7d44e4faeba916ba27608584692dd2f67f89aa19d73c5109e05' # github.com/Jaxx-io/Jaxx was verified as official when first introduced to the cask url "https://github.com/Jaxx-io/Jaxx/releases/download/v#{version}/Jaxx-#{version}.dmg" appcast 'https://github.com/Jaxx-io/Jaxx/releases.atom', checkpoint: '2670f07ef7e62cf6752333fbcef16a6be192ff340099eb64a071582fe86470b4' name 'Jaxx Blockchain Wallet' homepage 'https://jaxx.io/' app 'Jaxx.app' zap trash: [ '~/Library/Application Support/jaxx', '~/Library/Logs/jaxx', ] end
33.736842
89
0.698908
b9305fc55a1cfae6bf9fefeba477a1b9dd6c8602
121
class RemoveResumeFromPeople < ActiveRecord::Migration def change remove_column :people, :resume, :string end end
24.2
54
0.77686
e24c8a7cef89371c7a37177062abcaee38bfa0c0
3,131
# frozen_string_literal: true module RuboCop module Cop module Style # This cop enforces consistency when using exponential notation # for numbers in the code (eg 1.2e4). Different styles are supported: # - `scientific` which enforces a mantissa between 1 (inclusive) # and 10 (exclusive). # - `engineering` which enforces the exponent to be a multiple of 3 # and the mantissa to be between 0.1 (inclusive) # and 10 (exclusive). # - `integral` which enforces the mantissa to always be a whole number # without trailing zeroes. # # @example EnforcedStyle: scientific (default) # # Enforces a mantissa between 1 (inclusive) and 10 (exclusive). # # # bad # 10e6 # 0.3e4 # 11.7e5 # 3.14e0 # # # good # 1e7 # 3e3 # 1.17e6 # 3.14 # # @example EnforcedStyle: engineering # # Enforces using multiple of 3 exponents, # # mantissa should be between 0.1 (inclusive) and 1000 (exclusive) # # # bad # 3.2e7 # 0.1e5 # 12e5 # 1232e6 # # # good # 32e6 # 10e3 # 1.2e6 # 1.232e9 # # @example EnforcedStyle: integral # # Enforces the mantissa to have no decimal part and no # # trailing zeroes. # # # bad # 3.2e7 # 0.1e5 # 120e4 # # # good # 32e6 # 1e4 # 12e5 # class ExponentialNotation < Cop include ConfigurableEnforcedStyle def on_float(node) add_offense(node) if offense?(node) end private def scientific?(node) mantissa, = node.source.split('e') mantissa =~ /^-?[1-9](\.\d*[0-9])?$/ end def engineering?(node) mantissa, exponent = node.source.split('e') return false unless /^-?\d+$/.match?(exponent) return false unless (exponent.to_i % 3).zero? return false if /^-?\d{4}/.match?(mantissa) return false if /^-?0\d/.match?(mantissa) return false if /^-?0.0/.match?(mantissa) true end def integral(node) mantissa, = node.source.split('e') mantissa =~ /^-?[1-9](\d*[1-9])?$/ end def offense?(node) return false unless node.source['e'] case style when :scientific !scientific?(node) when :engineering !engineering?(node) when :integral !integral(node) else false end end def message(_node) case style when :scientific 'Use a mantissa in [1, 10[.' when :engineering 'Use an exponent divisible by 3 and a mantissa in [0.1, 1000[.' when :integral 'Use an integer as mantissa, without trailing zero.' end end end end end end
26.091667
76
0.499521
f7b24433c00493c0f83eda443ad85180524a28c2
5,097
require 'simplecov' # run coverage when on CI if ENV['CI'] SimpleCov.start 'rails' do add_filter '/spec/' end end require 'rubygems' # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require File.expand_path('../config/environment', __dir__) require 'rspec/rails' require 'capybara/rspec' require 'capybara/poltergeist' require "pundit/rspec" require "shoulda/matchers" # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec", "support", "**", "*.rb")].each { |f| require f } # This is required by CI because sometimes it runs the model specs before # other rails specs (which would have initialized/created the following directories) require 'fileutils' FileUtils.mkdir_p Rails.root.join("tmp", "cache") ActiveRecord::Migration.maintain_test_schema! Capybara.javascript_driver = :poltergeist RSpec.configure do |config| config.infer_spec_type_from_file_location! config.include(Shoulda::Matchers::ActiveModel, type: :model) config.include(Shoulda::Matchers::ActiveRecord, type: :model) config.include ActiveSupport::Testing::TimeHelpers config.example_status_persistence_file_path = "examples.txt" config.render_views # ## Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr if ENV["CI"] # config.filter_run_excluding :pdf_generation => true end config.before do # We do this instead of setting cache_store = :null_store # because sometimes we DO want caching enabled (see below) Rails.cache.clear end # Apartment Related config.before(:suite) do # Clean all tables to start DatabaseCleaner.clean_with :truncation # Use transactions for tests DatabaseCleaner.strategy = :transaction # Truncating doesn't drop schemas, ensure we're clean here, app *may not* exist begin Apartment::Tenant.drop('testing') rescue StandardError nil end # Create the default tenant for our tests tenant = Tenant.create!(description: 'Test Tenant', subdomain: 'testing', admin_upgrade_code: "TEST_UPGRADE_CODE") Apartment::Tenant.create(tenant.subdomain) end config.before do Apartment::Tenant.switch! 'testing' end config.after do Apartment::Tenant.reset end config.around(:each, :caching) do |example| caching = ActionController::Base.perform_caching ActionController::Base.perform_caching = example.metadata[:caching] example.run Rails.cache.clear ActionController::Base.perform_caching = caching end config.before do RequestStore.clear! end config.before(:each, type: :view) do assign(:config, EventConfiguration.new) end # this is necessary so that spec path builders without locales don't # incorrectly specify positional arguments into the 'locale' argument config.before(:each, type: :feature) do default_url_options[:locale] = I18n.default_locale end config.before :each, type: :view do controller.default_url_options[:locale] = I18n.default_locale end # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" config.after type: :feature do Warden.test_reset! end # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # If true, the base class of anonymous controllers will be inferred # automatically. This will be the default behavior in future versions of # rspec-rails. config.infer_base_class_for_anonymous_controllers = false # Default to using inline, meaning all jobs will run as they're # called. Since we primarily are using this for email, this ensures # the emails go immediately to ActionMailer::Base.deliveries require 'sidekiq/testing' config.before do Sidekiq::Worker.clear_all end # In order to cause .deliver_later to actually .deliver_now config.before do ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true end config.around do |example| if example.metadata[:sidekiq] == :fake Sidekiq::Testing.fake!(&example) else Sidekiq::Testing.inline!(&example) end end # config.include Devise::TestHelpers, type: :controller config.include Warden::Test::Helpers, type: :feature # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = "random" end # To enable using `allow` in FactoryBot after(:stub) calls, # https://github.com/thoughtbot/factory_bot/issues/703 FactoryBot::SyntaxRunner.class_eval do include RSpec::Mocks::ExampleMethods end
31.079268
118
0.739455
1c169e0bb6b3d23dfab193cdbbaac49206109325
133
class AddCurrentPlanToAccount < ActiveRecord::Migration[6.1] def change add_column :accounts, :current_plan, :string end end
22.166667
60
0.766917
61cc1fc3827796b81be94e3ddf36b354968fe3ef
1,414
class I386ElfGdb < Formula desc "GNU debugger for i386-elf cross development" homepage "https://www.gnu.org/software/gdb/" url "https://ftp.gnu.org/gnu/gdb/gdb-9.2.tar.xz" mirror "https://ftpmirror.gnu.org/gdb/gdb-9.2.tar.xz" sha256 "360cd7ae79b776988e89d8f9a01c985d0b1fa21c767a4295e5f88cb49175c555" license "GPL-2.0" head "https://sourceware.org/git/binutils-gdb.git" livecheck do url :stable end bottle do sha256 "8d6ce6e01f67563076e657967c64aa266b7b6d93fd9ffe7cc0f91cb38d4f700f" => :catalina sha256 "2a8ecb8ae77565fabfb6286fbc60f4aaf843bc74c72b3ff2e1d5087e4dcbd92e" => :mojave sha256 "8dad06d6eea6ec145763819d982916d590edd45b40e4c91e328bba76f0aac0bf" => :high_sierra end depends_on "python@3.8" depends_on "xz" # required for lzma support conflicts_with "gdb", because: "both install include/gdb, share/gdb and share/info" def install args = %W[ --target=i386-elf --prefix=#{prefix} --disable-debug --disable-dependency-tracking --with-lzma --with-python=#{Formula["python@3.8"].opt_bin}/python3 --disable-binutils ] mkdir "build" do system "../configure", *args system "make" # Don't install bfd or opcodes, as they are provided by binutils system "make", "install-gdb" end end test do system "#{bin}/i386-elf-gdb", "#{bin}/i386-elf-gdb", "-configuration" end end
28.857143
93
0.698727
114eabacbb229bfe5742450a51d456ee819fbf4a
371
cask 'retrobatch' do version '1.1' sha256 '22da92a29b4ba4e7cecc3e381b1bf3bc1f753b594ea62bcc5dc507892977d552' url 'https://flyingmeat.com/download/Retrobatch.zip' appcast "https://www.flyingmeat.com/download/retrobatch#{version.major}update.xml" name 'Retrobatch' homepage 'https://flyingmeat.com/retrobatch/' auto_updates true app 'Retrobatch.app' end
26.5
84
0.778976
1a041a7a697fe680a0a21ee215f278a6f3f5231d
4,546
cask "microsoft-office" do version "16.44.20121301" sha256 "da1848641fcb8496715d1153ac5398f0cd7303324bb72e6dc568f373f2e4bb34" url "https://officecdn-microsoft-com.akamaized.net/pr/C1297A47-86C4-4C1F-97FA-950631F94777/MacAutoupdate/Microsoft_Office_#{version}_Installer.pkg", verified: "officecdn-microsoft-com.akamaized.net/pr/C1297A47-86C4-4C1F-97FA-950631F94777/MacAutoupdate/" name "Microsoft Office" homepage "https://products.office.com/mac/microsoft-office-for-mac/" auto_updates true conflicts_with cask: %w[ microsoft-word microsoft-excel microsoft-powerpoint microsoft-outlook onedrive ] depends_on cask: "microsoft-auto-update" depends_on macos: ">= :sierra" pkg "Microsoft_Office_#{version}_Installer.pkg", choices: [ { "choiceIdentifier" => "com.microsoft.autoupdate", # Office16_all_autoupdate.pkg "choiceAttribute" => "selected", "attributeSetting" => 0, }, ] uninstall pkgutil: [ "com.microsoft.package.DFonts", "com.microsoft.package.Frameworks", "com.microsoft.package.Microsoft_AutoUpdate.app", "com.microsoft.package.Microsoft_Excel.app", "com.microsoft.package.Microsoft_OneNote.app", "com.microsoft.package.Microsoft_Outlook.app", "com.microsoft.package.Microsoft_PowerPoint.app", "com.microsoft.package.Microsoft_Word.app", "com.microsoft.package.Proofing_Tools", "com.microsoft.pkg.licensing", "com.microsoft.OneDrive", ], # Frameworks, DFonts and ProofingTools remain in each applicaiton after pkg uninstall, delete them delete: [ "/Applications/Microsoft Excel.app", "/Applications/Microsoft OneNote.app", "/Applications/Microsoft Outlook.app", "/Applications/Microsoft PowerPoint.app", "/Applications/Microsoft Word.app", "/Applications/OneDrive.app", ], launchctl: [ "com.microsoft.office.licensing.helper", "com.microsoft.office.licensingV2.helper", "com.microsoft.OneDriveStandaloneUpdater", "com.microsoft.OneDriveStandaloneUpdaterDaemon", "com.microsoft.OneDriveUpdaterDaemon", ] zap trash: [ "~/Library/Application Scripts/com.microsoft.Excel", "~/Library/Application Scripts/com.microsoft.Office365ServiceV2", "~/Library/Application Scripts/com.microsoft.Outlook", "~/Library/Application Scripts/com.microsoft.Powerpoint", "~/Library/Application Scripts/com.microsoft.Word", "~/Library/Application Scripts/com.microsoft.errorreporting", "~/Library/Application Scripts/com.microsoft.onenote.mac", "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.microsoft.excel.sfl*", "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.microsoft.powerpoint.sfl*", "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.microsoft.word.sfl*", "~/Library/Application Support/CrashReporter/Microsoft Error Reporting_*.plist", "~/Library/Application Support/Microsoft Update Assistant", "~/Library/Caches/com.microsoft.OneDriveStandaloneUpdater", "~/Library/Caches/com.plausiblelabs.crashreporter.data/com.microsoft.OneDriveStandaloneUpdater", "~/Library/Containers/com.microsoft.Excel", "~/Library/Containers/com.microsoft.Office365ServiceV2", "~/Library/Containers/com.microsoft.Outlook", "~/Library/Containers/com.microsoft.Powerpoint", "~/Library/Containers/com.microsoft.com.microsoft.RMS-XPCService", "~/Library/Containers/com.microsoft.Word", "~/Library/Containers/com.microsoft.errorreporting", "~/Library/Containers/com.microsoft.netlib.shipassertprocess", "~/Library/Containers/com.microsoft.onenote.mac", "~/Library/Group Containers/UBF8T346G9.Office", "~/Library/Group Containers/UBF8T346G9.OfficeOneDriveSyncIntegration", "~/Library/Group Containers/UBF8T346G9.OfficeOsfWebHost", "~/Library/Group Containers/UBF8T346G9.ms", "~/Library/Preferences/com.microsoft.Excel.plist", "~/Library/Preferences/com.microsoft.Outlook.plist", "~/Library/Preferences/com.microsoft.Powerpoint.plist", "~/Library/Preferences/com.microsoft.Word.plist", "~/Library/Saved Application State/com.microsoft.office.setupassistant.savedState", ] end
47.852632
150
0.721073
6185fd266690e7f7157d78dd4e2b7e316f1e494e
454
require 'dldinternet/doctl/api/compute' module DLDInternet module DOctl module Compute module DropletAction module Rebuild class Command < DLDInternet::Thor::Command no_commands do require 'dldinternet/doctl/compute/droplet-action/rebuild/mixins/no_commands' include DLDInternet::DOctl::Compute::DropletAction::Rebuild::MixIns::NoCommands end end end end end end end
21.619048
91
0.676211
26b8673655de9584e80e347447d00f0d94ce5714
594
# encoding: utf-8 # frozen_string_literal: true module Mail class ContentDispositionElement # :nodoc: include Mail::Utilities def initialize( string ) content_disposition = Mail::Parsers::ContentDispositionParser.new.parse(cleaned(string)) @disposition_type = content_disposition.disposition_type @parameters = content_disposition.parameters end def disposition_type @disposition_type end def parameters @parameters end def cleaned(string) string =~ /(.+);\s*$/ ? $1 : string end end end
21.214286
94
0.659933
11599810f0ef883df065da663475b4e49cbde454
700
require 'httparty' require 'highline/import' # class Egi::Fedcloud::Cloudhound::Connector include HTTParty # def initialize(opts = {}, password = nil) Egi::Fedcloud::Cloudhound::Log.debug "[#{self.class}] Initializing with #{opts.inspect}" self.class.pem File.read(opts[:credentials]), password self.class.ssl_ca_path opts[:ca_path] self.class.debug_output $stderr if opts[:debug] end # def retrieve(url = '/') Egi::Fedcloud::Cloudhound::Log.debug "[#{self.class}] Retrieving #{url.inspect}" response = self.class.get url raise "Failed to get a response from '#{url}' [#{response.code}]" unless response.code.between?(200,299) response.body end end
26.923077
108
0.688571
03801fe178ec289598177fcb40c89e043cc0a80f
2,191
# frozen_string_literal: true class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception depends_on :authentication, :errors, :feature_flags before_action :authenticate_user! # authentication_dependency helper_method :current_user, :logged_in?, :true_user # authentication_dependency helper_method :student_identifier_enabled?, :team_management_enabled? # feature_flags_dependency # errors_dependency rescue_from StandardError, with: :send_to_statsd_and_reraise rescue_from GitHub::Error, GitHub::Forbidden, GitHub::NotFound, NotAuthorized, with: :flash_and_redirect_back_with_message rescue_from ActionController::RoutingError, ActiveRecord::RecordNotFound, with: :render_404 rescue_from ActionController::InvalidAuthenticityToken do pre_login_destination = session[:pre_login_destination] reset_session session[:pre_login_destination] = pre_login_destination if pre_login_destination.present? url = session[:pre_login_destination] || root_path flash[:alert] = "Cannot verify CSRF Token Authenticity" redirect_to url end def peek_enabled? logged_in? && current_user.staff? end def failbot_context { current_scopes: session[:current_scopes], impersonator: session[:impersonated_user_id], required_scopes: session[:required_scopes], user: session[:user_id], zone: Time.zone.now } end private def not_found raise ActionController::RoutingError, "Not Found" end def redirect_to_root redirect_to root_path end def render_404(exception) GitHubClassroom.statsd.increment("exception.not_found", tags: [exception.class.to_s]) case exception when ActionController::RoutingError render file: Rails.root.join("public", "404.html"), layout: false, status: :not_found when ActiveRecord::RecordNotFound render file: Rails.root.join("public", "invalid_link_error.html"), layout: false, status: :not_found end end end
31.753623
106
0.735737
3341df8d829ceb507aac652d40d05a312ace5676
13,448
module Vanity module Rails def self.load! Vanity.playground.load_path = ::Rails.root + Vanity.playground.load_path Vanity.playground.logger ||= ::Rails.logger # Do this at the very end of initialization, allowing you to change # connection adapter, turn collection on/off, etc. ::Rails.configuration.after_initialize do Vanity.playground.load! if Vanity.playground.connected? end end # The use_vanity method will setup the controller to allow testing and # tracking of the current user. module UseVanity # Defines the vanity_identity method and the set_identity_context filter. # # Call with the name of a method that returns an object whose identity # will be used as the Vanity identity if the user is not already # cookied. Confusing? Let's try by example: # # class ApplicationController < ActionController::Base # use_vanity :current_user # # def current_user # User.find(session[:user_id]) # end # end # # If that method (current_user in this example) returns nil, Vanity will # look for a vanity cookie. If there is none, it will create an identity # (using a cookie to remember it across requests). It also uses this # mechanism if you don't provide an identity object, by calling # use_vanity with no arguments. # # You can also use a block: # class ProjectController < ApplicationController # use_vanity { |controller| controller.params[:project_id] } # end def use_vanity(symbol = nil, &block) if block define_method(:vanity_identity) { block.call(self) } else define_method :vanity_identity do return @vanity_identity if @vanity_identity # With user sign in, it's possible to visit not-logged in, get # cookied and shown alternative A, then sign in and based on # user.id, get shown alternative B. # This implementation prefers an initial vanity cookie id over a # new user.id to avoid the flash of alternative B (FOAB). if request.get? && params[:_identity] @vanity_identity = params[:_identity] cookies["vanity_id"] = { :value=>@vanity_identity, :expires=>1.month.from_now } @vanity_identity elsif cookies["vanity_id"] @vanity_identity = cookies["vanity_id"] elsif symbol && object = send(symbol) @vanity_identity = object.id elsif response # everyday use @vanity_identity = cookies["vanity_id"] || SecureRandom.hex(16) cookie = { :value=>@vanity_identity, :expires=>1.month.from_now } # Useful if application and admin console are on separate domains. cookie[:domain] ||= ::Rails.application.config.session_options[:domain] cookies["vanity_id"] = cookie @vanity_identity else # during functional testing @vanity_identity = "test" end end end protected :vanity_identity around_filter :vanity_context_filter before_filter :vanity_reload_filter unless ::Rails.configuration.cache_classes before_filter :vanity_query_parameter_filter after_filter :vanity_track_filter end protected :use_vanity end module UseVanityMailer def use_vanity_mailer(symbol = nil) # Context is the instance of ActionMailer::Base Vanity.context = self if symbol && (@object = symbol) class << self define_method :vanity_identity do @vanity_identity = (String === @object ? @object : @object.id) end end else class << self define_method :vanity_identity do @vanity_identity = @vanity_identity || SecureRandom.hex(16) end end end end protected :use_vanity_mailer end # Vanity needs these filters. They are includes in ActionController and # automatically added when you use #use_vanity in your controller. module Filters # Around filter that sets Vanity.context to controller. def vanity_context_filter previous, Vanity.context = Vanity.context, self yield ensure Vanity.context = previous end # This filter allows user to choose alternative in experiment using query # parameter. # # Each alternative has a unique fingerprint (run vanity list command to # see them all). A request with the _vanity query parameter is # intercepted, the alternative is chosen, and the user redirected to the # same request URL sans _vanity parameter. This only works for GET # requests. # # For example, if the user requests the page # http://example.com/?_vanity=2907dac4de, the first alternative of the # :null_abc experiment is chosen and the user redirected to # http://example.com/. def vanity_query_parameter_filter if request.get? && params[:_vanity] hashes = Array(params.delete(:_vanity)) Vanity.playground.experiments.each do |id, experiment| if experiment.respond_to?(:alternatives) experiment.alternatives.each do |alt| if hash = hashes.delete(experiment.fingerprint(alt)) experiment.chooses alt.value break end end end break if hashes.empty? end redirect_to url_for(params) end end # Before filter to reload Vanity experiments/metrics. Enabled when # cache_classes is false (typically, testing environment). def vanity_reload_filter Vanity.playground.reload! end # Filter to track metrics. Pass _track param along to call track! on that # alternative. def vanity_track_filter if request.get? && params[:_track] track! params[:_track] end end protected :vanity_context_filter, :vanity_query_parameter_filter, :vanity_reload_filter end # Introduces ab_test helper (controllers and views). Similar to the generic # ab_test method, with the ability to capture content (applicable to views, # see examples). module Helpers # This method returns one of the alternative values in the named A/B test. # # @example A/B two alternatives for a page # def index # if ab_test(:new_page) # true/false test # render action: "new_page" # else # render action: "index" # end # end # @example Similar, alternative value is page name # def index # render action: ab_test(:new_page) # end # @example A/B test inside ERB template (condition) # <%= if ab_test(:banner) %>100% less complexity!<% end %> # @example A/B test inside ERB template (value) # <%= ab_test(:greeting) %> <%= current_user.name %> # @example A/B test inside ERB template (capture) # <% ab_test :features do |count| %> # <%= count %> features to choose from! # <% end %> def ab_test(name, &block) value = setup_experiment(name) if block content = capture(value, &block) if defined?(block_called_from_erb?) && block_called_from_erb?(block) concat(content) else content end else value end end # Generate url with the identity of the current user and the metric to track on click def vanity_track_url_for(identity, metric, options = {}) options = options.merge(:_identity => identity, :_track => metric) url_for(options) end # Generate url with the fingerprint for the current Vanity experiment def vanity_tracking_image(identity, metric, options = {}) options = options.merge(:controller => :vanity, :action => :image, :_identity => identity, :_track => metric) image_tag(url_for(options), :width => "1px", :height => "1px", :alt => "") end def vanity_js return if @_vanity_experiments.nil? || @_vanity_experiments.empty? javascript_tag do render :file => Vanity.template("_vanity"), :formats => [:js] end end def vanity_h(text) h(text) end def vanity_html_safe(text) if text.respond_to?(:html_safe) text.html_safe else text end end def vanity_simple_format(text, html_options={}) vanity_html_safe(simple_format(text, html_options)) end # Return a copy of the active experiments on a page # # @example Render some info about each active experiment in development mode # <% if Rails.env.development? %> # <% vanity_experiments.each do |name, alternative| %> # <span>Participating in <%= name %>, seeing <%= alternative %>:<%= alternative.value %> </span> # <% end %> # <% end %> # @example Push experiment values into javascript for use there # <% experiments = vanity_experiments %> # <% unless experiments.empty? %> # <script> # <% experiments.each do |name, alternative| %> # myAbTests.<%= name.to_s.camelize(:lower) %> = '<%= alternative.value %>'; # <% end %> # </script> # <% end %> def vanity_experiments @_vanity_experiments ||= {} experiments = {} @_vanity_experiments.each do |name, alternative| experiments[name] = alternative.clone end experiments end protected def setup_experiment(name) @_vanity_experiments ||= {} request = respond_to?(:request) ? self.request : nil @_vanity_experiments[name] ||= Vanity.playground.experiment(name.to_sym).choose(request) @_vanity_experiments[name].value end end # Step 1: Add a new resource in config/routes.rb: # map.vanity "/vanity/:action/:id", :controller=>:vanity # # Step 2: Create a new experiments controller: # class VanityController < ApplicationController # include Vanity::Rails::Dashboard # end # # Step 3: Open your browser to http://localhost:3000/vanity module Dashboard def index render :file=>Vanity.template("_report"),:content_type=>Mime::HTML, :locals=>{ :experiments=>Vanity.playground.experiments, :experiments_persisted=>Vanity.playground.experiments_persisted?, :metrics=>Vanity.playground.metrics } end def participant render :file=>Vanity.template("_participant"), :locals=>{:participant_id => params[:id], :participant_info => Vanity.playground.participant_info(params[:id])}, :content_type=>Mime::HTML end def complete exp = Vanity.playground.experiment(params[:e].to_sym) alt = exp.alternatives[params[:a].to_i] confirmed = params[:confirmed] # make the user confirm before completing an experiment if confirmed && confirmed.to_i==alt.id && exp.active? exp.complete!(alt.id) render :file=>Vanity.template("_experiment"), :locals=>{:experiment=>exp} else @to_confirm = alt.id render :file=>Vanity.template("_experiment"), :locals=>{:experiment=>exp} end end def chooses exp = Vanity.playground.experiment(params[:e].to_sym) exp.chooses(exp.alternatives[params[:a].to_i].value) render :file=>Vanity.template("_experiment"), :locals=>{:experiment=>exp} end # JS callback action used by vanity_js def add_participant if params[:e].nil? || params[:e].empty? render :status => 404, :nothing => true return end exp = Vanity.playground.experiment(params[:e].to_sym) exp.chooses(exp.alternatives[params[:a].to_i].value, request) render :status => 200, :nothing => true end end module TrackingImage def image # send image send_file(File.expand_path("../images/x.gif", File.dirname(__FILE__)), :type => 'image/gif', :stream => false, :disposition => 'inline') end end end end # Enhance ActionController with use_vanity, filters and helper methods. ActiveSupport.on_load(:action_controller) do # Include in controller, add view helper methods. ActionController::Base.class_eval do extend Vanity::Rails::UseVanity include Vanity::Rails::Filters helper Vanity::Rails::Helpers end end # Include in mailer, add view helper methods. ActiveSupport.on_load(:action_mailer) do include Vanity::Rails::UseVanityMailer include Vanity::Rails::Filters helper Vanity::Rails::Helpers end # Reconnect whenever we fork under Passenger. if defined?(PhusionPassenger) PhusionPassenger.on_event(:starting_worker_process) do |forked| if forked begin Vanity.playground.reconnect! if Vanity.playground.collecting? rescue Exception=>ex Rails.logger.error "Error reconnecting: #{ex.to_s}" end end end end
36.053619
193
0.62039
e91fb24597b7d713bd3aeb33a54e9216702b6f70
307
require 'api_hammer/rails/halt' require 'api_hammer/rails/check_required_params' require 'api_hammer/rails/unmunged_request_params' module ApiHammer module Rails def self.included(klass) (@on_included || []).each do |included_proc| included_proc.call(klass) end end end end
21.928571
50
0.729642
33bc732628681fddd13c11cf23930235fffef35f
367
# frozen_string_literal: true module Thredded # Defines a moderation_state enum # Requires an integer moderation_state column on the including class. module ModerationState extend ActiveSupport::Concern included do enum moderation_state: %i(pending_moderation approved blocked) validates :moderation_state, presence: true end end end
26.214286
71
0.768392
18dc8e9f3a00c30a9cdad40cfa161bf8396e010e
389
class CreateOfferingMentorQuestions < ActiveRecord::Migration def self.up create_table :offering_mentor_questions do |t| t.integer :offering_id t.text :question t.boolean :required t.boolean :must_be_number t.string :display_as t.integer :size t.timestamps end end def self.down drop_table :offering_mentor_questions end end
20.473684
61
0.699229
f7c43f750805750ad09f30fa5bdaeafc9d11fb42
649
require_relative './sas_data' class RubyOlm::SAS METHODS = %i[decimal emoji] def generate(method, info) method = method.to_sym raise ArgumentError, "Unknown SAS method: #{method}" unless METHODS.include? method send method, info end protected def decimal(info) bytes = generate_bytes(5, info) bits = bytes.unpack1('B39') grouped = bits.chars.each_slice(13).map &:join grouped.map {|s| s.to_i(2) + 1000} end def emoji(info) bytes = generate_bytes(6, info) bits = bytes.unpack1('B42') grouped = bits.chars.each_slice(6).map &:join grouped.map {|s| EMOJI_TABLE[s.to_i(2)]}.join end end
22.37931
87
0.66718
ab315bdfeaab0fdd0d6eb7beb13947a4f4ca0577
40
module Agentify VERSION = "0.1.0" end
10
19
0.675
6ab8a0d91e1f8e31d8152acad7edeef2622e1db3
122
require 'test_helper' class AssigneeTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
15.25
44
0.704918
abbb0b99644db34a98efd53b46fccc1b90e1ee3b
1,817
# frozen_string_literal: true class ApplicationController < ActionController::API class AuthError < StandardError; end before_action :authenticate, :authenticate! attr_reader :current_user rescue_from AuthError, with: :handle_access_denied rescue_from ActiveRecord::RecordInvalid, with: :handle_invalid_record rescue_from ActiveRecord::RecordNotUnique, with: :handle_not_unique_record rescue_from ActiveRecord::RecordNotFound, with: :handle_record_not_found rescue_from PG::ForeignKeyViolation, with: :handle_record_in_usage protected def handle_access_denied render json: { success: false, errors: ["AUTH_REQUIRED"] }, status: 403 end def handle_invalid_record(e) errors = e.record.errors.details.reduce([]) do |acc, (field, errors)| acc << [field.to_s.upcase, errors[0][:error].to_s.upcase].join("_") end render json: { success: false, errors: errors }, status: 400 end def handle_not_unique_record render json: { success: false, errors: ["NOT_UNIQUE"] }, status: 400 end def handle_record_not_found render json: { success: false, errors: ["NOT_FOUND"] }, status: 404 end def handle_record_in_usage render json: { success: false, errors: ["NOT_ALLOWED", "IN_USAGE"] }, status: 403 end # Check JWT and set user if exists def authenticate token = request.headers["Authorization"]&.split(" ")&.last # TODO: for production need to change to RSA or any another similar algo :-) decoded_token = JWT.decode(token, nil, false) @current_user = decoded_token[0]["sub"] rescue JWT::DecodeError Rails.logger.warn "Unable to decode JWT token" end # Check that request has authorized user def authenticate! # just check, that something exists in sub :-) raise AuthError.new if current_user.nil? end end
31.877193
85
0.729224
2634152bf42a68cd1e730fd34675811cde7b03d9
1,632
require 'spec_helper' describe Anvil::Cli do # before {FakeFS.deactivate!} describe '#run' do let(:dummy_task) { DummyTask } let(:argv) { %w[dummy arg1 arg2 --argument value] } context 'with a task name' do before do expect(dummy_task).to receive(:new) .with('arg1', 'arg2', argument: 'value').and_call_original expect(subject).to_not receive(:print_help) end it('runs the task in the first parameter') { subject.run argv } end describe '#build_task' do it 'builds the task and parses the arguments' do expect(subject.build_task(argv).options).to eq({ argument: 'value' }) end context 'if the task is not found' do let(:argv) { %w[ihopethiswillnotexistever arg2] } it 'prints task list and exits' do expect(subject).to receive(:task_not_found) .with('ihopethiswillnotexistever') expect do subject.build_task(argv) end.to raise_error(SystemExit) end end context 'if the arguments are not the correct' do let(:argv) { %w[foo:dummy arg1 arg2 arg3 arg4 arg5 arg6 arg7] } it 'prints task list and exits' do expect(subject).to receive(:bad_arguments).with('foo:dummy') expect do subject.build_task(argv) end.to raise_error(SystemExit) end end end context 'without a task name' do let(:argv) { [] } before { expect(subject).to receive(:print_help_body) } it('prints the help') { subject.run argv } end end end
29.672727
77
0.598652
f756a23bdd1ce9dacba18914b8c8fb636fff3495
189
RSpec.describe GemChallenge do it "has a version number" do expect(GemChallenge::VERSION).not_to be nil end it "does something useful" do expect(false).to eq(true) end end
18.9
47
0.714286
ab60e47adc8e7d0b539a286eb9a7a534b89fd182
333
# frozen_string_literal: true module Root module Factions module Mice # Bases for cats, they get 3 bases and this handles their operations class Base < Pieces::Building include Miceable attr_reader :suit def initialize(suit) @suit = suit end end end end end
17.526316
74
0.618619
edaf55fbda7260e7f3bed13ad15ce5f290187f42
281
module Caboose class ShippingPackageMethod < ActiveRecord::Base self.table_name = 'store_shipping_package_methods' belongs_to :shipping_package belongs_to :shipping_method attr_accessible :id, :shipping_package_id, :shipping_method_id end end
21.615385
54
0.747331
e8d89f8428dae05dab0d91b84d3e9212b116aab6
2,146
# -*- encoding: utf-8 -*- # stub: jaro_winkler 1.5.1 ruby lib # stub: ext/jaro_winkler/extconf.rb Gem::Specification.new do |s| s.name = "jaro_winkler".freeze s.version = "1.5.1" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Jian Weihang".freeze] s.date = "2018-06-06" s.description = "jaro_winkler is an implementation of Jaro-Winkler \\\n distance algorithm which is written in C extension and will fallback to pure \\\n Ruby version in platforms other than MRI/KRI like JRuby or Rubinius. Both of \\\n C and Ruby implementation support any kind of string encoding, such as \\\n UTF-8, EUC-JP, Big5, etc.".freeze s.email = "tonytonyjan@gmail.com".freeze s.extensions = ["ext/jaro_winkler/extconf.rb".freeze] s.files = ["ext/jaro_winkler/extconf.rb".freeze] s.homepage = "https://github.com/tonytonyjan/jaro_winkler".freeze s.licenses = ["MIT".freeze] s.rubygems_version = "2.6.14".freeze s.summary = "An implementation of Jaro-Winkler distance algorithm written \\ in C extension which supports any kind of string encoding.".freeze s.installed_by_version = "2.6.14" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<bundler>.freeze, ["~> 1.7"]) s.add_development_dependency(%q<rake>.freeze, ["~> 12.0"]) s.add_development_dependency(%q<rake-compiler>.freeze, [">= 0"]) s.add_development_dependency(%q<minitest>.freeze, [">= 0"]) else s.add_dependency(%q<bundler>.freeze, ["~> 1.7"]) s.add_dependency(%q<rake>.freeze, ["~> 12.0"]) s.add_dependency(%q<rake-compiler>.freeze, [">= 0"]) s.add_dependency(%q<minitest>.freeze, [">= 0"]) end else s.add_dependency(%q<bundler>.freeze, ["~> 1.7"]) s.add_dependency(%q<rake>.freeze, ["~> 12.0"]) s.add_dependency(%q<rake-compiler>.freeze, [">= 0"]) s.add_dependency(%q<minitest>.freeze, [">= 0"]) end end
47.688889
351
0.681733
ed31299a0e553a0443934a559a228f09bfd49a59
121
class AddActiveToResources < ActiveRecord::Migration def change add_column :resources, :active, :boolean end end
20.166667
52
0.768595
bb4332aca0b86ac6a67c4baf67153f9b6ab30ab8
1,221
class Zssh < Formula desc "Interactive file transfers over SSH" homepage "https://zssh.sourceforge.io/" url "https://downloads.sourceforge.net/project/zssh/zssh/1.5/zssh-1.5c.tgz" sha256 "a2e840f82590690d27ea1ea1141af509ee34681fede897e58ae8d354701ce71b" bottle do cellar :any_skip_relocation sha256 "0b1567c1d4aef681ff463f058a884eead039fb0c50a1c03820a03c9f67786b52" => :mojave sha256 "9cb26f1bd359977406fae945abd311b2cdc5770570e6350f2ac278bfbe458f5b" => :high_sierra sha256 "49e01bb86097999f21f3d96b0f9cd63a975d4fd52f6e286d42ceee16ee996eb7" => :sierra sha256 "04212f19c1d9a6b97fd56ffe937606f1779849fdf04b93e3f285889599845c8f" => :el_capitan sha256 "94280569f9e1c1deb9d8c3be4256cd501399fd51758f8e2ea6d77fd9f1b6ef2e" => :yosemite sha256 "94b16bb29616a839134527fd869ac40a8fb5fa88b0048d1a93a828e306c2a270" => :mavericks sha256 "e81d8a0d4c8107898aff0cda9abbf4a2caaf098f16c37bd92aa168943c7e6554" => :mountain_lion end depends_on "lrzsz" def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make" bin.install "zssh", "ztelnet" man1.install "zssh.1", "ztelnet.1" end end
42.103448
95
0.776413
01ac84ff7dfe037eb5ac1341cbfaf03d2384e832
250
require 'spec_helper' describe Canaid do it 'has a version number' do expect(Canaid::VERSION).not_to be nil end describe 'configuration' do it 'has configuration' do expect(Canaid::Configuration).not_to be nil end end end
17.857143
49
0.704
3838a5951512c23402e55fe5951ddf96cfbd8713
1,520
class PasswordResetsController < ApplicationController before_action :get_user, only: [:edit, :update] before_action :valid_user, only: [:edit, :update] before_action :check_expiration, only: [:edit, :update] def new end def create @user = User.find_by(email: params[:password_reset][:email].downcase) if @user @user.create_reset_digest @user.send_password_reset_email flash[:info] = "Email sent with password reset instructions" redirect_to root_url else flash.now[:danger] = "Email address not found" render 'new' end end def edit end def update if params[:user][:password].empty? @user.errors.add(:password, "can't be empty") render 'edit' elsif @user.update(user_params) log_in @user @user.update_attribute(:reset_digest, nil) flash[:success] = "Password has been reset." redirect_to @user else render 'edit' end end private def user_params params.require(:user).permit(:password, :password_confirmation) end def get_user @user = User.find_by(email: params[:email]) end # Confirms a valid user. def valid_user unless (@user && @user.activated? && @user.authenticated?(:reset, params[:id])) redirect_to root_url end end # Checks expiration of reset token. def check_expiration if @user.password_reset_expired? flash[:danger] = "Password reset has expired." redirect_to new_password_reset_url end end end
23.384615
73
0.669737
1a06acd1b02be2a879dac46099f66d937ce91559
271
# frozen_string_literal: true FactoryBot.define do factory :repository_git_extra do git_http { 0 } default_branch { 'master' } association :repository, factory: :repository_gitolite key { RedmineGitHosting::Utils::Crypto.generate_secret 64 } end end
24.636364
63
0.745387
d5f0490058ecd65a2b1d8363b53d9bfdc7e881f0
1,899
class OauthController < ApplicationController before_filter :login_required, :except => [:request_token, :access_token, :test_request] before_filter :login_or_oauth_required, :only => [:test_request] before_filter :verify_oauth_consumer_signature, :only => [:request_token] before_filter :verify_oauth_request_token, :only => [:access_token] # Uncomment the following if you are using restful_open_id_authentication # skip_before_filter :verify_authenticity_token def request_token @token = current_client_application.create_request_token if @token render :text => @token.to_query else render :nothing => true, :status => 401 end end def access_token @token = current_token.exchange! if @token render :text => @token.to_query else render :nothing => true, :status => 401 end end def test_request render :text => params.collect{|k,v|"#{k}=#{v}"}.join("&") end def authorize @token = RequestToken.find_by_token params[:oauth_token] unless @token.invalidated? if request.post? if params[:authorize] == '1' @token.authorize!(current_user) redirect_url = params[:oauth_callback] || @token.client_application.callback_url if redirect_url redirect_to "#{redirect_url}?oauth_token=#{@token.token}" else render :action => "authorize_success" end elsif params[:authorize] == "0" @token.invalidate! render :action => "authorize_failure" end end else render :action => "authorize_failure" end end def revoke @token = current_user.tokens.find_by_token params[:token] if @token @token.invalidate! flash[:notice] = "You've revoked the token for #{@token.client_application.name}" end redirect_to oauth_clients_url end end
30.142857
90
0.663507
627d5f73ec59ba47d90c67a8c0a312478d7fc5b1
441
class User < ApplicationRecord before_save { email.downcase! } validates :name, presence: true,length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } has_secure_password validates :password, presence: true, length: { minimum: 6 } end
29.4
62
0.632653
188e6791504d5803b5639096dc004322a53b5d27
793
class MatchController < ApplicationController def artworks query = params.require(:query) response = ArtworkSearchService.call(query: query) render json: response end def genes term = params.require(:term) genes = Gene.match term: term, size: 5 render json: genes end def tags term = params.require(:term) tags = Tag.match term: term, size: 5 render json: tags end def partners term = params.require(:term) partners = Partner.match term: term, size: 5 render json: partners end def fairs term = params.require(:term) fairs = Fair.match term: term, size: 5 render json: fairs end def artists term = params.require(:term) artists = Artist.match term: term, size: 5 render json: artists end end
20.868421
54
0.664565
d59448735ade41d7d8acb155031d8f0bbf425ee4
2,175
class Ccache < Formula desc "Object-file caching compiler wrapper" homepage "https://ccache.dev/" url "https://github.com/ccache/ccache/releases/download/v3.7.1/ccache-3.7.1.tar.xz" sha256 "66fc121a2a33968f9ec428e02f48ff4b8896fbabb759e9c09352267014dcbe65" bottle do cellar :any_skip_relocation sha256 "758092cb544e543094c6db931631112660f817112df869ac44fd82a604921aeb" => :mojave sha256 "db4b6e2637ede1d12536544b7dc3f6c36549c1fad7cfca481a103b88cff134ae" => :high_sierra sha256 "b41e0434efa91fa46caae563d5866fcfee17915c52a8983b8c898d59a5646440" => :sierra end head do url "https://github.com/ccache/ccache.git" depends_on "asciidoc" => :build depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end def install ENV["XML_CATALOG_FILES"] = etc/"xml/catalog" if build.head? system "./autogen.sh" if build.head? system "./configure", "--prefix=#{prefix}", "--mandir=#{man}" system "make" system "make", "install" libexec.mkpath %w[ clang clang++ cc gcc gcc2 gcc3 gcc-3.3 gcc-4.0 gcc-4.2 gcc-4.3 gcc-4.4 gcc-4.5 gcc-4.6 gcc-4.7 gcc-4.8 gcc-4.9 gcc-5 gcc-6 gcc-7 c++ c++3 c++-3.3 c++-4.0 c++-4.2 c++-4.3 c++-4.4 c++-4.5 c++-4.6 c++-4.7 c++-4.8 c++-4.9 c++-5 c++-6 c++-7 g++ g++2 g++3 g++-3.3 g++-4.0 g++-4.2 g++-4.3 g++-4.4 g++-4.5 g++-4.6 g++-4.7 g++-4.8 g++-4.9 g++-5 g++-6 g++-7 ].each do |prog| libexec.install_symlink bin/"ccache" => prog end end def caveats; <<~EOS To install symlinks for compilers that will automatically use ccache, prepend this directory to your PATH: #{opt_libexec} If this is an upgrade and you have previously added the symlinks to your PATH, you may need to modify it to the path specified above so it points to the current version. NOTE: ccache can prevent some software from compiling. ALSO NOTE: The brew command, by design, will never use ccache. EOS end test do ENV.prepend_path "PATH", opt_libexec assert_equal "#{opt_libexec}/gcc", shell_output("which gcc").chomp system "#{bin}/ccache", "-s" end end
33.461538
117
0.661609
f7dbe963bc37c1c0e5ff1edc37e85f13116d6a9d
135
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_Wld_session'
33.75
73
0.8
ac1dc5823437920973518562ee030b0d905851b5
461
class User < ApplicationRecord has_many :courses has_many :enrollments has_many :enrolled_courses, through: :enrollments, source: :course # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable def enrolled_in?(course) return enrolled_courses.include?(course) end end
28.8125
68
0.759219
33634c606fa9a7696cc165858e6913e51fe707ad
140
class Product < ApplicationRecord attribute :quantity, :integer, default: 1 validates :quantity, presence: true has_many :orders end
20
43
0.764286
21e8299b3ff43231548f4c6b63c7a27175a77886
524
# encoding: utf-8 # This file is distributed under New Relic's license terms. # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(:default, Rails.env) if defined?(Bundler) module RpmTestApp class Application < Rails::Application config.encoding = "utf-8" config.filter_parameters += [:password] config.assets.enabled = true config.active_support.deprecation = :notify end end
27.578947
93
0.746183
f70b58483aea9497180938c231147aa678fdee85
488
name 'trusted_certificate' maintainer 'Chef Software, Inc.' maintainer_email 'cookbooks@chef.io' license 'Apache-2.0' description 'Manages adding certificates to the OS trust store' version '3.3.0' %w(ubuntu debian redhat centos suse opensuse opensuseleap scientific oracle amazon zlinux).each do |os| supports os end source_url 'https://github.com/chef-cookbooks/trusted_certificate' issues_url 'https://github.com/chef-cookbooks/trusted_certificate/issues' chef_version '>= 12.15'
30.5
103
0.797131
1ad776c5219902e7bd156867462675de72249987
1,268
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE Gem::Specification.new do |spec| spec.name = 'aws-sdk-s3' spec.version = File.read(File.expand_path('../VERSION', __FILE__)).strip spec.summary = 'AWS SDK for Ruby - Amazon S3' spec.description = 'Official AWS Ruby gem for Amazon Simple Storage Service (Amazon S3). This gem is part of the AWS SDK for Ruby.' spec.author = 'Amazon Web Services' spec.homepage = 'https://github.com/aws/aws-sdk-ruby' spec.license = 'Apache-2.0' spec.email = ['aws-dr-rubygems@amazon.com'] spec.require_paths = ['lib'] spec.files = Dir['LICENSE.txt', 'CHANGELOG.md', 'VERSION', 'lib/**/*.rb'] spec.metadata = { 'source_code_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-s3', 'changelog_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-s3/CHANGELOG.md' } spec.add_dependency('aws-sdk-kms', '~> 1') spec.add_dependency('aws-sigv4', '~> 1.1') spec.add_dependency('aws-sdk-core', '~> 3', '>= 3.112.0') end
38.424242
135
0.660095
5db86652f669edb7548fefc006cf8e8123acfd29
913
# ------------------------------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------------------------------ class DaprCliAT100Rc5 < Formula desc "Client for Dapr." homepage "https://dapr.io" version '1.0.0-rc.5' url "https://github.com/dapr/cli/archive/v1.0.0-rc.5.tar.gz" sha256 "8b0bb2a0a9c49b720563c28b477803ff06547d6d3dd105d5c5801ad1377207e8" depends_on "go" => :build bottle do root_url "https://github.com/dapr/homebrew-tap/releases/download/v1.0.0-rc.5" sha256 cellar :any_skip_relocation, catalina:"8d7b70d4335ed6718ec6156219f7fba1e366a6abc99ecf62860b9e5a37c60a03" end def install system "go", "build", "-ldflags", "-X main.version=#{version} -X main.apiVersion=1.0", "-o", "./cli" bin.install "cli" => "dapr" end test do system "#{bin}/dapr", "--version" end end
30.433333
115
0.611172
aca3f5a3b5e056feccf2c3c76374265786c75240
1,071
require 'formula' class ErlangInstalled < Requirement fatal true default_formula 'erlang' env :userpaths satisfy { erl = which('erl') and begin `#{erl} -noshell -eval 'io:fwrite("~s~n", [erlang:system_info(otp_release)]).' -s erlang halt | grep -q '^R1[6789]'` $?.exitstatus == 0 end } def message; <<-EOS.undent Erlang R16 is required to install. You can install this with: brew install erlang Or you can use an official installer from: http://www.erlang.org/ EOS end end class Elixir < Formula homepage 'http://elixir-lang.org/' url 'https://github.com/elixir-lang/elixir/archive/v0.10.2.tar.gz' sha1 'fd12cfc3d7ebba9087ea1d13de6ad940c644ecf1' head 'https://github.com/elixir-lang/elixir.git' depends_on ErlangInstalled def install system "make" bin.install Dir['bin/*'] - Dir['bin/*.bat'] Dir['lib/*/ebin'].each do |path| app = File.basename(File.dirname(path)) (lib/"#{app}").install path end end test do system "#{bin}/elixir", "-v" end end
21.42
122
0.644258
b98c6f7a0ee8a0a4b157ef5cc88efcd7b7dc342f
1,267
# -*- encoding: utf-8 -*- require File.expand_path("../lib/resque_scheduler/version", __FILE__) Gem::Specification.new do |s| s.name = "resque-mongo-scheduler" s.version = ResqueScheduler::Version s.platform = Gem::Platform::RUBY s.authors = ['Ben VandenBos', 'Nicolas Fouché'] s.email = ['bvandenbos@gmail.com', 'nicolas@silentale.com'] s.homepage = "http://github.com/nfo/resque-mongo-scheduler" s.summary = "Light weight job scheduling on top of Resque Mongo" s.description = %q{Light weight job scheduling on top of Resque Mongo. Adds methods enqueue_at/enqueue_in to schedule jobs in the future. Also supports queueing jobs on a fixed, cron-like schedule.} s.required_rubygems_version = ">= 1.3.6" s.add_development_dependency "bundler", ">= 1.0.0" s.files = `git ls-files`.split("\n") s.executables = `git ls-files`.split("\n").map{|f| f =~ /^bin\/(.*)/ ? $1 : nil}.compact s.require_path = 'lib' s.add_runtime_dependency(%q<mongo>, [">= 1.1"]) s.add_runtime_dependency(%q<mongo-resque>, [">= 1.11.0"]) s.add_runtime_dependency(%q<rufus-scheduler>, [">= 0"]) s.add_development_dependency(%q<mocha>, [">= 0"]) s.add_development_dependency(%q<rack-test>, [">= 0"]) end
42.233333
91
0.657459
acabd74895abbcc4d99a710ccfd69d532dbd849b
142
class AddTimezoneToUserPreferences < ActiveRecord::Migration[5.1] def change add_column :user_preferences, :timezone, :string end end
23.666667
65
0.78169
e9c759aa50f875946da608cb24e8268cbc1e6ce8
584
# frozen_string_literal: true require 'test_helper' require 'compeon/rack_tools/pipes/parse_env' module Compeon module RackTools module Pipes class ParseEnvTest < Minitest::Test def env Rack::MockRequest.env_for('', input: 'foobar', method: 'POST') end def test_parser parsed_env = Compeon::RackTools::Pipes::PARSE_ENV.call(env) assert_kind_of Hash, parsed_env assert_equal 'foobar', parsed_env[:body] assert_kind_of Rack::Request, parsed_env[:request] end end end end end
22.461538
72
0.648973
330bff64f42cf8ec38c34375ba3c544f62879380
1,699
require 'rails_helper' RSpec.feature 'Admin users can' do context 'when there are suppliers' do before do FactoryBot.create(:supplier, name: 'First Supplier') FactoryBot.create_list(:supplier, 24) FactoryBot.create(:supplier, name: 'Last Supplier') sign_in_as_admin end scenario 'view a paged list of suppliers' do visit admin_suppliers_path expect(page).to have_content 'First Supplier' expect(page).to have_content 'Next »' end scenario 'view a second supplier list page' do visit admin_suppliers_path click_on 'Next »' expect(page).to have_content 'Last Supplier' end scenario 'find a supplier' do visit admin_suppliers_path fill_in 'Search', with: 'ast Supp' click_button 'Search' expect(page).to have_content 'Last Supplier' end scenario 'see all suppliers when an empty search term is supplied' do visit admin_suppliers_path fill_in 'Search', with: '' click_button 'Search' expect(page).to have_content 'First Supplier' expect(page).to have_content 'Next »' end scenario 'see when a supplier search returns no results' do visit admin_suppliers_path fill_in 'Search', with: 'Missing Supplier' click_button 'Search' expect(page).to have_content 'No suppliers found for ‘Missing Supplier’' end scenario 'see the search term after performing the supplier search' do visit admin_suppliers_path fill_in 'Search', with: 'ast Supp' click_button 'Search' expect(page).to have_content 'Last Supplier' expect(page).to have_field('search', with: 'ast Supp') end end end
30.890909
78
0.683932
26b7d49893840700d1186916d162b4627bcd5e41
1,954
# frozen_string_literal: true RSpec.describe Qbert::Client do let(:client) { double(send_message: {}, receive_message: {}, delete_message: {}) } let(:queue_url) { "thisisaqurl" } subject { Qbert::Client.new } before do Qbert.configure { |config| config.queue_url = queue_url } allow(Aws::SQS::Client).to receive(:new).and_return(client) end describe ".put_message" do let(:message) { "Hello from Texas" } let(:msg_hash) { { message_body: message, queue_url: queue_url } } it "calls send_message" do allow(subject.client).to receive(:send_message).with(msg_hash) subject.put_message message expect(subject.client).to have_received(:send_message).with(msg_hash) end end describe ".get_messages" do let(:max_msgs) { 10 } let(:message_params) do { max_number_of_messages: max_msgs, queue_url: queue_url } end let(:receipt_handle) { "AQEBur2IJZIwx7HlKp2PQtMxce9HsjKvRB" } let(:msg_body) { "This is a test message" } let(:message) { double(:message, receipt_handle: receipt_handle, body: msg_body) } let(:result) { double(:result, messages: [message]) } let(:delete_params) do { receipt_handle: receipt_handle, queue_url: queue_url } end before do allow(subject.client).to receive(:receive_message).with(message_params).and_return(result) allow(subject.client).to receive(:delete_message).with(delete_params) end it "calls receive_message" do subject.get_messages expect(subject.client).to have_received(:receive_message).with(message_params) end it "calls delete_message" do subject.get_messages expect(subject.client).to have_received(:delete_message).with(delete_params) end it "returns an array" do expect(subject.get_messages).to be_an Array end it "returns an array of message bodies" do expect(subject.get_messages).to eq([msg_body]) end end end
31.516129
96
0.69652
1c7d708f2147e2939cff2b8a9be6c0605cdaf4fc
1,581
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'google/apis/datafusion_v1/service.rb' require 'google/apis/datafusion_v1/classes.rb' require 'google/apis/datafusion_v1/representations.rb' module Google module Apis # Cloud Data Fusion API # # Cloud Data Fusion is a fully-managed, cloud native, enterprise data # integration service for quickly building and managing data pipelines. It # provides a graphical interface to increase time efficiency and reduce # complexity, and allows business users, developers, and data scientists to # easily and reliably build scalable data integration solutions to cleanse, # prepare, blend, transfer and transform data without having to wrestle with # infrastructure. # # @see https://cloud.google.com/data-fusion/docs module DatafusionV1 VERSION = 'V1' REVISION = '20200803' # View and manage your data across Google Cloud Platform services AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform' end end end
38.560976
80
0.745731
61d46a58036f158374da6abfa3a34d9d553892a6
381
class Clock def initialize(hour, minute) @hour = (hour + minute / 60) % 24 @minute = minute % 60 end def self.at(hour, minute) new(hour, minute) end def to_s format('%02d:%02d', @hour, @minute) end def +(other) self.class.new(@hour, @minute + other) end def ==(other) to_s == other.to_s end end module BookKeeping VERSION = 2 end
14.111111
42
0.598425
62a7b7e459e1a8e79a274ccb13e13221633b4f1c
1,857
# frozen_string_literal: true class Tag < ApplicationRecord belongs_to :blog has_and_belongs_to_many :contents, order: "created_at DESC" validates :name, uniqueness: { scope: :blog_id } validates :blog, presence: true validates :name, presence: true before_validation :ensure_naming_conventions attr_accessor :description, :keywords def self.create_from_article!(article) return if article.keywords.nil? tags = [] Tag.transaction do tagwords = article.keywords.to_s.scan(/((['"]).*?\2|[.:[[:alnum:]]]+)/).map do |x| x.first.tr("\"'", "") end tagwords.uniq.each do |tagword| tagname = tagword.to_url tags << article.blog.tags.find_or_create_by(name: tagname) do |tag| tag.display_name = tagword end end end article.tags = tags tags end def ensure_naming_conventions self.display_name = name if display_name.blank? self.name = display_name.to_url if display_name.present? end def self.find_all_with_content_counters Tag.joins(:contents). where(contents: { state: "published" }). select(*Tag.column_names, "COUNT(contents_tags.content_id) as content_counter"). group(*Tag.column_names). order("content_counter DESC").limit(1000) end def self.find_with_char(char) where("name LIKE ? ", "%#{char}%").order("name ASC") end def self.collection_to_string(tags) tags.map(&:display_name).sort. map { |name| / /.match?(name) ? "\"#{name}\"" : name }.join ", " end def published_contents contents.published end def permalink name end def feed_url(format) "#{permalink_url}.#{format.gsub(/\d/, "")}" end def permalink_url(_anchor = nil, only_path = false) blog.url_for(controller: "tags", action: "show", id: permalink, only_path: only_path) end end
25.791667
89
0.662897
391fab15aeba4faa7ba2bdf14573db1321e5dc1c
153
class CreateUsers < ActiveRecord::Migration[5.2] def change create_table :users do |t| t.string :username end end end
21.857143
48
0.601307
6acfa8346d2f9e2bc96878e908ba9f9889ab5b67
317
# Copyright 2011-2012 Rice University. Licensed under the Affero General Public # License version 3 or later. See the COPYRIGHT file for details. # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :assignment_plan_topic do assignment_plan topic end end
26.416667
80
0.782334
08727ef5077093c57efccdca69c388d567d7b806
90
class CardUserSerializer < ActiveModel::Serializer attributes :id, :count, :card_id end
22.5
50
0.788889
7aab86cafa4bb0f317852b227d26a3451f98cbe8
170
#require Rails.root.join('app/controllers/errors_controller.rb') #Rails.application.configure do # config.exceptions_app = ErrorsController.action(:exceptions_app) #end
34
67
0.817647
79cbc7fd5180d05888aed9afced7e49c93a3d5fe
907
ENV['RAILS_ENV'] ||= 'test' require_relative '../config/environment' require 'rails/test_help' require "minitest/reporters" Minitest::Reporters.use! class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. fixtures :all include ApplicationHelper # Add more helper methods to be used by all tests here... # Returns true if a test user is logged in. def is_logged_in? !session[:user_id].nil? end # Log in as a particular user. def log_in_as(user) session[:user_id] = user.id end end class ActionDispatch::IntegrationTest # Log in as a particular user. def log_in_as(user, password: 'password', remember_me: '1') post login_path, params: { session: { email: user.email, password: password, remember_me: remember_me } } end end
27.484848
82
0.657111
62bf7a78906787f164f01c113cdb6291019c1250
356
class CreateRestaurants < ActiveRecord::Migration[6.0] def change create_table :restaurants do |t| t.string :name t.text :address t.boolean :carryout t.boolean :outdoor_dining t.boolean :indoor_dining t.boolean :follows_rules t.belongs_to :author, :class_name => "User" t.timestamps end end end
22.25
54
0.657303
d51214bacac0111f831ffbdff7025de1070e31de
3,737
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core/auxiliary/jtr' class MetasploitModule < Msf::Auxiliary include Msf::Auxiliary::JohnTheRipper def initialize super( 'Name' => 'John the Ripper MySQL Password Cracker (Fast Mode)', 'Description' => %Q{ This module uses John the Ripper to identify weak passwords that have been acquired from the mysql_hashdump module. Passwords that have been successfully cracked are then saved as proper credentials. }, 'Author' => [ 'theLightCosine', 'hdm' ] , 'License' => MSF_LICENSE # JtR itself is GPLv2, but this wrapper is MSF (BSD) ) end def run cracker = new_john_cracker # create the hash file first, so if there aren't any hashes we can quit early cracker.hash_path = hash_file # generate our wordlist and close the file handle wordlist = wordlist_file unless wordlist print_error('This module cannot run without a database connected. Use db_connect to connect to a database.') return end wordlist.close print_status "Wordlist file written out to #{wordlist.path}" cracker.wordlist = wordlist.path cleanup_files = [cracker.hash_path, wordlist.path] ['mysql','mysql-sha1'].each do |format| cracker_instance = cracker.dup cracker_instance.format = format print_status "Cracking #{format} hashes in normal wordlist mode..." # Turn on KoreLogic rules if the user asked for it if datastore['KORELOGIC'] cracker_instance.rules = 'KoreLogicRules' print_status "Applying KoreLogic ruleset..." end cracker_instance.crack do |line| vprint_status line.chomp end print_status "Cracking #{format} hashes in single mode..." cracker_instance.rules = 'single' cracker_instance.crack do |line| vprint_status line.chomp end print_status "Cracking #{format} hashes in incremental mode (Digits)..." cracker_instance.rules = nil cracker_instance.wordlist = nil cracker_instance.incremental = 'Digits' cracker_instance.crack do |line| vprint_status line.chomp end print_status "Cracked Passwords this run:" cracker_instance.each_cracked_password do |password_line| password_line.chomp! next if password_line.blank? fields = password_line.split(":") # If we don't have an expected minimum number of fields, this is probably not a hash line next unless fields.count >=3 username = fields.shift core_id = fields.pop password = fields.join(':') # Anything left must be the password. This accounts for passwords with : in them print_good "#{username}:#{password}" create_cracked_credential( username: username, password: password, core_id: core_id) end end cleanup_files.each do |f| File.delete(f) end end def hash_file wrote_hash = false hashlist = Rex::Quickfile.new("hashes_tmp") framework.db.creds(workspace: myworkspace, type: 'Metasploit::Credential::NonreplayableHash').each do |core| if core.private.jtr_format =~ /mysql|mysql-sha1/ hashlist.puts hash_to_jtr(core) wrote_hash = true end end hashlist.close unless wrote_hash # check if we wrote anything and bail early if we didn't hashlist.delete fail_with Failure::NotFound, 'No applicable hashes in database to crack' end print_status "Hashes Written out to #{hashlist.path}" hashlist.path end end
33.366071
116
0.670591
d5fdd0fde14de3655717ee09f24b37567dc8a7e9
7,231
=begin #Hydrogen Nucleus API #The Hydrogen Nucleus API OpenAPI spec version: 1.9.5 Contact: info@hydrogenplatform.com Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.19 =end require 'date' module NucleusApi # Page Object class PagePortfolioTransaction attr_accessor :content attr_accessor :first attr_accessor :last attr_accessor :number attr_accessor :number_of_elements attr_accessor :size attr_accessor :sort attr_accessor :total_elements attr_accessor :total_pages # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'content' => :'content', :'first' => :'first', :'last' => :'last', :'number' => :'number', :'number_of_elements' => :'number_of_elements', :'size' => :'size', :'sort' => :'sort', :'total_elements' => :'total_elements', :'total_pages' => :'total_pages' } end # Attribute type mapping. def self.swagger_types { :'content' => :'Array<PortfolioTransaction>', :'first' => :'BOOLEAN', :'last' => :'BOOLEAN', :'number' => :'Integer', :'number_of_elements' => :'Integer', :'size' => :'Integer', :'sort' => :'Array<Sort>', :'total_elements' => :'Integer', :'total_pages' => :'Integer' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } if attributes.has_key?(:'content') if (value = attributes[:'content']).is_a?(Array) self.content = value end end if attributes.has_key?(:'first') self.first = attributes[:'first'] end if attributes.has_key?(:'last') self.last = attributes[:'last'] end if attributes.has_key?(:'number') self.number = attributes[:'number'] end if attributes.has_key?(:'number_of_elements') self.number_of_elements = attributes[:'number_of_elements'] end if attributes.has_key?(:'size') self.size = attributes[:'size'] end if attributes.has_key?(:'sort') if (value = attributes[:'sort']).is_a?(Array) self.sort = value end end if attributes.has_key?(:'total_elements') self.total_elements = attributes[:'total_elements'] end if attributes.has_key?(:'total_pages') self.total_pages = attributes[:'total_pages'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && content == o.content && first == o.first && last == o.last && number == o.number && number_of_elements == o.number_of_elements && size == o.size && sort == o.sort && total_elements == o.total_elements && total_pages == o.total_pages end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [content, first, last, number, number_of_elements, size, sort, total_elements, total_pages].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime (value) when :Date (value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = NucleusApi.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
27.811538
107
0.598949
f853bb1a45550e426ff2509311b3d37029fef368
505
require_relative "InfoLogger" require_relative "WarningLogger" require_relative "ErrorLogger" require_relative "LoggerType" class LoggerFactory def create(type) case type when LoggerType::InfoLoggerType return InfoLogger.new when LoggerType::WarningLoggerType return WarningLogger.new when LoggerType::ErrorLoggerType return ErrorLogger.new else return nil end end end
26.578947
46
0.629703
282239f28bba4471a89a46a7e6e0b4592446bdf0
152
# frozen_string_literal: true class ExtensionColocatedTask < ColocatedTask def self.label Constants.CO_LOCATED_ADMIN_ACTIONS.extension end end
19
48
0.822368
9158634afa4c7d30f9084e6cf3b10b7072ba0f0e
6,158
# frozen_string_literal: true module RuboCop module Cop module Style # # This cop looks for uses of Perl-style global variables. # # @example EnforcedStyle: use_english_names (default) # # good # puts $LOAD_PATH # puts $LOADED_FEATURES # puts $PROGRAM_NAME # puts $ERROR_INFO # puts $ERROR_POSITION # puts $FIELD_SEPARATOR # or $FS # puts $OUTPUT_FIELD_SEPARATOR # or $OFS # puts $INPUT_RECORD_SEPARATOR # or $RS # puts $OUTPUT_RECORD_SEPARATOR # or $ORS # puts $INPUT_LINE_NUMBER # or $NR # puts $LAST_READ_LINE # puts $DEFAULT_OUTPUT # puts $DEFAULT_INPUT # puts $PROCESS_ID # or $PID # puts $CHILD_STATUS # puts $LAST_MATCH_INFO # puts $IGNORECASE # puts $ARGV # or ARGV # puts $MATCH # puts $PREMATCH # puts $POSTMATCH # puts $LAST_PAREN_MATCH # # @example EnforcedStyle: use_perl_names # # good # puts $: # puts $" # puts $0 # puts $! # puts $@ # puts $; # puts $, # puts $/ # puts $\ # puts $. # puts $_ # puts $> # puts $< # puts $$ # puts $? # puts $~ # puts $= # puts $* # puts $& # puts $` # puts $' # puts $+ # class SpecialGlobalVars < Cop include ConfigurableEnforcedStyle MSG_BOTH = 'Prefer `%<prefer>s` from the stdlib \'English\' ' \ 'module (don\'t forget to require it) or `%<regular>s` over ' \ '`%<global>s`.' MSG_ENGLISH = 'Prefer `%<prefer>s` from the stdlib \'English\' ' \ 'module (don\'t forget to require it) over `%<global>s`.' MSG_REGULAR = 'Prefer `%<prefer>s` over `%<global>s`.' ENGLISH_VARS = { # rubocop:disable Style/MutableConstant :$: => [:$LOAD_PATH], :$" => [:$LOADED_FEATURES], :$0 => [:$PROGRAM_NAME], :$! => [:$ERROR_INFO], :$@ => [:$ERROR_POSITION], :$; => %i[$FIELD_SEPARATOR $FS], :$, => %i[$OUTPUT_FIELD_SEPARATOR $OFS], :$/ => %i[$INPUT_RECORD_SEPARATOR $RS], :$\ => %i[$OUTPUT_RECORD_SEPARATOR $ORS], :$. => %i[$INPUT_LINE_NUMBER $NR], :$_ => [:$LAST_READ_LINE], :$> => [:$DEFAULT_OUTPUT], :$< => [:$DEFAULT_INPUT], :$$ => %i[$PROCESS_ID $PID], :$? => [:$CHILD_STATUS], :$~ => [:$LAST_MATCH_INFO], :$= => [:$IGNORECASE], :$* => %i[$ARGV ARGV], :$& => [:$MATCH], :$` => [:$PREMATCH], :$' => [:$POSTMATCH], :$+ => [:$LAST_PAREN_MATCH] } PERL_VARS = Hash[ENGLISH_VARS.flat_map { |k, vs| vs.map { |v| [v, [k]] } }] ENGLISH_VARS.merge!( Hash[ENGLISH_VARS.flat_map { |_, vs| vs.map { |v| [v, [v]] } }] ) PERL_VARS.merge!( Hash[PERL_VARS.flat_map { |_, vs| vs.map { |v| [v, [v]] } }] ) ENGLISH_VARS.each_value(&:freeze).freeze PERL_VARS.each_value(&:freeze).freeze # Anything *not* in this set is provided by the English library. NON_ENGLISH_VARS = Set.new(%i[ $LOAD_PATH $LOADED_FEATURES $PROGRAM_NAME ARGV ]).freeze def on_gvar(node) global_var, = *node return unless (preferred = preferred_names(global_var)) if preferred.include?(global_var) correct_style_detected else opposite_style_detected add_offense(node) end end def message(node) global_var, = *node if style == :use_english_names format_english_message(global_var) else format(MSG_REGULAR, prefer: preferred_names(global_var).first, global: global_var) end end def autocorrect(node) lambda do |corrector| global_var, = *node while node.parent&.begin_type? && node.parent.children.one? node = node.parent end corrector.replace(node, replacement(node, global_var)) end end private def format_english_message(global_var) regular, english = ENGLISH_VARS[global_var].partition do |var| NON_ENGLISH_VARS.include? var end format_message(english, regular, global_var) end def format_message(english, regular, global) if regular.empty? format(MSG_ENGLISH, prefer: format_list(english), global: global) elsif english.empty? format(MSG_REGULAR, prefer: format_list(regular), global: global) else format(MSG_BOTH, prefer: format_list(english), regular: format_list(regular), global: global) end end # For now, we assume that lists are 2 items or less. Easy grammar! def format_list(items) items.join('` or `') end def replacement(node, global_var) parent_type = node.parent&.type preferred_name = preferred_names(global_var).first return preferred_name.to_s unless %i[dstr xstr regexp].include?(parent_type) return english_name_replacement(preferred_name, node) if style == :use_english_names "##{preferred_name}" end def preferred_names(global) if style == :use_english_names ENGLISH_VARS[global] else PERL_VARS[global] end end def english_name_replacement(preferred_name, node) return "\#{#{preferred_name}}" if node.begin_type? "{#{preferred_name}}" end end end end end
29.605769
94
0.501949