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
0188ab1120fadae707a14e16b5c5199b64c63013
4,260
module Hancock::News module Admin module News def self.config(nav_label = nil, fields = {}) if nav_label.is_a?(Hash) nav_label, fields = nav_label[:nav_label], nav_label elsif nav_label.is_a?(Array) nav_label, fields = nil, nav_label end Proc.new { navigation_label(!nav_label.blank? ? nav_label : I18n.t("hancock.news")) list do scopes [:by_date, :enabled, nil] sort_by :publicate_time field :enabled, :toggle do searchable false end field :published, :toggle do searchable false end field :name do searchable true end field :publicate_time do searchable false end field :slug do searchable true searchable_columns do [{column: "#{abstract_model.table_name}._slugs", type: :string}] end queryable true end field :time do searchable false end field :categories do # searchable :name end if Hancock::News.config.pages_support and Hancock::News.configuration.can_connect_news_with_pages field :connected_pages, :hancock_connectable end group :content, &Hancock::Admin.content_block if Hancock::News.config.cache_support group :caching, &Hancock::Cache::Admin.caching_block end end edit do field :enabled, :toggle field :published, :toggle field :name if Hancock::News.config.pages_support and Hancock::News.configuration.can_connect_news_with_pages group :connected_pages do active false field :connected_pages, :hancock_connectable do read_only do !bindings[:view].current_user.admin? end end end end field :publicate_time field :time group(:categories, &Hancock::Admin.categories_block) group :URL, &Hancock::Admin.url_block # group :URL do # active false # field :slugs, :hancock_slugs # field :text_slug # end if Hancock::News.config.gallery_support group :image, &Hancock::Gallery::Admin.images_block(:images) # group :image do # active false # field :image, :hancock_image # field :images # end end group :content, &Hancock::Admin.content_block # group :content do # active false # field :excerpt, :hancock_html # field :content, :hancock_html # end Hancock::RailsAdminGroupPatch::hancock_cms_group(self, fields) if Hancock::News.config.seo_support group :seo_n_sitemap, &Hancock::Seo::Admin.seo_n_sitemap_block end # if Hancock::News.config.seo_support # group :seo do # active false # field :seo # end # group :sitemap_data do # active false # field :sitemap_data # end # end if Hancock::News.config.cache_support group :caching, &Hancock::Cache::Admin.caching_block end if Hancock::News.config.insertions_support group :insertions, &Hancock::Admin.insertions_block end end nested_set({max_depth: 1, scopes: []}) sort_embedded( { fields: [:images] } ) if defined?(RailsAdminMultipleFileUpload) multiple_file_upload( { fields: [:images] } ) end if block_given? yield self end } end end end end
29.178082
109
0.497183
26aaf5860cac2d4b8b9d4ad4f37e9abef20d9300
447
module Zenform module Param class TicketField < Base FIELDS = %w{title type visible_in_portal editable_in_portal required_in_portal description custom_field_options} FIELDS.each { |field| attr_reader field } def validate! %w{title type}.each { |field| validate_field! field } validate_field!("custom_field_options") if type == "tagger" end def format to_h end end end end
23.526316
118
0.666667
21aaa038ba0ac63c603f5813c963562f47403913
872
require File.dirname(__FILE__) + '/../test_helper' class Widget include XML::Mapping time_node :work_start_on, 'WorkStartOn', :default_value => nil end class TimeNodeTest < Test::Unit::TestCase def setup @xml = <<-END <Widget> <WorkStartOn>11:30:00</WorkStartOn> </Widget> END end def test_load_from_xml item = Widget.load_from_xml(REXML::Document.new(@xml).root) assert_instance_of Time, item.work_start_on assert_equal Time.parse('11:30:00'), item.work_start_on end def test_save_to_xml widget = Widget.new widget.work_start_on = Time.parse('11:30:00') assert_equal '<widget><WorkStartOn>11:30:00</WorkStartOn></widget>', widget.save_to_xml.to_s end def test_set_with_non_time_object widget = Widget.new widget.work_start_on = '11:30:00' assert_raise(RuntimeError){ widget.save_to_xml } end end
22.947368
96
0.71789
7a1049cd7e64ace603ef5ed0919e26cc5611af3c
432
module Paynl module Api class GetService < Api def getData Paynl::Helper::requireServiceId @@data['serviceId'] = Paynl::Config::getServiceId Paynl::Helper::requireApiToken @@data['token'] = Paynl::Config::getApiToken return super; end def doRequest # TODO: add caching to this return super('transaction/getService', 16) end end end end
19.636364
57
0.601852
38eef58299a827321bc2efe9bfe6c8a989963cc0
831
# frozen_string_literal: true class CostSplit::CostSplitCompanyMonthlyAdjustsController < CostSplit::BaseController def create to_split_company_code = split_cost_cost_split_company_monthly_adjust_params.delete(:to_split_company_code) month = split_cost_cost_split_company_monthly_adjust_params.delete(:month) adj = SplitCost::CostSplitCompanyMonthlyAdjust.find_or_create_by(to_split_company_code: to_split_company_code, month: month) adj.update(split_cost_cost_split_company_monthly_adjust_params.merge(user_id: current_user.id)) end private def split_cost_cost_split_company_monthly_adjust_params params.fetch(:split_cost_cost_split_company_monthly_adjust, {}) .permit(:to_split_company_code, :month, :group_cost_adjust, :shanghai_area_cost_adjust, :shanghai_hq_cost_adjust) end end
46.166667
128
0.836342
39c05f554248bbe23de1e2a72f249e227c319ac4
3,411
require "spec_helper" module Spree describe Spree::ProductDuplicator, type: :model do let(:product) { create(:product, properties: [create(:property, name: "MyProperty")]) } let!(:duplicator) { Spree::ProductDuplicator.new(product) } let(:image) { File.open(File.expand_path("../../../fixtures/thinking-cat.jpg", __FILE__)) } let(:params) do { viewable_id: product.master.id, viewable_type: "Spree::Variant", attachment: image, alt: "position 1", position: 1, } end before do Spree::Image.create(params) end it "will duplicate the product" do expect { duplicator.duplicate }.to change { Spree::Product.count }.by(1) end it "will duplicate already duplicated product" do expect { 3.times { duplicator.duplicate } }.to change { Spree::Product.count }.by(3) end context "when image duplication enabled" do it "will duplicate the product images" do expect { duplicator.duplicate }.to change { Spree::Image.count }.by(1) end end context "when image duplication disabled" do let!(:duplicator) { Spree::ProductDuplicator.new(product, false) } it "will not duplicate the product images" do expect { duplicator.duplicate }.to change { Spree::Image.count }.by(0) end end context "image duplication default" do context "when default is set to true" do it "clones images if no flag passed to initializer" do expect { duplicator.duplicate }.to change { Spree::Image.count }.by(1) end end context "when default is set to false" do before do ProductDuplicator.clone_images_default = false end after do ProductDuplicator.clone_images_default = true end it "does not clone images if no flag passed to initializer" do expect { ProductDuplicator.new(product).duplicate }.to change { Spree::Image.count }.by(0) end end end context "product attributes" do let!(:new_product) { duplicator.duplicate } it "will set an unique name" do expect(new_product.name).to eql "COPY OF #{product.name}" end it "will set an unique sku" do expect(new_product.sku).to include "COPY OF SKU" end it "copied the properties" do expect(new_product.product_properties.count).to be 1 expect(new_product.product_properties.first.property.name).to eql "MyProperty" end end context "with variants" do let(:option_type) { create(:option_type, name: "MyOptionType") } let(:option_value1) { create(:option_value, name: "OptionValue1", option_type: option_type) } let(:option_value2) { create(:option_value, name: "OptionValue2", option_type: option_type) } let!(:variant1) { create(:variant, product: product, option_values: [option_value1]) } let!(:variant2) { create(:variant, product: product, option_values: [option_value2]) } it "will duplciate the variants" do # will change the count by 3, since there will be a master variant as well expect { duplicator.duplicate }.to change { Spree::Variant.count }.by(3) end it "will not duplicate the option values" do expect { duplicator.duplicate }.to change { Spree::OptionValue.count }.by(0) end end end end
33.116505
100
0.646438
e85e24bb6370e264a76b26f471dbea14a91ef637
1,275
Pod::Spec.new do |s| s.name = 'SVProgressHUD' s.version = '2.2.6' s.ios.deployment_target = '8.3' s.tvos.deployment_target = '9.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A clean and lightweight progress HUD for your iOS and tvOS app.' s.homepage = 'https://github.com/SVProgressHUD/SVProgressHUD' s.authors = { 'Sam Vermette' => 'hello@samvermette.com', 'Tobias Tiemerding' => 'tobias@tiemerding.com' } s.source = { :git => 'https://github.com/SVProgressHUD/SVProgressHUD.git', :tag => s.version.to_s } s.description = 'SVProgressHUD is a clean and easy-to-use HUD meant to display the progress of an ongoing task on iOS and tvOS. The success and error icons are from Freepik from Flaticon and are licensed under Creative Commons BY 3.0.' s.framework = 'QuartzCore' s.requires_arc = true s.default_subspec = 'Core' s.subspec 'Core' do |core| core.source_files = 'Sources/SVProgressHUD/*.{h,m}' core.resources = 'SVProgressHUD/SVProgressHUD.bundle' end s.subspec 'AppExtension' do |ext| ext.source_files = 'SVProgressHUD/*.{h,m}' ext.resources = 'SVProgressHUD/SVProgressHUD.bundle' ext.pod_target_xcconfig = { 'GCC_PREPROCESSOR_DEFINITIONS' => 'SV_APP_EXTENSIONS=1' } end end
42.5
237
0.694118
284097b73542d37df2485fbfb14a9d0da516d02f
2,115
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2019_10_12_205055) do create_table "microposts", force: :cascade do |t| t.text "content" t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "picture" t.index ["user_id", "created_at"], name: "index_microposts_on_user_id_and_created_at" t.index ["user_id"], name: "index_microposts_on_user_id" end create_table "relationships", force: :cascade do |t| t.integer "follower_id" t.integer "followed_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["followed_id"], name: "index_relationships_on_followed_id" t.index ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true t.index ["follower_id"], name: "index_relationships_on_follower_id" end create_table "users", force: :cascade do |t| t.string "name" t.string "email" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "password_digest" t.string "remember_digest" t.boolean "admin", default: false t.string "activation_digest" t.boolean "activated", default: false t.datetime "activated_at" t.string "reset_digest" t.datetime "reset_sent_at" t.index ["email"], name: "index_users_on_email", unique: true end end
40.673077
116
0.736643
380f10b54dce5d833251ab3fbe7ecc7d6d5884df
196
# frozen_string_literal: true require 'rails_helper' describe OrganizationDisplayName do context 'Extends LocalizedName' do it { is_expected.to validate_presence :organization } end end
19.6
57
0.795918
1c453468089d2be71e711489c7e8e2ae2490c56b
360
require 'simplecov' SimpleCov.start require 'bundler/setup' require 'rake' require 'support/shared_contexts/rake' require 'rake_template' RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = '.rspec_status' config.expect_with :rspec do |c| c.syntax = :expect end end
18.947368
63
0.761111
03f027d18a70fc39f62c01b3826faf6094f4fd08
136
# frozen_string_literal: true module RailsBestPractices module Core # Mailer classes. class Mailers < Klasses; end end end
15.111111
32
0.735294
bf6f6c86c6862d862b835d94bfefc18eedd705bb
3,281
# frozen_string_literal: true # Include this into controller to enable site_account support. module SiteAccountSupport def self.included(base) base.class_eval do helper_method :site_account helper_method :domain_account end end private class NoAccountForDomain < ActiveRecord::RecordNotFound def initialize(request) super "Couldn't find an account for domain #{request.try(:host)}" end end def domain_account @domain_account ||= site_account_request.domain_account or raise NoAccountForDomain.new(request) end delegate :site_account, :site_account_by_provider_key, to: :site_account_request delegate :internal_host, to: :request def site_account_request @_site_account_request ||= SiteAccountSupport::Request.new(request) end # Am I on the domain of my provider? def provider_domain? @_provider_domain ||= current_account.provider_account == site_account end # Use this as before filter, to make sure the action is performed on the # admin domain for the provider account def force_provider_domain if current_account && !provider_domain? && request.get? redirect_to_domain(current_account.external_admin_domain) end end def force_provider_or_master_domain unless ThreeScale.tenant_mode.master? || Account.is_admin_domain?(internal_host) || Account.is_master_domain?(internal_host) render_error 'Access denied', :status => :forbidden end end def buyer_domain? @_buyer_domain ||= !Account.is_admin_domain?(internal_host) end def admin_domain? current_account.internal_self_domain == internal_host end class Request attr_reader :request private :request delegate :tenant_mode, to: ThreeScale delegate :host, :internal_host, to: :request, allow_nil: true module MasterDomainWildcard def find_provider Account.master_on_premises || super end def domain_account Account.master_on_premises || super end def site_account_by_provider_key return unless (key = provider_key.presence) if ThreeScale.master_on_premises? Account.where(master: true).first_by_provider_key!(key) || super else super end end def site_account_by_domain Account.master_on_premises || super end end prepend MasterDomainWildcard def initialize(request) @request = request end def find_provider Account.providers_with_master.find_by!(self_domain: internal_host) end def domain_account Account.find_by(self_domain: internal_host) end def site_account @_site_account ||= site_account_by_provider_key || site_account_by_domain or raise NoAccountForDomain.new(request) end def site_account_by_provider_key return unless (key = provider_key.presence) Account.providers_with_master.by_self_domain(internal_host).first_by_provider_key!(key) end def site_account_by_domain site = Account.find_by(self_domain: internal_host) if site site.provider_account else Account.find_by(domain: internal_host) end end private def provider_key request.params[:provider_key] end end end
25.632813
128
0.722341
4abcf138f5fc3f8e0dd33bd15453649ec350febc
121
require 'multi_spec' describe 'Multi Tests v 5.x' do include_examples 'multi::init', "5.1.2", ["ingest-geoip"] end
13.444444
59
0.677686
5df3ba32dfa9999fdeb1ecd89aa4ecd45a0985dd
2,470
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads/v6/errors/image_error.proto require 'google/protobuf' require 'google/api/annotations_pb' Google::Protobuf::DescriptorPool.generated_pool.build do add_file("google/ads/googleads/v6/errors/image_error.proto", :syntax => :proto3) do add_message "google.ads.googleads.v6.errors.ImageErrorEnum" do end add_enum "google.ads.googleads.v6.errors.ImageErrorEnum.ImageError" do value :UNSPECIFIED, 0 value :UNKNOWN, 1 value :INVALID_IMAGE, 2 value :STORAGE_ERROR, 3 value :BAD_REQUEST, 4 value :UNEXPECTED_SIZE, 5 value :ANIMATED_NOT_ALLOWED, 6 value :ANIMATION_TOO_LONG, 7 value :SERVER_ERROR, 8 value :CMYK_JPEG_NOT_ALLOWED, 9 value :FLASH_NOT_ALLOWED, 10 value :FLASH_WITHOUT_CLICKTAG, 11 value :FLASH_ERROR_AFTER_FIXING_CLICK_TAG, 12 value :ANIMATED_VISUAL_EFFECT, 13 value :FLASH_ERROR, 14 value :LAYOUT_PROBLEM, 15 value :PROBLEM_READING_IMAGE_FILE, 16 value :ERROR_STORING_IMAGE, 17 value :ASPECT_RATIO_NOT_ALLOWED, 18 value :FLASH_HAS_NETWORK_OBJECTS, 19 value :FLASH_HAS_NETWORK_METHODS, 20 value :FLASH_HAS_URL, 21 value :FLASH_HAS_MOUSE_TRACKING, 22 value :FLASH_HAS_RANDOM_NUM, 23 value :FLASH_SELF_TARGETS, 24 value :FLASH_BAD_GETURL_TARGET, 25 value :FLASH_VERSION_NOT_SUPPORTED, 26 value :FLASH_WITHOUT_HARD_CODED_CLICK_URL, 27 value :INVALID_FLASH_FILE, 28 value :FAILED_TO_FIX_CLICK_TAG_IN_FLASH, 29 value :FLASH_ACCESSES_NETWORK_RESOURCES, 30 value :FLASH_EXTERNAL_JS_CALL, 31 value :FLASH_EXTERNAL_FS_CALL, 32 value :FILE_TOO_LARGE, 33 value :IMAGE_DATA_TOO_LARGE, 34 value :IMAGE_PROCESSING_ERROR, 35 value :IMAGE_TOO_SMALL, 36 value :INVALID_INPUT, 37 value :PROBLEM_READING_FILE, 38 value :IMAGE_CONSTRAINTS_VIOLATED, 39 value :FORMAT_NOT_ALLOWED, 40 end end end module Google module Ads module GoogleAds module V6 module Errors ImageErrorEnum = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v6.errors.ImageErrorEnum").msgclass ImageErrorEnum::ImageError = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v6.errors.ImageErrorEnum.ImageError").enummodule end end end end end
35.797101
166
0.722672
e20c6b2d8504153f471e012e735ad087b0a338c5
16,915
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core/auxiliary/report' class MetasploitModule < Msf::Auxiliary # Exploit mixins should be called first include Msf::Exploit::Remote::SMB::Client include Msf::Exploit::Remote::SMB::Client::Authenticated include Msf::Exploit::Remote::DCERPC # Scanner mixin should be near last include Msf::Auxiliary::Report include Msf::Auxiliary::Scanner def initialize(info={}) super(update_info(info, 'Name' => 'SMB Share Enumeration', 'Description' => %q{ This module determines what shares are provided by the SMB service and which ones are readable/writable. It also collects additional information such as share types, directories, files, time stamps, etc. By default, a netshareenum request is done in order to retrieve share information, but if this fails, you may also fall back to SRVSVC. }, 'Author' => [ 'hdm', 'nebulus', 'sinn3r', 'r3dy', 'altonjx' ], 'License' => MSF_LICENSE, 'DefaultOptions' => { 'DCERPC::fake_bind_multi' => false } )) register_options( [ OptBool.new('SpiderShares', [false, 'Spider shares recursively', false]), OptBool.new('ShowFiles', [true, 'Show detailed information when spidering', false]), OptBool.new('SpiderProfiles', [false, 'Spider only user profiles when share = C$', true]), OptEnum.new('LogSpider', [false, '0 = disabled, 1 = CSV, 2 = table (txt), 3 = one liner (txt)', 3, [0,1,2,3]]), OptInt.new('MaxDepth', [true, 'Max number of subdirectories to spider', 999]), OptBool.new('USE_SRVSVC_ONLY', [true, 'List shares only with SRVSVC', false ]) ]) deregister_options('RPORT', 'RHOST') end def share_type(val) [ 'DISK', 'PRINTER', 'DEVICE', 'IPC', 'SPECIAL', 'TEMPORARY' ][val] end def device_type_int_to_text(device_type) types = [ "UNSET", "BEEP", "CDROM", "CDROM FILE SYSTEM", "CONTROLLER", "DATALINK", "DFS", "DISK", "DISK FILE SYSTEM", "FILE SYSTEM", "INPORT PORT", "KEYBOARD", "MAILSLOT", "MIDI IN", "MIDI OUT", "MOUSE", "UNC PROVIDER", "NAMED PIPE", "NETWORK", "NETWORK BROWSER", "NETWORK FILE SYSTEM", "NULL", "PARALLEL PORT", "PHYSICAL NETCARD", "PRINTER", "SCANNER", "SERIAL MOUSE PORT", "SERIAL PORT", "SCREEN", "SOUND", "STREAMS", "TAPE", "TAPE FILE SYSTEM", "TRANSPORT", "UNKNOWN", "VIDEO", "VIRTUAL DISK", "WAVE IN", "WAVE OUT", "8042 PORT", "NETWORK REDIRECTOR", "BATTERY", "BUS EXTENDER", "MODEM", "VDM" ] types[device_type] end def to_unix_time(thi, tlo) t = ::Time.at(::Rex::Proto::SMB::Utils.time_smb_to_unix(thi, tlo)) t.strftime("%m-%d-%Y %H:%M:%S") end def eval_host(ip, share, subdir = "") read = write = false # srvsvc adds a null byte that needs to be removed share = share.chomp("\x00") return false,false,nil,nil if share == 'IPC$' self.simple.connect("\\\\#{ip}\\#{share}") begin device_type = self.simple.client.queryfs_fs_device['device_type'] unless device_type vprint_error("\\\\#{ip}\\#{share}: Error querying filesystem device type") return false,false,nil,nil end rescue ::Rex::Proto::SMB::Exceptions::ErrorCode => e err = e.to_s.scan(/The server responded with error: (\w+)/i).flatten[0] case err when /0xffff0002/ # 0xffff0002 means that the server can't handle the request for device type device_type = -1 when /STATUS_INVALID_DEVICE_REQUEST/ return false,false,"Invalid device request" when /0x00040002/ # Samba may throw this error too return false,false,"Mac/Apple Clipboard?" when /STATUS_NETWORK_ACCESS_DENIED/, /0x00030001/, /0x00060002/ # 0x0006002 = bad network name, 0x0030001 Directory not found return false,false,nil,nil else vprint_error("\\\\#{ip}\\#{share}: Error querying filesystem device type") return false,false,nil,nil end end skip = false msg = '' case device_type when -1 msg = "Unable to determine device" when 1, 21 .. 29, 34 .. 35, 37 .. 44 skip = true msg = "Unhandled Device Type (#{device_type})" when 2 .. 16, 18 .. 20, 30 .. 33, 36 msg = device_type_int_to_text(device_type) when 17 skip = true msg = device_type_int_to_text(device_type) else msg = "Unknown Device Type" msg << " (#{device_type})" if device_type end return read,write,msg,nil if skip rfd = self.simple.client.find_first("#{subdir}\\*") read = true if rfd != nil # Test writable filename = Rex::Text.rand_text_alpha(rand(8)) wfd = simple.open("\\#{filename}", 'rwct') wfd << Rex::Text.rand_text_alpha(rand(1024)) wfd.close simple.delete("\\#{filename}") simple.disconnect("\\\\#{ip}\\#{share}") # Operating under assumption STATUS_ACCESS_DENIED or the like will get # thrown before write=true write = true return read,write,msg,rfd rescue ::Rex::Proto::SMB::Exceptions::NoReply,::Rex::Proto::SMB::Exceptions::InvalidType, ::Rex::Proto::SMB::Exceptions::ReadPacket,::Rex::Proto::SMB::Exceptions::ErrorCode return read,false,msg,rfd end def get_os_info(ip, rport) os = smb_fingerprint os_info = "#{os['os']} #{os['sp']} (#{os['lang']})" if os['os'] != "Unknown" report_service( :host => ip, :port => rport, :proto => 'tcp', :name => 'smb', :info => os_info ) if os_info os_info end def lanman_netshareenum(ip, rport, info) shares = [] begin res = self.simple.client.trans( "\\PIPE\\LANMAN", ( [0x00].pack('v') + "WrLeh\x00" + "B13BWz\x00" + [0x01, 65406].pack("vv") )) rescue ::Rex::Proto::SMB::Exceptions::ErrorCode => e if e.error_code == 0xC00000BB vprint_error("Got 0xC00000BB while enumerating shares, switching to srvsvc...") @srvsvc = true # Make sure the module is aware of this state return srvsvc_netshareenum(ip) end end return [] if res.nil? lerror, lconv, lentries, lcount = res['Payload'].to_s[ res['Payload'].v['ParamOffset'], res['Payload'].v['ParamCount'] ].unpack("v4") data = res['Payload'].to_s[ res['Payload'].v['DataOffset'], res['Payload'].v['DataCount'] ] 0.upto(lentries - 1) do |i| sname,tmp = data[(i * 20) + 0, 14].split("\x00") stype = data[(i * 20) + 14, 2].unpack('v')[0] scoff = data[(i * 20) + 16, 2].unpack('v')[0] scoff -= lconv if lconv != 0 scomm,tmp = data[scoff, data.length - scoff].split("\x00") shares << [ sname, share_type(stype), scomm] end shares end def srvsvc_netshareenum(ip) shares = [] simple.connect("\\\\#{ip}\\IPC$") handle = dcerpc_handle('4b324fc8-1670-01d3-1278-5a47bf6ee188', '3.0', 'ncacn_np', ["\\srvsvc"]) begin dcerpc_bind(handle) rescue Rex::Proto::SMB::Exceptions::ErrorCode => e vprint_error(e.message) return [] end stubdata = NDR.uwstring("\\\\#{ip}") + NDR.long(1) #level ref_id = stubdata[0,4].unpack("V")[0] ctr = [1, ref_id + 4 , 0, 0].pack("VVVV") stubdata << ctr stubdata << NDR.align(ctr) stubdata << ["FFFFFFFF"].pack("H*") stubdata << [ref_id + 8, 0].pack("VV") response = dcerpc.call(0x0f, stubdata) res = response.dup win_error = res.slice!(-4, 4).unpack("V")[0] if win_error != 0 raise "DCE/RPC error : Win_error = #{win_error + 0}" end # remove some uneeded data res.slice!(0,12) # level, CTR header, Reference ID of CTR share_count = res.slice!(0, 4).unpack("V")[0] res.slice!(0,4) # Reference ID of CTR1 share_max_count = res.slice!(0, 4).unpack("V")[0] raise "Dce/RPC error : Unknow situation encountered count != count max (#{share_count}/#{share_max_count})" if share_max_count != share_count # RerenceID / Type / ReferenceID of Comment types = res.slice!(0, share_count * 12).scan(/.{12}/n).map{|a| a[4,2].unpack("v")[0]} share_count.times do |t| length, offset, max_length = res.slice!(0, 12).unpack("VVV") raise "Dce/RPC error : Unknow situation encountered offset != 0 (#{offset})" if offset != 0 raise "Dce/RPC error : Unknow situation encountered length !=max_length (#{length}/#{max_length})" if length != max_length name = res.slice!(0, 2 * length).gsub('\x00','') res.slice!(0,2) if length % 2 == 1 # pad comment_length, comment_offset, comment_max_length = res.slice!(0, 12).unpack("VVV") raise "Dce/RPC error : Unknow situation encountered comment_offset != 0 (#{comment_offset})" if comment_offset != 0 if comment_length != comment_max_length raise "Dce/RPC error : Unknow situation encountered comment_length != comment_max_length (#{comment_length}/#{comment_max_length})" end comment = res.slice!(0, 2 * comment_length).gsub('\x00','') res.slice!(0,2) if comment_length % 2 == 1 # pad name = Rex::Text.to_ascii(name) s_type = Rex::Text.to_ascii(share_type(types[t])) comment = Rex::Text.to_ascii(comment) shares << [ name, s_type, comment ] end shares end def get_user_dirs(ip, share, base, sub_dirs) dirs = [] usernames = [] begin read,write,type,files = eval_host(ip, share, base) # files or type could return nil due to various conditions return dirs if files.nil? files.each do |f| if f[0] != "." and f[0] != ".." usernames.push(f[0]) end end usernames.each do |username| sub_dirs.each do |sub_dir| dirs.push("#{base}\\#{username}\\#{sub_dir}") end end return dirs rescue return dirs end end def profile_options(ip, share) old_dirs = ['My Documents','Desktop'] new_dirs = ['Desktop','Documents','Downloads','Music','Pictures','Videos'] dirs = get_user_dirs(ip, share, "Documents and Settings", old_dirs) if dirs.blank? dirs = get_user_dirs(ip, share, "Users", new_dirs) end return dirs end def get_files_info(ip, rport, shares, info) read = false write = false # Creating a separate file for each IP address's results. detailed_tbl = Rex::Text::Table.new( 'Header' => "Spidered results for #{ip}.", 'Indent' => 1, 'Columns' => [ 'IP Address', 'Type', 'Share', 'Path', 'Name', 'Created', 'Accessed', 'Written', 'Changed', 'Size' ] ) logdata = "" list = shares.collect {|e| e[0]} list.each do |x| x = x.strip if x == "ADMIN$" or x == "IPC$" next end if not datastore['ShowFiles'] print_status("Spidering #{x}.") end subdirs = [""] if x.strip() == "C$" and datastore['SpiderProfiles'] subdirs = profile_options(ip, x) end while subdirs.length > 0 depth = subdirs[0].count("\\") if datastore['SpiderProfiles'] and x == "C$" if depth-2 > datastore['MaxDepth'] subdirs.shift next end else if depth > datastore['MaxDepth'] subdirs.shift next end end read,write,type,files = eval_host(ip, x, subdirs[0]) if files and (read or write) if files.length < 3 subdirs.shift next end header = "" if simple.client.default_domain and simple.client.default_name header << " \\\\#{simple.client.default_domain}" end header << "\\#{x.sub("C$","C$\\")}" if simple.client.default_name header << subdirs[0] pretty_tbl = Rex::Text::Table.new( 'Header' => header, 'Indent' => 1, 'Columns' => [ 'Type', 'Name', 'Created', 'Accessed', 'Written', 'Changed', 'Size' ] ) f_types = { 1 => 'RO', 2 => 'HIDDEN', 4 => 'SYS', 8 => 'VOL', 16 => 'DIR', 32 => 'ARC', 64 => 'DEV', 128 => 'FILE' } files.each do |file| if file[0] and file[0] != '.' and file[0] != '..' info = file[1]['info'] fa = f_types[file[1]['attr']] # Item type fname = file[0] # Filename tcr = to_unix_time(info[3], info[2]) # Created tac = to_unix_time(info[5], info[4]) # Accessed twr = to_unix_time(info[7], info[6]) # Written tch = to_unix_time(info[9], info[8]) # Changed sz = info[12] + info[13] # Size # Filename is too long for the UI table, cut it. fname = "#{fname[0, 35]}..." if fname.length > 35 # Add subdirectories to list to use if SpiderShare is enabled. if fa == "DIR" or (fa == nil and sz == 0) subdirs.push(subdirs[0] + "\\" + fname) end pretty_tbl << [fa || 'Unknown', fname, tcr, tac, twr, tch, sz] detailed_tbl << ["#{ip}", fa || 'Unknown', "#{x}", subdirs[0] + "\\", fname, tcr, tac, twr, tch, sz] logdata << "#{ip}\\#{x.sub("C$","C$\\")}#{subdirs[0]}\\#{fname}\n" end end print_good(pretty_tbl.to_s) if datastore['ShowFiles'] end subdirs.shift end print_status("Spider #{x} complete.") unless datastore['ShowFiles'] end unless detailed_tbl.rows.empty? if datastore['LogSpider'] == '1' p = store_loot('smb.enumshares', 'text/csv', ip, detailed_tbl.to_csv) print_good("info saved in: #{p.to_s}") elsif datastore['LogSpider'] == '2' p = store_loot('smb.enumshares', 'text/plain', ip, detailed_tbl) print_good("info saved in: #{p.to_s}") elsif datastore['LogSpider'] == '3' p = store_loot('smb.enumshares', 'text/plain', ip, logdata) print_good("info saved in: #{p.to_s}") end end end def rport @rport || datastore['RPORT'] end # Overrides the one in smb.rb def smb_direct @smb_redirect || datastore['SMBDirect'] end def run_host(ip) @rport = datastore['RPORT'] @smb_redirect = datastore['SMBDirect'] @srvsvc = datastore['USE_SRVSVC_ONLY'] shares = [] [[139, false], [445, true]].each do |info| @rport = info[0] @smb_redirect = info[1] begin connect smb_login if @srvsvc shares = srvsvc_netshareenum(ip) else shares = lanman_netshareenum(ip, rport, info) end os_info = get_os_info(ip, rport) print_status(os_info) if os_info if shares.empty? print_status("No shares collected") else shares_info = shares.map{|x| "#{x[0]} - (#{x[1]}) #{x[2]}" }.join(", ") shares_info.split(", ").each { |share| print_good share } report_note( :host => ip, :proto => 'tcp', :port => rport, :type => 'smb.shares', :data => { :shares => shares }, :update => :unique_data ) if datastore['SpiderShares'] get_files_info(ip, rport, shares, info) end break if rport == 139 end rescue ::Interrupt raise $! rescue ::Rex::Proto::SMB::Exceptions::LoginError, ::Rex::Proto::SMB::Exceptions::ErrorCode => e print_error(e.message) return if e.message =~ /STATUS_ACCESS_DENIED/ rescue Errno::ECONNRESET, ::Rex::Proto::SMB::Exceptions::InvalidType, ::Rex::Proto::SMB::Exceptions::ReadPacket, ::Rex::Proto::SMB::Exceptions::InvalidCommand, ::Rex::Proto::SMB::Exceptions::InvalidWordCount, ::Rex::Proto::SMB::Exceptions::NoReply => e vprint_error(e.message) next if not shares.empty? and rport == 139 # no results, try again rescue Errno::ENOPROTOOPT print_status("Wait 5 seconds before retrying...") select(nil, nil, nil, 5) retry rescue ::Exception => e next if e.to_s =~ /execution expired/ next if not shares.empty? and rport == 139 vprint_error("Error: '#{ip}' '#{e.class}' '#{e.to_s}'") ensure disconnect end # if we already got results, not need to try on another port return unless shares.empty? end end end
33.037109
145
0.567957
61f14f28bb0cd31301171d7a0454a624ba343c7d
39,493
#: * `audit` [`--strict`] [`--fix`] [`--online`] [`--new-formula`] [`--display-cop-names`] [`--display-filename`] [`--only=`<method>|`--except=`<method>] [`--only-cops=`<cops>|`--except-cops=`<cops>] [<formulae>]: #: Check <formulae> for Homebrew coding style violations. This should be run #: before submitting a new formula. Will exit with a non-zero status if any errors #: are found, which can be useful for implementing pre-commit hooks. #: #: If no <formulae> are provided, all of them are checked. #: #: If `--strict` is passed, additional checks are run, including RuboCop #: style checks. #: #: If `--fix` is passed, style violations will be #: automatically fixed using RuboCop's auto-correct feature. #: #: If `--online` is passed, additional slower checks that require a network #: connection are run. #: #: If `--new-formula` is passed, various additional checks are run that check #: if a new formula is eligible for Homebrew. This should be used when creating #: new formulae and implies `--strict` and `--online`. #: #: If `--display-cop-names` is passed, the RuboCop cop name for each violation #: is included in the output. #: #: If `--display-filename` is passed, every line of output is prefixed with the #: name of the file or formula being audited, to make the output easy to grep. #: #: Specifying `--only=`<method> will run only the methods named `audit_`<method>, #: while `--except=`<method> will skip the methods named `audit_`<method>. #: For either option <method> should be a comma-separated list. #: #: Specifying `--only-cops=`<cops> will check for violations of only the listed #: RuboCop <cops>, while `--except-cops=`<cops> will skip checking the listed #: <cops>. For either option <cops> should be a comma-separated list of cop names. # Undocumented options: # `-D` activates debugging and profiling of the audit methods (not the same as `--debug`) require "formula" require "formula_versions" require "utils/curl" require "extend/ENV" require "formula_cellar_checks" require "cmd/search" require "style" require "date" require "missing_formula" require "digest" require "cli_parser" module Homebrew module_function def audit_args Homebrew::CLI::Parser.new do usage_banner <<~EOS `audit` [<options>] <formulae> Check <formulae> for Homebrew coding style violations. This should be run before submitting a new formula. Will exit with a non-zero status if any errors are found, which can be useful for implementing pre-commit hooks. If no <formulae> are provided, all of them are checked. EOS switch "--strict", description: "Run additional style checks, including RuboCop style checks." switch "--online", description: "Run additional slower style checks that require a network connection." switch "--new-formula", description: "Run various additional style checks to determine if a new formula is eligible "\ "for Homebrew. This should be used when creating new formula and implies "\ "`--strict` and `--online`." switch "--fix", description: "Fix style violations automatically using RuboCop's auto-correct feature." switch "--display-cop-names", description: "Include the RuboCop cop name for each violation in the output." switch "--display-filename", description: "Prefix every line of output with name of the file or formula being audited, to "\ "make output easy to grep." switch "-D", "--audit-debug", description: "Enable debugging and profiling of audit methods." comma_array "--only", description: "Specify a comma-separated <method> list to only run the methods named "\ "`audit_`<method>." comma_array "--except", description: "Specify a comma-separated <method> list to skip running the methods named "\ "`audit_`<method>." comma_array "--only-cops", description: "Specify a comma-separated <cops> list to check for violations of only the listed "\ "RuboCop cops." comma_array "--except-cops", description: "Specify a comma-separated <cops> list to skip checking for violations of the listed "\ "RuboCop cops." switch :verbose switch :debug conflicts "--only", "--except" conflicts "--only-cops", "--except-cops" end end def audit audit_args.parse Homebrew.auditing = true inject_dump_stats!(FormulaAuditor, /^audit_/) if args.audit_debug? formula_count = 0 problem_count = 0 corrected_problem_count = 0 new_formula_problem_count = 0 new_formula = args.new_formula? strict = new_formula || args.strict? online = new_formula || args.online? ENV.activate_extensions! ENV.setup_build_environment if ARGV.named.empty? ff = Formula files = Tap.map(&:formula_dir) else ff = ARGV.resolved_formulae files = ARGV.resolved_formulae.map(&:path) end only_cops = args.only_cops except_cops = args.except_cops if only_cops && except_cops odie "--only-cops and --except-cops cannot be used simultaneously!" elsif (only_cops || except_cops) && (strict || args.only) odie "--only-cops/--except-cops and --strict/--only cannot be used simultaneously!" end options = { fix: args.fix?, realpath: true } if only_cops options[:only_cops] = only_cops elsif args.new_formula? nil elsif strict options[:except_cops] = [:NewFormulaAudit] elsif except_cops options[:except_cops] = except_cops elsif !strict options[:only_cops] = [:FormulaAudit] end options[:display_cop_names] = args.display_cop_names? # Check style in a single batch run up front for performance style_results = Style.check_style_json(files, options) new_formula_problem_lines = [] ff.sort.each do |f| only = only_cops ? ["style"] : args.only options = { new_formula: new_formula, strict: strict, online: online, only: only, except: args.except } options[:style_offenses] = style_results.file_offenses(f.path) fa = FormulaAuditor.new(f, options) fa.audit next if fa.problems.empty? && fa.new_formula_problems.empty? fa.problems formula_count += 1 problem_count += fa.problems.size problem_lines = format_problem_lines(fa.problems) corrected_problem_count = options[:style_offenses].count(&:corrected?) new_formula_problem_lines = format_problem_lines(fa.new_formula_problems) if args.display_filename? puts problem_lines.map { |s| "#{f.path}: #{s}" } else puts "#{f.full_name}:", problem_lines.map { |s| " #{s}" } end end created_pr_comment = false if new_formula && !new_formula_problem_lines.empty? begin if GitHub.create_issue_comment(new_formula_problem_lines.join("\n")) created_pr_comment = true end rescue *GitHub.api_errors => e opoo "Unable to create issue comment: #{e.message}" end end unless created_pr_comment new_formula_problem_count += new_formula_problem_lines.size puts new_formula_problem_lines.map { |s| " #{s}" } end total_problems_count = problem_count + new_formula_problem_count problem_plural = "#{total_problems_count} #{"problem".pluralize(total_problems_count)}" formula_plural = "#{formula_count} #{"formula".pluralize(formula_count)}" corrected_problem_plural = "#{corrected_problem_count} #{"problem".pluralize(corrected_problem_count)}" errors_summary = "#{problem_plural} in #{formula_plural} detected" if corrected_problem_count.positive? errors_summary += ", #{corrected_problem_plural} corrected" end if problem_count.positive? || (new_formula_problem_count.positive? && !created_pr_comment) ofail errors_summary end end def format_problem_lines(problems) problems.uniq.map { |p| "* #{p.chomp.gsub("\n", "\n ")}" } end class FormulaText def initialize(path) @text = path.open("rb", &:read) @lines = @text.lines.to_a end def without_patch @text.split("\n__END__").first end def data? /^[^#]*\bDATA\b/ =~ @text end def end? /^__END__$/ =~ @text end def trailing_newline? /\Z\n/ =~ @text end def =~(other) other =~ @text end def include?(s) @text.include? s end def line_number(regex, skip = 0) index = @lines.drop(skip).index { |line| line =~ regex } index ? index + 1 : nil end def reverse_line_number(regex) index = @lines.reverse.index { |line| line =~ regex } index ? @lines.count - index : nil end end class FormulaAuditor include FormulaCellarChecks attr_reader :formula, :text, :problems, :new_formula_problems def initialize(formula, options = {}) @formula = formula @versioned_formula = formula.versioned_formula? @new_formula_inclusive = options[:new_formula] @new_formula = options[:new_formula] && !@versioned_formula @strict = options[:strict] @online = options[:online] @display_cop_names = options[:display_cop_names] @only = options[:only] @except = options[:except] # Accept precomputed style offense results, for efficiency @style_offenses = options[:style_offenses] # Allow the formula tap to be set as `core`, for testing purposes @core_tap = formula.tap&.core_tap? || options[:core_tap] @problems = [] @new_formula_problems = [] @text = FormulaText.new(formula.path) @specs = %w[stable devel head].map { |s| formula.send(s) }.compact end def audit_style return unless @style_offenses @style_offenses.each do |offense| if offense.cop_name.start_with?("NewFormulaAudit") next if @versioned_formula new_formula_problem offense.to_s(display_cop_name: @display_cop_names) next end problem offense.to_s(display_cop_name: @display_cop_names) end end def audit_file # Under normal circumstances (umask 0022), we expect a file mode of 644. If # the user's umask is more restrictive, respect that by masking out the # corresponding bits. (The also included 0100000 flag means regular file.) wanted_mode = 0100644 & ~File.umask actual_mode = formula.path.stat.mode unless actual_mode == wanted_mode problem format("Incorrect file permissions (%03<actual>o): chmod %03<wanted>o %{path}", actual: actual_mode & 0777, wanted: wanted_mode & 0777, path: formula.path) end problem "'DATA' was found, but no '__END__'" if text.data? && !text.end? if text.end? && !text.data? problem "'__END__' was found, but 'DATA' is not used" end if text =~ /inreplace [^\n]* do [^\n]*\n[^\n]*\.gsub![^\n]*\n\ *end/m problem "'inreplace ... do' was used for a single substitution (use the non-block form instead)." end problem "File should end with a newline" unless text.trailing_newline? if formula.core_formula? && @versioned_formula unversioned_formula = begin # build this ourselves as we want e.g. homebrew/core to be present full_name = if formula.tap "#{formula.tap}/#{formula.name}" else formula.name end Formulary.factory(full_name.gsub(/@.*$/, "")).path rescue FormulaUnavailableError, TapFormulaAmbiguityError, TapFormulaWithOldnameAmbiguityError Pathname.new formula.path.to_s.gsub(/@.*\.rb$/, ".rb") end unless unversioned_formula.exist? unversioned_name = unversioned_formula.basename(".rb") problem "#{formula} is versioned but no #{unversioned_name} formula exists" end elsif ARGV.build_stable? && formula.stable? && !(versioned_formulae = formula.versioned_formulae).empty? versioned_aliases = formula.aliases.grep(/.@\d/) _, last_alias_version = versioned_formulae.map(&:name).last.split("@") major, minor, = formula.version.to_s.split(".") alias_name_major = "#{formula.name}@#{major}" alias_name_major_minor = "#{alias_name_major}.#{minor}" alias_name = if last_alias_version.split(".").length == 1 alias_name_major else alias_name_major_minor end valid_alias_names = [alias_name_major, alias_name_major_minor] unless @core_tap versioned_aliases.map! { |a| "#{formula.tap}/#{a}" } valid_alias_names.map! { |a| "#{formula.tap}/#{a}" } end valid_versioned_aliases = versioned_aliases & valid_alias_names invalid_versioned_aliases = versioned_aliases - valid_alias_names if valid_versioned_aliases.empty? if formula.tap problem <<~EOS Formula has other versions so create a versioned alias: cd #{formula.tap.alias_dir} ln -s #{formula.path.to_s.gsub(formula.tap.path, "..")} #{alias_name} EOS else problem "Formula has other versions so create an alias named #{alias_name}." end end unless invalid_versioned_aliases.empty? problem <<~EOS Formula has invalid versioned aliases: #{invalid_versioned_aliases.join("\n ")} EOS end end end def self.aliases # core aliases + tap alias names + tap alias full name @aliases ||= Formula.aliases + Formula.tap_aliases end def audit_formula_name return unless @strict return unless @core_tap name = formula.name if MissingFormula.blacklisted_reason(name) problem "'#{name}' is blacklisted." end if Formula.aliases.include? name problem "Formula name conflicts with existing aliases." return end if oldname = CoreTap.instance.formula_renames[name] problem "'#{name}' is reserved as the old name of #{oldname}" return end return if formula.core_formula? return unless Formula.core_names.include?(name) problem "Formula name conflicts with existing core formula." end def audit_deps @specs.each do |spec| # Check for things we don't like to depend on. # We allow non-Homebrew installs whenever possible. spec.deps.each do |dep| begin dep_f = dep.to_formula rescue TapFormulaUnavailableError # Don't complain about missing cross-tap dependencies next rescue FormulaUnavailableError problem "Can't find dependency #{dep.name.inspect}." next rescue TapFormulaAmbiguityError problem "Ambiguous dependency #{dep.name.inspect}." next rescue TapFormulaWithOldnameAmbiguityError problem "Ambiguous oldname dependency #{dep.name.inspect}." next end if dep_f.oldname && dep.name.split("/").last == dep_f.oldname problem "Dependency '#{dep.name}' was renamed; use new name '#{dep_f.name}'." end if self.class.aliases.include?(dep.name) && (dep_f.core_formula? || !dep_f.versioned_formula?) problem "Dependency '#{dep.name}' is an alias; use the canonical name '#{dep.to_formula.full_name}'." end if @new_formula && dep_f.keg_only_reason && !["openssl", "apr", "apr-util"].include?(dep.name) && !["openblas"].include?(dep.name) && dep_f.keg_only_reason.reason == :provided_by_macos new_formula_problem( "Dependency '#{dep.name}' may be unnecessary as it is provided " \ "by macOS; try to build this formula without it.", ) end dep.options.each do |opt| next if @core_tap next if dep_f.option_defined?(opt) next if dep_f.requirements.find do |r| if r.recommended? opt.name == "with-#{r.name}" elsif r.optional? opt.name == "without-#{r.name}" end end problem "Dependency #{dep} does not define option #{opt.name.inspect}" end if dep.name == "git" problem "Don't use git as a dependency (it's always available)" end if dep.tags.include?(:run) problem "Dependency '#{dep.name}' is marked as :run. Remove :run; it is a no-op." end next unless @core_tap if dep.tags.include?(:recommended) || dep.tags.include?(:optional) problem "Formulae should not have optional or recommended dependencies" end end next unless @core_tap if spec.requirements.map(&:recommended?).any? || spec.requirements.map(&:optional?).any? problem "Formulae should not have optional or recommended requirements" end end end def audit_conflicts formula.conflicts.each do |c| begin Formulary.factory(c.name) rescue TapFormulaUnavailableError # Don't complain about missing cross-tap conflicts. next rescue FormulaUnavailableError problem "Can't find conflicting formula #{c.name.inspect}." rescue TapFormulaAmbiguityError, TapFormulaWithOldnameAmbiguityError problem "Ambiguous conflicting formula #{c.name.inspect}." end end end def audit_keg_only_style return unless formula.keg_only? whitelist = %w[ Apple macOS OS Homebrew Xcode GPG GNOME BSD Firefox ].freeze reason = formula.keg_only_reason.to_s # Formulae names can legitimately be uppercase/lowercase/both. name = Regexp.new(formula.name, Regexp::IGNORECASE) reason.sub!(name, "") first_word = reason.split.first if reason =~ /\A[A-Z]/ && !reason.start_with?(*whitelist) problem <<~EOS '#{first_word}' from the keg_only reason should be '#{first_word.downcase}'. EOS end return unless reason.end_with?(".") problem "keg_only reason should not end with a period." end def audit_postgresql return unless formula.name == "postgresql" return unless @core_tap major_version = formula.version .to_s .split(".") .first .to_i previous_major_version = major_version - 1 previous_formula_name = "postgresql@#{previous_major_version}" begin Formula[previous_formula_name] rescue FormulaUnavailableError problem "Versioned #{previous_formula_name} must be created for " \ "`brew-postgresql-upgrade-database` and `pg_upgrade` to work." end end def audit_versioned_keg_only return unless @versioned_formula return unless @core_tap if formula.keg_only? return if formula.keg_only_reason.reason == :versioned_formula if formula.name.start_with?("openssl", "libressl") && formula.keg_only_reason.reason == :provided_by_macos return end end keg_only_whitelist = %w[ autoconf@2.13 bash-completion@2 gnupg@1.4 lua@5.1 python@2 ].freeze return if keg_only_whitelist.include?(formula.name) || formula.name.start_with?("gcc@") problem "Versioned formulae should use `keg_only :versioned_formula`" end def audit_homepage homepage = formula.homepage return if homepage.nil? || homepage.empty? return unless @online return unless DevelopmentTools.curl_handles_most_https_certificates? if http_content_problem = curl_check_http_content(homepage, user_agents: [:browser, :default], check_content: true, strict: @strict) problem http_content_problem end end def audit_bottle_spec # special case: new versioned formulae should be audited return unless @new_formula_inclusive return unless @core_tap return if formula.bottle_disabled? return unless formula.bottle_defined? new_formula_problem "New formulae should not have a `bottle do` block" end def audit_bottle_disabled return unless formula.bottle_disabled? return if formula.bottle_unneeded? unless formula.bottle_disable_reason.valid? problem "Unrecognized bottle modifier" end return unless @core_tap problem "Formulae should not use `bottle :disabled`" end def audit_github_repository return unless @core_tap return unless @online return unless @new_formula regex = %r{https?://github\.com/([^/]+)/([^/]+)/?.*} _, user, repo = *regex.match(formula.stable.url) if formula.stable _, user, repo = *regex.match(formula.homepage) unless user return if !user || !repo repo.gsub!(/.git$/, "") begin metadata = GitHub.repository(user, repo) rescue GitHub::HTTPNotFoundError return end return if metadata.nil? new_formula_problem "GitHub fork (not canonical repository)" if metadata["fork"] if (metadata["forks_count"] < 30) && (metadata["subscribers_count"] < 30) && (metadata["stargazers_count"] < 75) new_formula_problem "GitHub repository not notable enough (<30 forks, <30 watchers and <75 stars)" end return if Date.parse(metadata["created_at"]) <= (Date.today - 30) new_formula_problem "GitHub repository too new (<30 days old)" end def audit_specs problem "Head-only (no stable download)" if head_only?(formula) problem "Devel-only (no stable download)" if devel_only?(formula) %w[Stable Devel HEAD].each do |name| spec_name = name.downcase.to_sym next unless spec = formula.send(spec_name) ra = ResourceAuditor.new(spec, spec_name, online: @online, strict: @strict).audit problems.concat ra.problems.map { |problem| "#{name}: #{problem}" } spec.resources.each_value do |resource| ra = ResourceAuditor.new(resource, spec_name, online: @online, strict: @strict).audit problems.concat ra.problems.map { |problem| "#{name} resource #{resource.name.inspect}: #{problem}" } end next if spec.patches.empty? next unless @new_formula new_formula_problem( "Formulae should not require patches to build. " \ "Patches should be submitted and accepted upstream first.", ) end %w[Stable Devel].each do |name| next unless spec = formula.send(name.downcase) version = spec.version if version.to_s !~ /\d/ problem "#{name}: version (#{version}) is set to a string without a digit" end if version.to_s.start_with?("HEAD") problem "#{name}: non-HEAD version name (#{version}) should not begin with HEAD" end end if formula.stable && formula.devel if formula.devel.version < formula.stable.version problem "devel version #{formula.devel.version} is older than stable version #{formula.stable.version}" elsif formula.devel.version == formula.stable.version problem "stable and devel versions are identical" end end return unless @core_tap problem "Formulae should not have a `devel` spec" if formula.devel if formula.head head_spec_message = "Formulae should not have a `HEAD` spec" if @new_formula new_formula_problem head_spec_message elsif @versioned_formula versioned_head_spec = %w[ bash-completion@2 imagemagick@6 python@2 ] problem head_spec_message unless versioned_head_spec.include?(formula.name) end end throttled = %w[ aws-sdk-cpp 10 awscli 10 quicktype 10 vim 50 ] throttled.each_slice(2).to_a.map do |a, b| next if formula.stable.nil? version = formula.stable.version.to_s.split(".").last.to_i if a == formula.name && version.modulo(b.to_i).nonzero? problem "should only be updated every #{b} releases on multiples of #{b}" end end unstable_whitelist = %w[ aalib 1.4rc5 automysqlbackup 3.0-rc6 aview 1.3.0rc1 distcc 3.2rc1 elm-format 0.6.0-alpha ftgl 2.1.3-rc5 hidapi 0.8.0-rc1 libcaca 0.99b19 nethack4 4.3.0-beta2 premake 4.4-beta5 pwnat 0.3-beta recode 3.7-beta2 speexdsp 1.2rc3 sqoop 1.4.6 tcptraceroute 1.5beta7 testssl 2.8rc3 tiny-fugue 5.0b8 vbindiff 3.0_beta4 ].each_slice(2).to_a.map do |formula, version| [formula, version.sub(/\d+$/, "")] end gnome_devel_whitelist = %w[ gtk-doc 1.25 libart 2.3.21 pygtkglext 1.1.0 libepoxy 1.5.0 gtk-mac-integration 2.1.2 ].each_slice(2).to_a.map do |formula, version| [formula, version.split(".")[0..1].join(".")] end stable = formula.stable case stable&.url when /[\d\._-](alpha|beta|rc\d)/ matched = Regexp.last_match(1) version_prefix = stable.version.to_s.sub(/\d+$/, "") return if unstable_whitelist.include?([formula.name, version_prefix]) problem "Stable version URLs should not contain #{matched}" when %r{download\.gnome\.org/sources}, %r{ftp\.gnome\.org/pub/GNOME/sources}i version_prefix = stable.version.to_s.split(".")[0..1].join(".") return if gnome_devel_whitelist.include?([formula.name, version_prefix]) version = Version.parse(stable.url) if version >= Version.create("1.0") _, minor_version, = version.to_s.split(".", 3).map(&:to_i) if minor_version.odd? problem "#{stable.version} is a development release" end end end end def audit_revision_and_version_scheme return unless formula.tap # skip formula not from core or any taps return unless formula.tap.git? # git log is required return if @new_formula fv = FormulaVersions.new(formula) previous_version_and_checksum = fv.previous_version_and_checksum("origin/master") [:stable, :devel].each do |spec_sym| next unless spec = formula.send(spec_sym) next unless previous_version_and_checksum[spec_sym][:version] == spec.version next if previous_version_and_checksum[spec_sym][:checksum] == spec.checksum problem( "#{spec_sym}: sha256 changed without the version also changing; " \ "please create an issue upstream to rule out malicious " \ "circumstances and to find out why the file changed.", ) end attributes = [:revision, :version_scheme] attributes_map = fv.version_attributes_map(attributes, "origin/master") current_version_scheme = formula.version_scheme [:stable, :devel].each do |spec| spec_version_scheme_map = attributes_map[:version_scheme][spec] next if spec_version_scheme_map.empty? version_schemes = spec_version_scheme_map.values.flatten max_version_scheme = version_schemes.max max_version = spec_version_scheme_map.select do |_, version_scheme| version_scheme.first == max_version_scheme end.keys.max if max_version_scheme && current_version_scheme < max_version_scheme problem "version_scheme should not decrease (from #{max_version_scheme} to #{current_version_scheme})" end if max_version_scheme && current_version_scheme >= max_version_scheme && current_version_scheme > 1 && !version_schemes.include?(current_version_scheme - 1) problem "version_schemes should only increment by 1" end formula_spec = formula.send(spec) next unless formula_spec spec_version = formula_spec.version next unless max_version next if spec_version >= max_version above_max_version_scheme = current_version_scheme > max_version_scheme map_includes_version = spec_version_scheme_map.key?(spec_version) next if !current_version_scheme.zero? && (above_max_version_scheme || map_includes_version) problem "#{spec} version should not decrease (from #{max_version} to #{spec_version})" end current_revision = formula.revision revision_map = attributes_map[:revision][:stable] if formula.stable && !revision_map.empty? stable_revisions = revision_map[formula.stable.version] stable_revisions ||= [] max_revision = stable_revisions.max || 0 if current_revision < max_revision problem "revision should not decrease (from #{max_revision} to #{current_revision})" end stable_revisions -= [formula.revision] if !current_revision.zero? && stable_revisions.empty? && revision_map.keys.length > 1 problem "'revision #{formula.revision}' should be removed" elsif current_revision > 1 && current_revision != max_revision && !stable_revisions.include?(current_revision - 1) problem "revisions should only increment by 1" end elsif !current_revision.zero? # head/devel-only formula problem "'revision #{current_revision}' should be removed" end end def audit_text bin_names = Set.new bin_names << formula.name bin_names += formula.aliases [formula.bin, formula.sbin].each do |dir| next unless dir.exist? bin_names += dir.children.map(&:basename).map(&:to_s) end bin_names.each do |name| ["system", "shell_output", "pipe_output"].each do |cmd| if text =~ /test do.*#{cmd}[\(\s]+['"]#{Regexp.escape(name)}[\s'"]/m problem %Q(fully scope test #{cmd} calls e.g. #{cmd} "\#{bin}/#{name}") end end end end def audit_lines text.without_patch.split("\n").each_with_index do |line, lineno| line_problems(line, lineno + 1) end end def line_problems(line, _lineno) # Check for string interpolation of single values. if line =~ /(system|inreplace|gsub!|change_make_var!).*[ ,]"#\{([\w.]+)\}"/ problem "Don't need to interpolate \"#{Regexp.last_match(2)}\" with #{Regexp.last_match(1)}" end # Check for string concatenation; prefer interpolation if line =~ /(#\{\w+\s*\+\s*['"][^}]+\})/ problem "Try not to concatenate paths in string interpolation:\n #{Regexp.last_match(1)}" end # Prefer formula path shortcuts in Pathname+ if line =~ %r{\(\s*(prefix\s*\+\s*(['"])(bin|include|libexec|lib|sbin|share|Frameworks)[/'"])} problem( "\"(#{Regexp.last_match(1)}...#{Regexp.last_match(2)})\" should" \ " be \"(#{Regexp.last_match(3).downcase}+...)\"", ) end problem "Use separate make calls" if line.include?("make && make") if line =~ /JAVA_HOME/i && !formula.requirements.map(&:class).include?(JavaRequirement) problem "Use `depends_on :java` to set JAVA_HOME" end return unless @strict if line.include?("env :userpaths") problem "`env :userpaths` in formulae is deprecated" end if line =~ /system ((["'])[^"' ]*(?:\s[^"' ]*)+\2)/ bad_system = Regexp.last_match(1) unless %w[| < > & ; *].any? { |c| bad_system.include? c } good_system = bad_system.gsub(" ", "\", \"") problem "Use `system #{good_system}` instead of `system #{bad_system}` " end end problem "`#{Regexp.last_match(1)}` is now unnecessary" if line =~ /(require ["']formula["'])/ if line =~ %r{#\{share\}/#{Regexp.escape(formula.name)}[/'"]} problem "Use \#{pkgshare} instead of \#{share}/#{formula.name}" end if !@core_tap && line =~ /depends_on .+ if build\.with(out)?\?\(?["']\w+["']\)?/ problem "`Use :optional` or `:recommended` instead of `#{Regexp.last_match(0)}`" end return unless line =~ %r{share(\s*[/+]\s*)(['"])#{Regexp.escape(formula.name)}(?:\2|/)} problem "Use pkgshare instead of (share#{Regexp.last_match(1)}\"#{formula.name}\")" return unless @core_tap return unless line.include?("env :std") problem "`env :std` in `core` formulae is deprecated" end def audit_reverse_migration # Only enforce for new formula being re-added to core return unless @strict return unless @core_tap return unless formula.tap.tap_migrations.key?(formula.name) problem <<~EOS #{formula.name} seems to be listed in tap_migrations.json! Please remove #{formula.name} from present tap & tap_migrations.json before submitting it to Homebrew/homebrew-#{formula.tap.repo}. EOS end def audit_prefix_has_contents return unless formula.prefix.directory? return unless Keg.new(formula.prefix).empty_installation? problem <<~EOS The installation seems to be empty. Please ensure the prefix is set correctly and expected files are installed. The prefix configure/make argument may be case-sensitive. EOS end def audit_url_is_not_binary return unless @core_tap urls = @specs.map(&:url) urls.each do |url| if url =~ /darwin/i && (url =~ /x86_64/i || url =~ /amd64/i) problem "#{url} looks like a binary package, not a source archive. The `core` tap is source-only." end end end def quote_dep(dep) dep.is_a?(Symbol) ? dep.inspect : "'#{dep}'" end def problem_if_output(output) problem(output) if output end def audit only_audits = @only except_audits = @except if only_audits && except_audits odie "--only and --except cannot be used simultaneously!" end methods.map(&:to_s).grep(/^audit_/).each do |audit_method_name| name = audit_method_name.gsub(/^audit_/, "") if only_audits next unless only_audits.include?(name) elsif except_audits next if except_audits.include?(name) end send(audit_method_name) end end private def problem(p) @problems << p end def new_formula_problem(p) @new_formula_problems << p end def head_only?(formula) formula.head && formula.devel.nil? && formula.stable.nil? end def devel_only?(formula) formula.devel && formula.stable.nil? end end class ResourceAuditor attr_reader :name, :version, :checksum, :url, :mirrors, :using, :specs, :owner attr_reader :spec_name, :problems def initialize(resource, spec_name, options = {}) @name = resource.name @version = resource.version @checksum = resource.checksum @url = resource.url @mirrors = resource.mirrors @using = resource.using @specs = resource.specs @owner = resource.owner @spec_name = spec_name @online = options[:online] @strict = options[:strict] @problems = [] end def audit audit_version audit_download_strategy audit_urls self end def audit_version if version.nil? problem "missing version" elsif version.blank? problem "version is set to an empty string" elsif !version.detected_from_url? version_text = version version_url = Version.detect(url, specs) if version_url.to_s == version_text.to_s && version.instance_of?(Version) problem "version #{version_text} is redundant with version scanned from URL" end end if version.to_s.start_with?("v") problem "version #{version} should not have a leading 'v'" end return unless version.to_s =~ /_\d+$/ problem "version #{version} should not end with an underline and a number" end def audit_download_strategy if url =~ %r{^(cvs|bzr|hg|fossil)://} || url =~ %r{^(svn)\+http://} problem "Use of the #{$&} scheme is deprecated, pass `:using => :#{Regexp.last_match(1)}` instead" end url_strategy = DownloadStrategyDetector.detect(url) if using == :git || url_strategy == GitDownloadStrategy if specs[:tag] && !specs[:revision] problem "Git should specify :revision when a :tag is specified." end end return unless using if using == :cvs mod = specs[:module] problem "Redundant :module value in URL" if mod == name if url =~ %r{:[^/]+$} mod = url.split(":").last if mod == name problem "Redundant CVS module appended to URL" else problem "Specify CVS module as `:module => \"#{mod}\"` instead of appending it to the URL" end end end return unless url_strategy == DownloadStrategyDetector.detect("", using) problem "Redundant :using value in URL" end def self.curl_openssl_and_deps @curl_openssl_and_deps ||= begin formulae_names = ["curl", "openssl"] formulae_names += formulae_names.flat_map do |f| Formula[f].recursive_dependencies.map(&:name) end formulae_names.uniq rescue FormulaUnavailableError [] end end def audit_urls return unless @online urls = [url] + mirrors urls.each do |url| next if !@strict && mirrors.include?(url) strategy = DownloadStrategyDetector.detect(url, using) if strategy <= CurlDownloadStrategy && !url.start_with?("file") # A `brew mirror`'ed URL is usually not yet reachable at the time of # pull request. next if url =~ %r{^https://dl.bintray.com/homebrew/mirror/} if http_content_problem = curl_check_http_content(url) problem http_content_problem end elsif strategy <= GitDownloadStrategy unless Utils.git_remote_exists? url problem "The URL #{url} is not a valid git URL" end elsif strategy <= SubversionDownloadStrategy next unless DevelopmentTools.subversion_handles_most_https_certificates? next unless Utils.svn_available? unless Utils.svn_remote_exists? url problem "The URL #{url} is not a valid svn URL" end end end end def problem(text) @problems << text end end end
34.04569
214
0.622794
1138102442805c8f574c025c141f0c4b3bdb92f6
4,186
class UsersController < ApplicationController load_and_authorize_resource before_action :set_user, only: [:show, :edit, :update, :destroy] skip_before_action :authenticate_user!, only: [:create] skip_before_filter :verify_authenticity_token, only: [:create] # GET /users def index if params[:role] if params[:chain_id] resource = Chain.find(params[:chain_id]) elsif params[:school_id] resource = School.find(params[:school_id]) elsif params[:room_id] resource = Room.find(params[:room_id]) elsif params[:child_id] resource = Child.find(params[:child_id]) elsif params[:user_id] resource = User.find(params[:user_id]) else resource = nil end @users = User.with_role(params[:role], resource).paginate(:page => params[:page], :per_page => params[:per_page]) else @users = User.paginate(:page => params[:page], :per_page => params[:per_page]) end @return_path = request.path respond_to do |format| format.html # index.html.erb format.xml { render_for_api :private, :xml => @users, :root => :users, :dasherize => false } format.json { render_for_api :private, :json => @users, :root => :users, :dasherize => false } end end # GET /users/1 def show @user = User.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render_for_api :private, :xml => @user, :dasherize => false } format.json { render_for_api :private, :json => @user, :dasherize => false } end end # GET /users/new def new @user = User.new @return_path = params[:ref] ? params[:ref] : users_path end # GET /users/1/edit def edit @user = User.find(params[:id]) @return_path = params[:ref] ? params[:ref] : user_path(@user) end # POST /users def create @user = User.find_by_email params[:user][:email] if @user redirect_to @user and return end @user = User.new(sign_up_params) if @user.save @return_path = params[:ref] ? params[:ref] : @user redirect_to @user else respond_to do |format| format.html { render action: 'new'} format.xml { render :status=>200, :xml =>{:errors => @user.errors.full_messages}} format.json { render :status=>200, :json=>{:errors => @user.errors.full_messages}} end end end # PATCH/PUT /users/1 def update role = Role.find params[:user][:roles] if params[:user][:roles] if role @user.remove_role @user.roles.first @user.add_role role, @user.publisher end if @user.update(user_params) @return_path = params[:ref] ? params[:ref] : @user respond_to do |format| format.html { redirect_to @return_path, notice: 'User was successfully updated.' } format.xml { render :status=>200, :xml =>{:id => @user.id}} format.json { render :status=>200, :json=>{:id => @user.id}} end else respond_to do |format| format.html { render action: 'edit'} format.xml { render :status=>200, :xml =>{:errors => @user.errors.full_messages}} format.json { render :status=>200, :json=>{:errors => @user.errors.full_messages}} end end end # DELETE /users/1 def destroy @user.destroy respond_to do |format| format.html { redirect_to :back, notice: 'User was successfully deleted.'} format.xml { render :status=>200, :xml =>{:id => @user.id, :deleted_at => DateTime.now}} format.json { render :status=>200, :json =>{:id => @user.id, :deleted_at => DateTime.now}} end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Only allow a trusted parameter "white list" through. def user_params params.require(:user).permit(:first_name, :avatar, :last_name, :display_name, :gender, :phone, :email, :publisher_id) end def sign_up_params params.require(:user).permit(:email, :password, :password_confirmation) end end
31.473684
123
0.617535
d51cbd519481ef4c21237ae5d50303e331e1929e
1,128
require 'rails_helper' describe AssessorsImport::Builder do let(:csv_path) { File.join(Rails.root, 'spec','support','file_samples','emails.csv') } subject { AssessorsImport::Builder.new(csv_path) } describe '#initialize' do it 'creates an instance with a valid filepath' do expect(subject).to be_a(AssessorsImport::Builder) end end describe '#process' do context 'with emails not used by accessors' do it 'creates new instances of Assessor based on the emails' do expect{ subject.process }.to change(Assessor, :count).by(subject.csv.count) end end context 'save failed' do it 'return not_saved' do allow_any_instance_of(Assessor).to receive(:save) {false} response = subject.process expect(response[:not_saved]).not_to be_empty end end context 'with emails already used by accessors' do before do subject.process end it 'does not create new Assessors for the giving emails' do subject.process expect{ subject.process }.not_to change(Assessor, :count) end end end end
28.2
88
0.671986
7944c6a7f705797ca1ad819805002ad2063c9f64
3,922
class EmsEvent module Automate extend ActiveSupport::Concern def manager_refresh(sync: false) refresh_targets = manager_refresh_targets return if refresh_targets.empty? EmsRefresh.queue_refresh(refresh_targets, nil, :create_task => sync) end def refresh(*targets, sync) return if ext_management_system&.supports_streaming_refresh? targets = targets.flatten return if targets.blank? refresh_targets = targets.collect { |t| get_target("#{t}_refresh_target") unless t.blank? }.compact.uniq return if refresh_targets.empty? EmsRefresh.queue_refresh(refresh_targets, nil, :create_task => sync) end def policy(target_str, policy_event, param = nil) _log.debug("ems: [#{ems_id}]") return if ems_id.nil? target, policy_event, policy_src = parse_policy_parameters(target_str, policy_event, param) return if target.nil? || policy_event.nil? || policy_src.nil? inputs = { policy_src.class.table_name.to_sym => policy_src, :ems_event => self } begin MiqEvent.raise_evm_event(target, policy_event, inputs) rescue => err _log.log_backtrace(err) end end def scan(*targets) _log.debug("Targets: [#{targets.inspect}]") missing_targets = targets.each_with_object([]) do |t, arr| target = get_target(t) if target.nil? # Queue that target for refresh instead _log.info("Unable to find target [#{t}]. Queueing for refresh.") arr << t else _log.info("Scanning [#{t}] [#{target.id}] name: [#{target.name}]") target.scan end end unless missing_targets.empty? _log.info("Performing refresh on the targets that were not found #{missing_targets.inspect}.") refresh(*missing_targets) end end def src_vm_as_template(flag) options = { :param => flag, :save => true } call("src_vm", "template=", options) end def change_event_target_state(target_str, param) options = { :param => param, :save => true } target = get_target(target_str) method = target.respond_to?(:raw_power_state=) ? "raw_power_state=" : "state=" call(target_str, method, options) end def src_vm_destroy_all_snapshots call("src_vm", "snapshots.destroy_all") end private def parse_policy_parameters(target_str, policy_event, param) target = get_target(target_str) unless target_str.blank? policy_event ||= event_type policy_src = parse_policy_source(target, param) if target _log.warn("Unable to find target [#{target_str}], skipping policy evaluation") if target.nil? _log.debug("Target: [#{target_str}], Policy event: [#{policy_event}]") _log.debug("Target object: [#{target.inspect}]") _log.debug("Policy source: [#{policy_src}]") [target, policy_event, policy_src] end def parse_policy_source(target, param) param.blank? ? ext_management_system : target.send(param) rescue => err _log.warn("Error: #{err.message}, getting policy source, skipping policy evaluation") end def call(target_str, method, options = {}) return if target_str.nil? || method.nil? target = target_original = get_target(target_str) if target.nil? _log.info("Unable to find target [#{target_str}]. Performing refresh.") return refresh(target_str) end methods = method.split('.').collect { |m| [m] } methods[-1] << options[:param] if options.key?(:param) _log.info("Calling method [#{target.class}, #{target.id}].#{methods}") methods.each { |m| target = target.send(*m) } target_original.send(:save!) if options[:save] == true end end end
30.640625
110
0.629271
bf79ad31db1a54500016e9ea2fac29e02281f261
1,701
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = Sidekiq.server? # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true config.active_job.queue_adapter = :sidekiq config.web_console.whiny_requests = false end
36.978261
85
0.775426
01f12d0341fafe33d5464da17046e0c85ed18f80
1,120
# encoding: UTF-8 require 'em-synchrony' require 'redis' require 'redis/connection/synchrony' require File.expand_path("./helper", File.dirname(__FILE__)) # # if running under Eventmachine + Synchrony (Ruby 1.9+), then # we can simulate the blocking API while performing the network # IO via the EM reactor. # EM.synchrony do r = Redis.new r.flushdb r.rpush "foo", "s1" r.rpush "foo", "s2" assert 2 == r.llen("foo") assert "s2" == r.rpop("foo") r.set("foo", "bar") assert "bar" == r.getset("foo", "baz") assert "baz" == r.get("foo") r.set("foo", "a") assert_equal 1, r.getbit("foo", 1) assert_equal 1, r.getbit("foo", 2) assert_equal 0, r.getbit("foo", 3) assert_equal 0, r.getbit("foo", 4) assert_equal 0, r.getbit("foo", 5) assert_equal 0, r.getbit("foo", 6) assert_equal 1, r.getbit("foo", 7) r.flushdb # command pipelining r.pipelined do r.lpush "foo", "s1" r.lpush "foo", "s2" end assert 2 == r.llen("foo") assert "s2" == r.lpop("foo") assert "s1" == r.lpop("foo") assert "OK" == r.client.call(:quit) assert "PONG" == r.ping EM.stop end
19.310345
63
0.622321
e82a167013e9f7d78adf35758bfe23268cf7e07e
2,138
require 'puppet/parameter' # This specialized {Puppet::Parameter} handles validation and munging of paths. # By default, a single path is accepted, and by calling {accept_arrays} it is possible to # allow an array of paths. # class Puppet::Parameter::Path < Puppet::Parameter # Specifies whether multiple paths are accepted or not. # @dsl type # def self.accept_arrays(bool = true) @accept_arrays = !!bool end def self.arrays? @accept_arrays end # Performs validation of the given paths. # If the concrete parameter defines a validation method, it may call this method to perform # path validation. # @raise [Puppet::Error] if this property is configured for single paths and an array is given # @raise [Puppet::Error] if a path is not an absolute path # @return [Array<String>] the given paths # def validate_path(paths) if paths.is_a?(Array) and ! self.class.arrays? then fail "#{name} only accepts a single path, not an array of paths" end fail("#{name} must be a fully qualified path") unless Array(paths).all? {|path| absolute_path?(path)} paths end # This is the default implementation of the `validate` method. # It will be overridden if the validate option is used when defining the parameter. # @return [void] # def unsafe_validate(paths) validate_path(paths) end # This is the default implementation of `munge`. # If the concrete parameter defines a `munge` method, this default implementation will be overridden. # This default implementation does not perform any munging, it just checks the one/many paths # constraints. A derived implementation can perform this check as: # `paths.is_a?(Array) and ! self.class.arrays?` and raise a {Puppet::Error}. # @param [String, Array<String>] one of multiple paths # @return [String, Array<String>] the given paths # @raise [Puppet::Error] if the given paths does not comply with the on/many paths rule. def unsafe_munge(paths) if paths.is_a?(Array) and ! self.class.arrays? then fail "#{name} only accepts a single path, not an array of paths" end paths end end
36.862069
105
0.715622
5dbecfe58665231d9b416a013d55fd5160a10202
748
module FHIR # fhir/referred_document_status.rb class ReferredDocumentStatus < PrimitiveCode include Mongoid::Document def as_json(*args) result = super result.delete('id') unless self.fhirId.nil? result['id'] = self.fhirId result.delete('fhirId') end result end def self.transform_json(json_hash, extension_hash, target = ReferredDocumentStatus.new) result = target unless extension_hash.nil? result['fhirId'] = extension_hash['id'] unless extension_hash['id'].nil? result['extension'] = extension_hash['extension'].map { |ext| Extension.transform_json(ext) } end result['value'] = json_hash result end end end
26.714286
101
0.640374
62734572d574d20d1cd95785c7f175ace2fcb32d
152
class CreateSongs < ActiveRecord::Migration[5.1] def change create_table :songs do |t| t.string :name t.timestamps end end end
15.2
48
0.651316
91ca4bd699bb7290ce5b83315cfcbb1ffe36a7d9
106
module Fluent class ConfigError < StandardError end class ConfigParseError < ConfigError end end
13.25
38
0.773585
4afef67894619ae6d18fccdcafccd3dc3453d9a3
9,357
# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril. # It is recommended to regenerate this file in the future when you upgrade to a # newer version of cucumber-rails. Consider adding your own code to a new file # instead of editing this one. Cucumber will automatically load all features/**/*.rb # files. require 'uri' require 'cgi' require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths")) module FillInHelpers def fill_in_first(locator, options={}) # Highly inspired by Capybara's fill_in implementation # https://github.com/jnicklas/capybara/blob/80befdad73c791eeaea50a7cbe23f04a445a24bc/lib/capybara/node/actions.rb#L50 raise "Must pass a hash containing 'with'" if not options.is_a?(Hash) or not options.has_key?(:with) with = options.delete(:with) first(:fillable_field, locator, options).set(with) end def fill_in_nth(locator, n, options={}) # Highly inspired by Capybara's fill_in implementation # https://github.com/jnicklas/capybara/blob/80befdad73c791eeaea50a7cbe23f04a445a24bc/lib/capybara/node/actions.rb#L50 raise "Must pass a hash containing 'with'" if not options.is_a?(Hash) or not options.has_key?(:with) with = options.delete(:with) results = all(:fillable_field, locator, options) if results.size >= n results[n - 1].set(with) end end end World(FillInHelpers) module WithinHelpers def with_scope(locator) if locator expect(page).to have_css(locator) within(locator) { yield } else yield end end end World(WithinHelpers) module FindHelpers def find_field_with_value(value) matches = all(:xpath, "//input[@value=\"#{value}\"]") exact_match = if matches.length == 0 throw "Couldn't find field with value '#{value}'" elsif matches.length > 1 throw "Ambiguous match, found #{matches.length} fields with value '#{value}'" else matches.first end end end World(FindHelpers) Given /^(?:|I )am on (.+)$/ do |page_name| visit path_to(page_name) end When /^(?:|I )go to (.+)$/ do |page_name| visit path_to(page_name) end When /^(?:|I )press "([^"]*)"(?: within "([^"]*)")?$/ do |button, selector| with_scope(selector) do click_button(button) end end When /^(?:|I )press submit(?: within "([^"]*)")?$/ do |selector| with_scope(selector) do find("[type=submit]").click end end When /^(?:|I )follow "([^"]*)"(?: within "([^"]*)")?$/ do |link, selector| with_scope(selector) do click_link(link) end end When(/^I follow the first "(.*?)"$/) do |link| first(:link, link).click end When /^I remove the focus"?$/ do page.execute_script("$('input').blur();") end When /^ajax requests are completed$/ do expect { page.evaluate_script("$.active") == 0 }.to become_true end When /^(?:|I )fill in "([^"]*)" with "([^"]*)"(?: within "([^"]*)")?$/ do |field, value, selector| with_scope(selector) do fill_in(field, :with => value) end end When /^(?:|I )fill in (first|second|third) "([^"]*)" with "([^"]*)"(?: within "([^"]*)")?$/ do |ordinal, field, value, selector| nums = {"first" => 1, "second" => 2, "third" => 3} n = nums[ordinal] with_scope(selector) do fill_in_nth(field, n, :with => value) end end When(/^I send keys "(.*?)" to form field "([^"]*)"$/) do |keys, field| find_field(field).native.send_keys "#{keys}" end When /^(?:|I )wait for (\d+) seconds?$/ do |arg1| sleep Integer(arg1) end When /^(?:|I )fill in "([^"]*)" for "([^"]*)"(?: within "([^"]*)")?$/ do |value, field, selector| with_scope(selector) do fill_in(field, :with => value) end end # Use this to fill in an entire form with data from a table. Example: # # When I fill in the following: # | Account Number | 5002 | # | Expiry date | 2009-11-01 | # | Note | Nice guy | # | Wants Email? | | # # TODO: Add support for checkbox, select og option # based on naming conventions. # When /^(?:|I )fill in the following(?: within "([^"]*)")?:$/ do |selector, fields| with_scope(selector) do fields.rows_hash.each do |name, value| When %{I fill in "#{name}" with "#{value}"} end end end When /^(?:|I )select "([^"]*)" from "([^"]*)"(?: within "([^"]*)")?$/ do |value, field, selector| with_scope(selector) do select(value, :from => field) end end When /^(?:|I )check "([^"]*)"(?: within "([^"]*)")?$/ do |field, selector| with_scope(selector) do check(field) end end When /^(?:|I )uncheck "([^"]*)"(?: within "([^"]*)")?$/ do |field, selector| with_scope(selector) do uncheck(field) end end When /^(?:|I )choose "([^"]*)"(?: within "([^"]*)")?$/ do |field, selector| with_scope(selector) do choose(field) end end When /^(?:|I )attach the file "([^"]*)" to "([^"]*)"(?: within "([^"]*)")?$/ do |path, field, selector| with_scope(selector) do attach_file(field, path) end end Then /^(?:|I )should see JSON:$/ do |expected_json| require 'json' expected = JSON.pretty_generate(JSON.parse(expected_json)) actual = JSON.pretty_generate(JSON.parse(response.body)) expect(expected).to eq(actual) end Then /^(?:|I )should see "([^"]*)"(?: within "([^"]*)")?$/ do |text, selector| with_scope(selector) do expect(page).to have_content(text) end end Then /^(?:|I )should see \/([^\/]*)\/(?: within "([^"]*)")?$/ do |regexp, selector| regexp = Regexp.new(regexp) with_scope(selector) do expect(page).to have_xpath('//*', :text => regexp) end end Then /^I should see "([^"]*)" in the "([^"]*)" input$/ do |content, field| expect(find_field(field).value).to eq(content) end Then /^(?:|I )should not see "([^"]*)"(?: within "([^"]*)")?$/ do |text, selector| with_scope(selector) do expect(page).to have_no_content(text) end end Then /^I should see dropdown field with label "([^"]*)"$/ do |label| find_field(label).tag_name == "select" end Then /^(?:|I )should not see \/([^\/]*)\/(?: within "([^"]*)")?$/ do |regexp, selector| regexp = Regexp.new(regexp) with_scope(selector) do expect(page).to have_no_xpath('//*', :text => regexp) end end Then /^the "([^"]*)" field(?: within "([^"]*)")? should contain "([^"]*)"$/ do |field, selector, value| with_scope(selector) do field = find_field(field) field_value = (field.tag_name == 'textarea') ? field.text : field.value expect(field_value).to match(/#{value}/) end end Then /^the "([^"]*)" field(?: within "([^"]*)")? should not contain "([^"]*)"$/ do |field, selector, value| with_scope(selector) do field = find_field(field) field_value = (field.tag_name == 'textarea') ? field.text : field.value expect(field_value).not_to match(/#{value}/) end end Then /^the "([^"]*)" checkbox(?: within "([^"]*)")? should be checked$/ do |label, selector| with_scope(selector) do field_checked = find_field(label)['checked'] expect(field_checked).to be_truthy end end Then /^the "([^"]*)" checkbox(?: within "([^"]*)")? should not be checked$/ do |label, selector| with_scope(selector) do field_checked = find_field(label)['checked'] expect(field_checked).to be_falsey end end Then /^(?:|I )should be on (URL )?(.+)$/ do |match_url, page| match_url = match_url == "URL" if match_url url = URI.parse(current_url) expect(url.to_s).to eq(page) elsif current_path.respond_to? :should current_path = URI.parse(current_url).path expect(current_path).to eq(path_to(page)) else assert_equal path_to(page), current_path end end Then /^(?:|I )should have the following query string:$/ do |expected_pairs| query = URI.parse(current_url).query actual_params = query ? CGI.parse(query) : {} expected_params = {} expected_pairs.rows_hash.each_pair{|k,v| expected_params[k] = v.split(',')} expect(actual_params).to eq(expected_params) end # This is a workaround for PhantomJS, which doesn't (or actually WebDriver) support confirm dialogs. # Use this keyword BEFORE the confirmation dialog appears Given /^I will(?:| (not)) confirm all following confirmation dialogs in this page if I am running PhantomJS$/ do |do_not_confirm| confirm = do_not_confirm != "not" if ENV['PHANTOMJS'] then page.execute_script("window.__original_confirm = window.confirm; window.confirm = function() { return #{confirm}; };") end end When /^I confirm alert popup$/ do page.driver.browser.switch_to.alert.accept unless ENV['PHANTOMJS'] end Then /^I should see validation error$/ do expect(find("label.error")).to be_visible end Then /^I should see (\d+) validation errors$/ do |errors_count| errors = all("label.error"); expect(errors.size).to eql(errors_count.to_i) all("label.error").each { |error| expect(error).to be_visible } end Then /^take a screenshot$/ do save_screenshot('screenshot.png') end Then /^show me the page$/ do save_and_open_page end When /^I refresh the page$/ do visit(current_path) end When /^I hover "([^"]*)"$/ do |selector| find(selector).hover end Then(/^"([^"]*)" should have CSS property "([^"]*)" with value "([^"]*)"$/) do |selector, property, value| actual_value = page.evaluate_script("$('#{selector}').css('#{property}')"); expect(actual_value).to be_eql(value) end When(/^I change field "([^"]*)" to "([^"]*)"$/) do |from, to| find_field_with_value(from).set(to) end
29.332288
129
0.636849
bb3206f53990c331589c61bd02352ad6dc3e4fb8
1,165
# frozen_string_literal: true module Preloaders # This class preloads the `project`, `group`, and subscription associations for the given # labels, user, and project (if provided). A Label can be of type ProjectLabel or GroupLabel # and the preloader supports both. # # Usage: # labels = Label.where(...) # Preloaders::LabelsPreloader.new(labels, current_user, @project).preload_all # labels.first.project # won't fire any query class LabelsPreloader attr_reader :labels, :user, :project def initialize(labels, user, project = nil) @labels = labels @user = user @project = project end def preload_all preloader = ActiveRecord::Associations::Preloader.new preloader.preload(labels.select {|l| l.is_a? ProjectLabel }, { project: [:project_feature, namespace: :route] }) preloader.preload(labels.select {|l| l.is_a? GroupLabel }, { group: :route }) labels.each do |label| label.lazy_subscription(user) label.lazy_subscription(user, project) if project.present? end end end end Preloaders::LabelsPreloader.prepend_mod_with('Preloaders::LabelsPreloader')
33.285714
118
0.696137
9104b6aeed0d314606ba6396954f0a3badf9e872
1,118
require 'sinatra/base' require 'mechanize' require './app/models/sweep' class PaypalAutosweep < Sinatra::Base set paypal_settings = YAML.load( File.read("config/paypal.yml") ) # Tasks uris # Autosweep post '/tasks/sweeps' do sweep = Sweep.new sweep.environment = paypal_settings['paypal']['environment'] sweep.email = paypal_settings['paypal']['email'] sweep.password = paypal_settings['paypal']['password'] sweep.api_username = paypal_settings['paypal']['api_username'] sweep.api_password = paypal_settings['paypal']['api_password'] sweep.api_signature = paypal_settings['paypal']['api_signature'] sweep.developer_email = paypal_settings['paypal']['developer_email'] sweep.developer_password = paypal_settings['paypal']['developer_password'] sweep.minimum_balance = paypal_settings['paypal']['minimum_balance'] sweep.minimum_transfer = paypal_settings['paypal']['minimum_transfer'] sweep.perform end get '/cron/autosweep' do AppEngine::Labs::TaskQueue.add( nil, :url => "/tasks/sweeps", :method => 'POST' ) end end
29.421053
79
0.701252
bf859e38c5cb73f9cb41b61be8ebbcb690e048a2
1,765
require 'spec_helper' describe "clients/index" do before(:each) do assign(:clients, [ stub_model(Client, :name => "Name", :company_name => "Company Name", :title => "Title", :email => "Email", :website => "Website", :user_id => 1, :address => "Address", :city => "City", :state => "State", :zip => "Zip", :phone => "Phone", :office_phone => "Office Phone" ), stub_model(Client, :name => "Name", :company_name => "Company Name", :title => "Title", :email => "Email", :website => "Website", :user_id => 1, :address => "Address", :city => "City", :state => "State", :zip => "Zip", :phone => "Phone", :office_phone => "Office Phone" ) ]) end it "renders a list of clients" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "tr>td", :text => "Name".to_s, :count => 2 assert_select "tr>td", :text => "Company Name".to_s, :count => 2 assert_select "tr>td", :text => "Title".to_s, :count => 2 assert_select "tr>td", :text => "Email".to_s, :count => 2 assert_select "tr>td", :text => "Website".to_s, :count => 2 assert_select "tr>td", :text => 1.to_s, :count => 2 assert_select "tr>td", :text => "Address".to_s, :count => 2 assert_select "tr>td", :text => "City".to_s, :count => 2 assert_select "tr>td", :text => "State".to_s, :count => 2 assert_select "tr>td", :text => "Zip".to_s, :count => 2 assert_select "tr>td", :text => "Phone".to_s, :count => 2 assert_select "tr>td", :text => "Office Phone".to_s, :count => 2 end end
32.685185
87
0.526912
ac8a2f8bd5fc32d47706c420977efbd295e68484
9,706
module ActiveMerchant #:nodoc: module Billing #:nodoc: class BarclaysEpdqGateway < Gateway TEST_URL = 'https://secure2.mde.epdq.co.uk:11500' LIVE_URL = 'https://secure2.epdq.co.uk:11500' self.supported_countries = ['UK'] self.default_currency = 'GBP' self.supported_cardtypes = [:visa, :master, :maestro, :switch ] self.money_format = :cents self.homepage_url = 'http://www.barclaycard.co.uk/business/accepting-payments/epdq-mpi/' self.display_name = 'Barclays ePDQ' def initialize(options = {}) requires!(options, :login, :password, :client_id) @options = options super end def authorize(money, creditcard, options = {}) document = Document.new(self, @options) do add_order_form(options[:order_id]) do add_consumer(options) do add_creditcard(creditcard) end add_transaction(:PreAuth, money) end end commit(document) end def purchase(money, creditcard, options = {}) # disable fraud checks if this is a repeat order: if options[:payment_number] && (options[:payment_number] > 1) no_fraud = true else no_fraud = options[:no_fraud] end document = Document.new(self, @options, :no_fraud => no_fraud) do add_order_form(options[:order_id], options[:group_id]) do add_consumer(options) do add_creditcard(creditcard) end add_transaction(:Auth, money, options) end end commit(document) end # authorization is your unique order ID, not the authorization # code returned by ePDQ def capture(money, authorization, options = {}) document = Document.new(self, @options) do add_order_form(authorization) do add_transaction(:PostAuth, money) end end commit(document) end # authorization is your unique order ID, not the authorization # code returned by ePDQ def credit(money, creditcard_or_authorization, options = {}) if creditcard_or_authorization.is_a?(String) credit_existing_order(money, creditcard_or_authorization, options) else credit_new_order(money, creditcard_or_authorization, options) end end def void(authorization, options = {}) document = Document.new(self, @options) do add_order_form(authorization) do add_transaction(:Void) end end commit(document) end private def credit_new_order(money, creditcard, options) document = Document.new(self, @options) do add_order_form do add_consumer(options) do add_creditcard(creditcard) end add_transaction(:Credit, money) end end commit(document) end def credit_existing_order(money, authorization, options) order_id, _ = authorization.split(":") document = Document.new(self, @options) do add_order_form(order_id) do add_transaction(:Credit, money) end end commit(document) end def parse(body) parser = Parser.new(body) response = parser.parse Response.new(response[:success], response[:message], response, :test => test?, :authorization => response[:authorization], :avs_result => response[:avsresponse], :cvv_result => response[:cvv_result], :order_id => response[:order_id], :raw_response => response[:raw_response] ) end def commit(document) url = (test? ? TEST_URL : LIVE_URL) data = ssl_post(url, document.to_xml) parse(data) end class Parser def initialize(response) @response = response end def parse doc = REXML::Document.new(@response) auth_type = find(doc, "//Transaction/Type").to_sym message = find(doc, "//Message/Text") if message.blank? message = find(doc, "//Transaction/CardProcResp/CcReturnMsg") end case auth_type.to_sym when :Credit, :Void success = find(doc, "//CcReturnMsg") == "Approved." else success = find(doc, "//Transaction/AuthCode").present? end { :success => success, :message => message, :authorization => [find(doc, "//OrderFormDoc/Id"), find(doc, "//Transaction/Id")].join(":"), :avs_result => find(doc, "//Transaction/AvsRespCode"), :cvv_result => find(doc, "//Transaction/Cvv2Resp"), :order_id => find(doc, "//OrderFormDoc/Transaction/Id"), :raw_response => @response } end def find(doc, xpath) REXML::XPath.first(doc, xpath).try(:text) end end class Document attr_reader :type, :xml PAYMENT_INTERVALS = { :days => 'D', :months => 'M' } EPDQ_CARD_TYPES = { :visa => 1, :master => 2, :switch => 9, :maestro => 10, } def initialize(gateway, options = {}, document_options = {}, &block) @gateway = gateway @options = options @document_options = document_options @xml = Builder::XmlMarkup.new(:indent => 2) build(&block) end def to_xml @xml.target! end def build(&block) xml.instruct!(:xml, :version => '1.0') xml.EngineDocList do xml.DocVersion "1.0" xml.EngineDoc do xml.ContentType "OrderFormDoc" xml.User do xml.Name(@options[:login]) xml.Password(@options[:password]) xml.ClientId({ :DataType => "S32" }, @options[:client_id]) end xml.Instructions do if @document_options[:no_fraud] xml.Pipeline "PaymentNoFraud" else xml.Pipeline "Payment" end end instance_eval(&block) end end end def add_order_form(order_id=nil, group_id=nil, &block) xml.OrderFormDoc do xml.Mode 'P' xml.Id(order_id) if order_id xml.GroupId(group_id) if group_id instance_eval(&block) end end def add_consumer(options=nil, &block) xml.Consumer do if options xml.Email(options[:email]) if options[:email] billing_address = options[:billing_address] || options[:address] if billing_address xml.BillTo do xml.Location do xml.Address do xml.Street1 billing_address[:address1] xml.Street2 billing_address[:address2] xml.City billing_address[:city] xml.StateProv billing_address[:state] xml.PostalCode billing_address[:zip] xml.Country billing_address[:country_code] end end end end end instance_eval(&block) end end def add_creditcard(creditcard) xml.PaymentMech do xml.CreditCard do xml.Type({ :DataType => 'S32' }, EPDQ_CARD_TYPES[creditcard.type.to_sym]) xml.Number creditcard.number xml.Expires({ :DataType => 'ExpirationDate', :Locale => 826 }, format_expiry_date(creditcard)) if creditcard.verification_value.present? xml.Cvv2Indicator 1 xml.Cvv2Val creditcard.verification_value else xml.Cvv2Indicator 5 end xml.IssueNum(creditcard.issue_number) if creditcard.issue_number.present? end end end def add_transaction(auth_type, amount = nil, options = {}) @auth_type = auth_type xml.Transaction do xml.Type @auth_type.to_s if options[:payment_number] && options[:payment_number] > 1 xml.CardholderPresentCode({ :DataType => 'S32' }, 8) else xml.CardholderPresentCode({ :DataType => 'S32' }, 7) end if options[:payment_number] xml.PaymentNumber({ :DataType => 'S32' }, options[:payment_number]) end if options[:total_payments] xml.TotalNumberPayments({ :DataType => 'S32' }, options[:total_payments]) end if amount xml.CurrentTotals do xml.Totals do xml.Total({ :DataType => 'Money', :Currency => 826 }, amount) end end end end end # date must be formatted MM/YY def format_expiry_date(creditcard) month_str = "%02d" % creditcard.month if match = creditcard.year.to_s.match(/^\d{2}(\d{2})$/) year_str = "%02d" % match[1].to_i else year_str = "%02d" % creditcard.year end "#{month_str}/#{year_str}" end end end end end
31.822951
108
0.530497
b9e12e8d44db7aff2fa96b350342aa0e7002abf6
31,124
# # Copyright 2019 ThoughtWorks, 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 'rails_helper' describe "config_view/templates/_job_view.html.erb" do include TaskMother it "should render job settings" do job = JobConfig.new('build_job') job.addResourceConfig('buildr') job.addResourceConfig('ruby') job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".summary fieldset.job_summary ul").tap do |list| list.find("li.field.resources").tap do |resources| resources.find("label").tap do |label| expect(label).to have_selector("span.key", :text => "Resources") expect(label).to have_selector("span.hint", :text => "Agent resources that this job requires to run") end expect(resources).to have_selector("span.value", :text => "buildr | ruby") end list.find("li.field.job_timeout").tap do |timeout| timeout.find("label").tap do |label| expect(label).to have_selector("span.key", :text => "Job Timeout") expect(label).to have_selector("span.hint", :text => "If this job is inactive for more than the specified period (in minutes), Go will cancel it.") end expect(timeout).to have_selector("span.value", :text => "Use default") end list.find("li.field.run_on_all_agents").tap do |run| run.find("label").tap do |label| expect(label).to have_selector("span.key", :text => "Run on all agents") end expect(run).to have_selector("span.value", :text => "No") end list.find("li.field.run_multiple_instances").tap do |run| run.find("label").tap do |label| expect(label).to have_selector("span.key", :text => "Run multiple instances") end expect(run).to have_selector("span.value", :text => "No") end end end end it "should render resources as none when no resources are configured" do job = JobConfig.new('build_job') job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".summary fieldset.job_summary ul").tap do |list| list.find("li.field.resources").tap do |item| item.find("label").tap do |label| expect(label).to have_selector("span.key", :text => "Resources") expect(label).to have_selector("span.hint", :text => "Agent resources that this job requires to run") end expect(item).to have_selector("span.value", :text => "None") end end end end it "should render job timeout it is configured to never timeout" do job = JobConfig.new('build_job') job.setTimeout('0') job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".summary fieldset.job_summary ul").tap do |list| list.find("li.field.job_timeout").tap do |item| item.find("label").tap do |label| expect(label).to have_selector("span.key", :text => "Job Timeout") expect(label).to have_selector("span.hint", :text => "If this job is inactive for more than the specified period (in minutes), Go will cancel it.") end expect(item).to have_selector("span.value", :text => "Never") end end end end it "should render overridden job timeout" do job = JobConfig.new('build_job') job.setTimeout('30') job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".summary fieldset.job_summary ul").tap do |list| list.find("li.field.job_timeout").tap do |item| item.find("label").tap do |label| expect(label).to have_selector("span.key", :text => "Job Timeout") expect(label).to have_selector("span.hint", :text => "If this job is inactive for more than the specified period (in minutes), Go will cancel it.") end expect(item).to have_selector("span.value", :text => "Cancel after '30' minute(s) of inactivity") end end end end it "should render when job is configured to run on all agents" do job = JobConfig.new('build_job') job.setRunOnAllAgents(true) job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".summary fieldset.job_summary ul").tap do |list| list.find("li.field.run_on_all_agents").tap do |item| item.find("label").tap do |label| expect(label).to have_selector("span.key", :text => "Run on all agents") end expect(item).to have_selector("span.value", :text => "Yes") end end end end it "should render when job is configured to run multiple instances" do job = JobConfig.new('build_job') job.setRunInstanceCount(2) job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".summary fieldset.job_summary ul").tap do |list| list.find("li.field.run_multiple_instances").tap do |item| item.find("label").tap do |label| expect(label).to have_selector("span.key", :text => "Run multiple instances") end expect(item).to have_selector("span.value", :text => "Yes") end end end end it "should render tabs to show job details like tasks, artifacts, environment variables and custom tabs" do job = JobConfig.new('build_job') job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find("ul.nav.nav-tabs").tap do |list| list.find("li.active").tap do |active_item| expect(active_item).to have_selector("a[href='#tasks_stage_id_job_1'][data-toggle='tab']", :text => "Tasks") end list.all("li:not(.active)").tap do |items| expect(items[0]).to have_selector("a[href='#artifacts_stage_id_job_1'][data-toggle='tab']", :text => "Artifacts") expect(items[1]).to have_selector("a[href='#environment_variables_stage_id_job_1'][data-toggle='tab']", :text => "Environment Variables") expect(items[2]).to have_selector("a[href='#custom_tabs_stage_id_job_1'][data-toggle='tab']", :text => "Custom Tabs") end end end end it "should render artifacts tab for a job" do artifact_plans = ArtifactConfigs.new() artifact_plans.add(BuildArtifactConfig.new("build-result", "build-output")) test_artifact = TestArtifactConfig.new('test-result', 'test-output') artifact_plans.add(test_artifact) artifact_plans.add(PluggableArtifactConfig.new("installer","hub.docker")) job = JobConfig.new(CaseInsensitiveString.new("jobName"), ResourceConfigs.new(), artifact_plans) job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| expect(job).to have_selector(".tab-content #artifacts_stage_id_job_1.tab-pane .artifact_title.build_artifact", count: 1, text: 'Build Artifact') expect(job).to have_selector(".tab-content #artifacts_stage_id_job_1.tab-pane .artifact_title.test_artifact", count: 1, text: 'Test Artifact') expect(job).to have_selector(".tab-content #artifacts_stage_id_job_1.tab-pane .artifact_title.external_artifact", count: 1, text: 'External Artifact') expect(job).not_to have_selector(".no_build_artifact") expect(job).not_to have_selector(".no_test_artifact") expect(job).not_to have_selector(".no_external_artifact") job.find(".tab-content #artifacts_stage_id_job_1.tab-pane .artifact_key_value_pair.build_artifact li").tap do |li| expect(li).to have_selector("label", count: 2) all_labels = li.all("label") expect(all_labels[0]).to have_selector("span.key", text: 'Source') expect(all_labels[0]).to have_selector("span.value", text: 'build-result') expect(all_labels[1]).to have_selector("span.key", text: 'Destination') expect(all_labels[1]).to have_selector("span.value", text: 'build-output') end job.find(".tab-content #artifacts_stage_id_job_1.tab-pane .artifact_key_value_pair.test_artifact li").tap do |li| expect(li).to have_selector("label", count: 2) all_labels = li.all("label") expect(all_labels[0]).to have_selector("span.key", text: 'Source') expect(all_labels[0]).to have_selector("span.value", text: 'test-result') expect(all_labels[1]).to have_selector("span.key", text: 'Destination') expect(all_labels[1]).to have_selector("span.value", text: 'test-output') end job.find(".tab-content #artifacts_stage_id_job_1.tab-pane .artifact_key_value_pair.external_artifact li").tap do |li| expect(li).to have_selector("label", count: 2) all_labels = li.all("label") expect(all_labels[0]).to have_selector("span.key", text: 'Artifact ID') expect(all_labels[0]).to have_selector("span.value", text: 'installer') expect(all_labels[1]).to have_selector("span.key", text: 'Store ID') expect(all_labels[1]).to have_selector("span.value", text: 'hub.docker') end end end it "should render artifacts tab when not configured for a job" do job = JobConfig.new('job1') job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| expect(job).to have_selector(".tab-content #artifacts_stage_id_job_1.tab-pane .artifact_title.build_artifact", count: 1, text: 'Build Artifact') expect(job).to have_selector(".tab-content #artifacts_stage_id_job_1.tab-pane .artifact_title.test_artifact", count: 1, text: 'Test Artifact') expect(job).to have_selector(".tab-content #artifacts_stage_id_job_1.tab-pane .artifact_title.external_artifact", count: 1, text: 'External Artifact') expect(job).to have_selector(".no_build_artifact", text: 'No build artifacts have been configured') expect(job).to have_selector(".no_test_artifact", text: 'No test artifacts have been configured') expect(job).to have_selector(".no_external_artifact", text: 'No external artifacts have been configured') expect(job).not_to have_selector(".tab-content #artifacts_stage_id_job_1.tab-pane .artifact_key_value_pair.build_artifact") expect(job).not_to have_selector(".tab-content #artifacts_stage_id_job_1.tab-pane .artifact_key_value_pair.test_artifact") expect(job).not_to have_selector(".tab-content #artifacts_stage_id_job_1.tab-pane .artifact_key_value_pair.external_artifact") end end it "should display environment variables for a job" do job = JobConfig.new('job1') job.addVariable('env1', 'value1') job.addVariable('env2', 'value2') job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #environment_variables_stage_id_job_1.tab-pane table.variables.list_table").tap do |table| table.find("thead").tap do |head| head.find("tr").tap do |row| expect(row).to have_selector("th", :text => "Name") expect(row).to have_selector("th", :text => "Value") end end table.find("tbody").tap do |body| body.all("tr").tap do |rows| expect(rows[0]).to have_selector("td.name_value_cell", :text => "env1") expect(rows[0]).to have_selector("td.name_value_cell", :text => "value1") expect(rows[1]).to have_selector("td.name_value_cell", :text => "env2") expect(rows[1]).to have_selector("td.name_value_cell", :text => "value2") end end end end end it "should display masked value for secure environment variables for a job" do job = JobConfig.new('job1') environment_variable_config_new = EnvironmentVariableConfig.new("env2", "value2") environment_variable_config_new.setIsSecure(true) job.setVariables(EnvironmentVariablesConfig.new([EnvironmentVariableConfig.new("env1", "value1"), environment_variable_config_new])) job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #environment_variables_stage_id_job_1.tab-pane table.variables.list_table").tap do |table| table.find("thead").tap do |head| head.find("tr").tap do |row| expect(row).to have_selector("th", :text => "Name") expect(row).to have_selector("th", :text => "Value") end end table.find("tbody").tap do |body| body.all("tr").tap do |rows| expect(rows[0]).to have_selector("td.name_value_cell", :text => "env1") expect(rows[0]).to have_selector("td.name_value_cell", :text => "value1") expect(rows[1]).to have_selector("td.name_value_cell", :text => "env2") expect(rows[1]).to have_selector("td.name_value_cell", :text => "****") end end end end end it "should render environment variables tab when no variables are configured" do job = JobConfig.new('job1') job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #environment_variables_stage_id_job_1.tab-pane table.variables.list_table").tap do |table| table.find("thead").tap do |head| head.find("tr").tap do |row| expect(row).to have_selector("th", :text => "Name") expect(row).to have_selector("th", :text => "Value") end end table.find("tbody").tap do |body| body.find("tr").tap do |row| expect(row).to have_selector("td.name_value_cell[align='center'][colspan='2']", :text => "No environment variables have been configured") end end end end end it "should display custom tab for a job" do job = JobConfig.new('job1') job.addTab('test-reports', 'reports/rspec') job.addTab('cobertura', 'reports/code-coverage') job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #custom_tabs_stage_id_job_1.tab-pane table.custom_tabs.list_table").tap do |table| table.find("thead").tap do |head| head.find("tr").tap do |row| expect(row).to have_selector("th", :text => "Tab Name") expect(row).to have_selector("th", :text => "Path") end end table.find("tbody").tap do |body| body.all("tr").tap do |rows| expect(rows[0]).to have_selector("td.name_value_cell", :text => "test-reports") expect(rows[0]).to have_selector("td.name_value_cell", :text => "reports/rspec") expect(rows[1]).to have_selector("td.name_value_cell", :text => "cobertura") expect(rows[1]).to have_selector("td.name_value_cell", :text => "reports/code-coverage") end end end end end it "should render custom tab when no tabs are configured" do job = JobConfig.new('job1') job.addTask(ant_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #custom_tabs_stage_id_job_1.tab-pane table.custom_tabs.list_table").tap do |table| table.find("thead").tap do |head| head.find("tr").tap do |row| expect(row).to have_selector("th", :text => "Tab Name") expect(row).to have_selector("th", :text => "Path") end end table.find("tbody").tap do |body| body.find("tr").tap do |row| expect(row).to have_selector("td.name_value_cell[align='center'][colspan='2']", :text => "No custom tabs have been configured") end end end end end describe "render tasks" do it "should display tasks of a job" do job = JobConfig.new('job1') job.addTask(ant_task) job.addTask(simple_exec_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #tasks_stage_id_job_1").tap do |tasks| tasks.find("ul.tasks_view_list").tap do |list| list.all("li").tap do |items| items[0].find("code").tap do |code| expect(code).to have_selector("span.working_dir", :text => "default/wd$") expect(code).to have_selector("span.command", :text => "ant") expect(code).to have_selector("span.arguments", :text => "-f \"build.xml\" compile") end expect(items[0]).to have_selector("span.condition", :text => "Run if Passed") expect(items[0]).to_not have_selector("ul li span.on_cancel") items[1].find("code").tap do |code| expect(code).to have_selector("span.working_dir", :text => "hero/ka/directory$") expect(code).to have_selector("span.command", :text => "ls") expect(code).to have_selector("span.arguments", :text => "-la") end expect(items[1]).to have_selector("span.condition", :text => "Run if Passed") end end end end end it "should display fetch artifact task of a job" do job = JobConfig.new('job1') job.addTask(fetch_task_with_exec_on_cancel_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #tasks_stage_id_job_1 ul.tasks_view_list").tap do |list| list.all("li.fetch code").tap do |items| item = items[0] expect(item).to have_selector("span", :text => "Fetch Artifact -") expect(item).to have_selector("span[title='Pipeline Name']", :text => "pipeline") expect(item).to have_selector("span.path_separator", :text => ">") expect(item).to have_selector("span[title='Stage Name']", :text => "stage") expect(item).to have_selector("span.path_separator", :text => ">") expect(item).to have_selector("span[title='Job Name']", :text => "job") expect(item).to have_selector("span.delimiter", :text => ":") expect(item).to have_selector("span[title='Source']", :text => "src") expect(item).to have_selector("span.direction_arrow", :text => "->") expect(item).to have_selector("span[title='Destination']", :text => "dest") end end end end it "should display fetch artifact task of a job when it fetches from same pipeline" do job = JobConfig.new('job1') task = fetch_task_with_exec_on_cancel_task(nil) job.addTask(task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #tasks_stage_id_job_1 ul.tasks_view_list").tap do |list| list.all("li.fetch code").tap do |items| item = items[0] expect(item).to have_selector("span", :text => "Fetch Artifact -") expect(item).to have_selector("span[title='Pipeline Name']", :text => "Current pipeline") expect(item).to have_selector("span.path_separator", :text => ">") expect(item).to have_selector("span[title='Stage Name']", :text => "stage") expect(item).to have_selector("span.path_separator", :text => ">") expect(item).to have_selector("span[title='Job Name']", :text => "job") expect(item).to have_selector("span.delimiter", :text => ":") expect(item).to have_selector("span[title='Source']", :text => "src") expect(item).to have_selector("span.direction_arrow", :text => "->") expect(item).to have_selector("span[title='Destination']", :text => "dest") end end end end it "should display fetch external artifact task" do job = JobConfig.new('job1') job.addTask(fetch_external_task(nil)) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #tasks_stage_id_job_1 ul.tasks_view_list").tap do |list| list.all("li.fetch code").tap do |items| item = items[0] expect(item).to have_selector("span", :text => "Fetch External Artifact -") expect(item).to have_selector("span[title='Pipeline Name']", :text => "Current pipeline") expect(item).to have_selector("span.path_separator", :text => ">") expect(item).to have_selector("span[title='Stage Name']", :text => "stage") expect(item).to have_selector("span.path_separator", :text => ">") expect(item).to have_selector("span[title='Job Name']", :text => "job") expect(item).to have_selector("span.delimiter", :text => ":") expect(item).to have_selector("span", :text => "ArtifactID") expect(item).to have_selector("span.delimiter", :text => ":") expect(item).to have_selector("span[title='Artifact ID']", :text => "docker") end end end end it "should display multiple run if conditions" do job = JobConfig.new('job1') task = simple_exec_task task.getConditions().add(com.thoughtworks.go.config.RunIfConfig::PASSED) task.getConditions().add(com.thoughtworks.go.config.RunIfConfig::FAILED) job.addTask(task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #tasks_stage_id_job_1 ul").tap do |list| list.find("li").tap do |item| expect(item).to have_selector("span.condition", :text => "Run if Passed, Failed") end end end end it "should display as run if Passed or failed when run if condition is any" do job = JobConfig.new('job1') task = simple_exec_task task.getConditions().add(com.thoughtworks.go.config.RunIfConfig::ANY) job.addTask(task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #tasks_stage_id_job_1 ul").tap do |list| list.find("li").tap do |item| expect(item).to have_selector("span.condition", :text => "Run if Failed, Passed") end end end end it "should display on cancel task details of a task" do job = JobConfig.new('job1') task = ant_task task.setCancelTask(nant_task) job.addTask(task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #tasks_stage_id_job_1 ul.tasks_view_list").tap do |list| list.find("li.ant").tap do |item| expect(item).to have_selector("span.condition", :text => "Run if Passed") item.all("code").tap do |codes| code = codes[0] expect(code).to have_selector("span.working_dir", :text => "default/wd$") expect(code).to have_selector("span.command", :text => "ant") expect(code).to have_selector("span.arguments", :text => "-f \"build.xml\" compile") end item.find("ul").tap do |list2| list2.find("li").tap do |item2| item2.find("code").tap do |code2| expect(code2).to have_selector("span.on_cancel", :text => "On Cancel") expect(code2).to have_selector("span.working_dir", :text => "default/wd$") expect(code2).to have_selector("span.command", :text => "nant") expect(code2).to have_selector("span.arguments", :text => "-buildfile:\"default.build\" compile") end end end end end end end it "should display message saying that no tasks have been configured when there are none" do job = JobConfig.new('job1') render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #tasks_stage_id_job_1").tap do |tasks| expect(tasks).to have_selector("span", :text => "No tasks have been configured") end end end it "should display task details of a plugin task" do pluggable_task = plugin_task "plugin.1", [ConfigurationPropertyMother.create("KEY1", false, "value1"), ConfigurationPropertyMother.create("KEY2", false, "value2")] job = JobConfig.new('job1') job.addTask(pluggable_task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #tasks_stage_id_job_1 ul.tasks_view_list").tap do |list| list.find("li.pluggable_task_plugin_1 code div.plugin-task").tap do |item| expect(item).to_not have_selector("span.on_cancel", :text => "On Cancel") expect(item).to have_selector("span.plugin-name", :text => "plugin.1") item.find("div.plugin-task-properties").tap do |prop| expect(prop).to have_selector(".plugin-task-property dt span.plugin-task-key-name", :text => "KEY1") expect(prop).to have_selector(".plugin-task-property dd.plugin-task-value", :text => "value1") expect(prop).to have_selector(".plugin-task-property dt span.plugin-task-key-name", :text => "KEY2") expect(prop).to have_selector(".plugin-task-property dd.plugin-task-value", :text => "value2") end end end end end it "should display cancel task details, even if it's a plugin task" do pluggable_task = plugin_task "plugin.1", [ConfigurationPropertyMother.create("KEY1", false, "value1"), ConfigurationPropertyMother.create("KEY2", false, "value2")] job = JobConfig.new('job1') task = ant_task task.setCancelTask(pluggable_task) job.addTask(task) render :partial => 'config_view/templates/job_view', :locals => {:scope => {:job => job, :index => 1, :stage_id => 'stage_id', :stage_name => "stage_build"}} Capybara.string(response.body).find("#stage_id_job_1").tap do |job| job.find(".tab-content #tasks_stage_id_job_1 ul.tasks_view_list").tap do |list| list.find("li.ant ul li code").tap do |code| expect(code).to have_selector("span.on_cancel", :text => "On Cancel") expect(code).to have_selector("span.plugin-name", :text => "plugin.1") list.find("div.plugin-task div.plugin-task-properties").tap do |prop| expect(prop).to have_selector(".plugin-task-property dt span.plugin-task-key-name", :text => "KEY1") expect(prop).to have_selector(".plugin-task-property dd.plugin-task-value", :text => "value1") expect(prop).to have_selector(".plugin-task-property dt span.plugin-task-key-name", :text => "KEY2") expect(prop).to have_selector(".plugin-task-property dd.plugin-task-value", :text => "value2") end end end end end end end
54.034722
169
0.63443
26c14f18eac9b3a15b6617ec8cfb0985b2b0af52
871
unless { a: 1 }.respond_to?(:fetch_values) # Add fetch_values if this version of ruby does not define it. class Hash def fetch_values(*keys) result = [] keys.each do |k| result << if block_given? yield(self[k]) else self[k] end end result end end end unless ''.respond_to?(:match?) # Add String#match? to pre-2.4 ruby class String def match?(regexp) self =~ regexp end end end unless //.respond_to?(:match?) # Add Regexp#match? to pre-2.4 ruby class Regexp def match?(str) self =~ str end end end unless ''.respond_to?(:strip_heredoc) # Patch String to provide heredocs with whitespace stripped class String def strip_heredoc indent = chomp.scan(/^\s*/).min.size gsub(/^\s{#{indent}}/, '') end end end
18.934783
64
0.580941
ac779c1574b86548280cfe194d26f34e5cc218a5
8,116
require 'spec_helper' require 'net/http' require 'timeout' require 'uri' require 'capybara/rspec' require 'capybara/poltergeist' Capybara.default_driver = :poltergeist Capybara.server = :webrick describe "SAML Authentication", type: :feature do let(:idp_port) { 8009 } let(:sp_port) { 8020 } shared_examples_for "it authenticates and creates users" do it "authenticates an existing user on a SP via an IdP" do create_user("you@example.com") visit 'http://localhost:8020/' expect(current_url).to match(%r(\Ahttp://localhost:8009/saml/auth\?SAMLRequest=)) fill_in "Email", with: "you@example.com" fill_in "Password", with: "asdf" click_on "Sign in" expect(page).to have_content("you@example.com") expect(current_url).to eq("http://localhost:8020/") end it "creates a user on the SP from the IdP attributes" do visit 'http://localhost:8020/' expect(current_url).to match(%r(\Ahttp://localhost:8009/saml/auth\?SAMLRequest=)) fill_in "Email", with: "you@example.com" fill_in "Password", with: "asdf" click_on "Sign in" expect(page).to have_content("you@example.com") expect(page).to have_content("A User") expect(current_url).to eq("http://localhost:8020/") end it "updates a user on the SP from the IdP attributes" do create_user("you@example.com") visit 'http://localhost:8020/' expect(current_url).to match(%r(\Ahttp://localhost:8009/saml/auth\?SAMLRequest=)) fill_in "Email", with: "you@example.com" fill_in "Password", with: "asdf" click_on "Sign in" expect(page).to have_content("you@example.com") expect(page).to have_content("A User") expect(current_url).to eq("http://localhost:8020/") end it "logs a user out of the IdP via the SP" do sign_in # prove user is still signed in visit 'http://localhost:8020/' expect(page).to have_content("you@example.com") expect(current_url).to eq("http://localhost:8020/") click_on "Log out" #confirm the logout response redirected to the SP which in turn attempted to sign the user back in expect(current_url).to match(%r(\Ahttp://localhost:8009/saml/auth\?SAMLRequest=)) # prove user is now signed out visit 'http://localhost:8020/' expect(current_url).to match(%r(\Ahttp://localhost:8009/saml/auth\?SAMLRequest=)) end end shared_examples_for "it logs a user out via the IdP" do it 'logs a user out of the SP via the IdP' do sign_in visit "http://localhost:#{idp_port}/saml/sp_sign_out" visit 'http://localhost:8020/' expect(current_url).to match(%r(\Ahttp://localhost:8009/saml/auth\?SAMLRequest=)) end end context "when the attributes are used to authenticate" do before(:each) do create_app('idp', 'INCLUDE_SUBJECT_IN_ATTRIBUTES' => "true") create_app('sp', 'USE_SUBJECT_TO_AUTHENTICATE' => "false") @idp_pid = start_app('idp', idp_port) @sp_pid = start_app('sp', sp_port) end after(:each) do stop_app(@idp_pid) stop_app(@sp_pid) end it_behaves_like "it authenticates and creates users" end context "when the subject is used to authenticate" do before(:each) do create_app('idp', 'INCLUDE_SUBJECT_IN_ATTRIBUTES' => "false") create_app('sp', 'USE_SUBJECT_TO_AUTHENTICATE' => "true") @idp_pid = start_app('idp', idp_port) @sp_pid = start_app('sp', sp_port) end after(:each) do stop_app(@idp_pid) stop_app(@sp_pid) end it_behaves_like "it authenticates and creates users" end context "when the session index key is set" do before(:each) do create_app('idp', 'INCLUDE_SUBJECT_IN_ATTRIBUTES' => "false") create_app('sp', 'USE_SUBJECT_TO_AUTHENTICATE' => "true", 'SAML_SESSION_INDEX_KEY' => ":session_index") @idp_pid = start_app('idp', idp_port) @sp_pid = start_app('sp', sp_port) end after(:each) do stop_app(@idp_pid) stop_app(@sp_pid) end it_behaves_like "it authenticates and creates users" it_behaves_like "it logs a user out via the IdP" end context "when the session index key is not set" do before(:each) do create_app('idp', 'INCLUDE_SUBJECT_IN_ATTRIBUTES' => "false") create_app('sp', 'USE_SUBJECT_TO_AUTHENTICATE' => "true", 'SAML_SESSION_INDEX_KEY' => "nil") @idp_pid = start_app('idp', idp_port) @sp_pid = start_app('sp', sp_port) end after(:each) do stop_app(@idp_pid) stop_app(@sp_pid) end it_behaves_like "it authenticates and creates users" end context "when the idp_settings_adapter key is set" do before(:each) do create_app('idp', 'INCLUDE_SUBJECT_IN_ATTRIBUTES' => "false") create_app('sp', 'USE_SUBJECT_TO_AUTHENTICATE' => "true", 'IDP_SETTINGS_ADAPTER' => "IdpSettingsAdapter", 'IDP_ENTITY_ID_READER' => "OurEntityIdReader") @idp_pid = start_app('idp', idp_port) @sp_pid = start_app('sp', sp_port) end after(:each) do stop_app(@idp_pid) stop_app(@sp_pid) end it "authenticates an existing user on a SP via an IdP" do create_user("you@example.com") visit 'http://localhost:8020/users/saml/sign_in/?entity_id=http%3A%2F%2Flocalhost%3A8020%2Fsaml%2Fmetadata' expect(current_url).to match(%r(\Ahttp://www.example.com/sso\?SAMLRequest=)) end it "logs a user out of the IdP via the SP" do sign_in # prove user is still signed in visit 'http://localhost:8020/' expect(page).to have_content("you@example.com") expect(current_url).to eq("http://localhost:8020/") click_on "Log out" #confirm the logout response redirected to the SP which in turn attempted to sign th e expect(current_url).to match(%r(\Ahttp://www.example.com/slo\?SAMLRequest=)) # prove user is now signed out visit 'http://localhost:8020/users/saml/sign_in/?entity_id=http%3A%2F%2Flocalhost%3A8020%2Fsaml%2Fmetadata' expect(current_url).to match(%r(\Ahttp://www.example.com/sso\?SAMLRequest=)) end end context "when the saml_failed_callback is set" do let(:valid_destination) { "true" } before(:each) do create_app('idp', 'INCLUDE_SUBJECT_IN_ATTRIBUTES' => "false", 'VALID_DESTINATION' => valid_destination) create_app('sp', 'USE_SUBJECT_TO_AUTHENTICATE' => "true", 'SAML_FAILED_CALLBACK' => "OurSamlFailedCallbackHandler") @idp_pid = start_app('idp', idp_port) @sp_pid = start_app('sp', sp_port) end after(:each) do stop_app(@idp_pid) stop_app(@sp_pid) end it_behaves_like "it authenticates and creates users" context "a bad SAML Request" do let(:valid_destination) { "false" } it "redirects to the callback handler's redirect destination" do create_user("you@example.com") visit 'http://localhost:8020/' expect(current_url).to match(%r(\Ahttp://localhost:8009/saml/auth\?SAMLRequest=)) fill_in "Email", with: "you@example.com" fill_in "Password", with: "asdf" click_on "Sign in" expect(page).to have_content(:all, "Example Domain This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.") expect(current_url).to eq("http://www.example.com/") end end end def create_user(email) response = Net::HTTP.post_form(URI('http://localhost:8020/users'), email: email) expect(response.code).to eq('201') end def sign_in visit 'http://localhost:8020/' expect(current_url).to match(%r(\Ahttp://localhost:8009/saml/auth\?SAMLRequest=)) fill_in "Email", with: "you@example.com" fill_in "Password", with: "asdf" click_on "Sign in" Timeout.timeout(Capybara.default_max_wait_time) do loop do sleep 0.1 break if current_url == "http://localhost:8020/" end end rescue Timeout::Error expect(current_url).to eq("http://localhost:8020/") end end
34.683761
213
0.666092
38885a460db33afd1d408cfe70afec627cb35391
569
require 'test/unit' require 'redgreenblue' class Test_int < Test::Unit::TestCase def test_to_i assert_equal 0, RGB.black.to_i assert_equal 16777215, RGB.white.to_i # https://codegolf.stackexchange.com/questions/43155 assert_equal 4563356, RGB.rgb(69,161,156).to_i end def test_at assert_equal RGB.black, RGB.at( 0) assert_equal RGB.white, RGB.at(16777215) assert_equal RGB.black, RGB.at(0.9) # https://codegolf.stackexchange.com/questions/43155 assert_equal RGB.rgb(69,161,156), RGB.at(4563356) end end
21.884615
56
0.699473
3905a648468d530759f6b12977d5f5d74e51e66b
4,842
############################################################################### # Copyright 2008-2010 Amazon Technologies, 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://aws.amazon.com/apache2.0 # This file 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 'base64' require 'cgi' require 'openssl' module Amazon module FPS # # Copyright:: Copyright (c) 2009 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # RFC 2104-compliant HMAC signature for request parameters # Implements AWS Signature, as per following spec: # # If Signature Version is 1, it performs the following: # # Sorts all parameters (including SignatureVersion and excluding Signature, # the value of which is being created), ignoring case. # # Iterate over the sorted list and append the parameter name (in original case) # and then its value. It will not URL-encode the parameter values before # constructing this string. There are no separators. # # If Signature Version is 2, string to sign is based on following: # # 1. The HTTP Request Method followed by an ASCII newline (%0A) # 2. The HTTP Host header in the form of lowercase host, followed by an ASCII newline. # 3. The URL encoded HTTP absolute path component of the URI # (up to but not including the query string parameters); # if this is empty use a forward '/'. This parameter is followed by an ASCII newline. # 4. The concatenation of all query string components (names and values) # as UTF-8 characters which are URL encoded as per RFC 3986 # (hex characters MUST be uppercase), sorted using lexicographic byte ordering. # Parameter names are separated from their values by the '=' character # (ASCII character 61), even if the value is empty. # Pairs of parameter and values are separated by the '&' character (ASCII code 38). # class SignatureUtils SIGNATURE_KEYNAME = "Signature" SIGNATURE_METHOD_KEYNAME = "SignatureMethod" SIGNATURE_VERSION_KEYNAME = "SignatureVersion" HMAC_SHA256_ALGORITHM = "HmacSHA256" HMAC_SHA1_ALGORITHM = "HmacSHA1" def self.sign_parameters(args) signature_version = args[:parameters][SIGNATURE_VERSION_KEYNAME] string_to_sign = ""; algorithm = 'sha1'; if (signature_version == '1') then string_to_sign = calculate_string_to_sign_v1(args) elsif (signature_version == '2') then algorithm = get_algorithm(args[:parameters][SIGNATURE_METHOD_KEYNAME]) string_to_sign = calculate_string_to_sign_v2(args) else raise "Invalid Signature Version specified" end return compute_signature(string_to_sign, args[:aws_secret_key], algorithm) end # Convert a string into URL encoded form. def self.urlencode(plaintext) CGI.escape(plaintext.to_s).gsub("+", "%20").gsub("%7E", "~") end private # All the methods below are private def self.calculate_string_to_sign_v1(args) parameters = args[:parameters] # exclude any existing Signature parameter from the canonical string sorted = (parameters.reject { |k, v| k == SIGNATURE_KEYNAME }).sort { |a,b| a[0].downcase <=> b[0].downcase } canonical = '' sorted.each do |v| canonical << v[0] canonical << v[1] unless(v[1].nil?) end return canonical end def self.calculate_string_to_sign_v2(args) parameters = args[:parameters] uri = args[:uri] uri = "/" if uri.nil? or uri.empty? uri = urlencode(uri).gsub("%2F", "/") verb = args[:verb] host = args[:host].downcase # exclude any existing Signature parameter from the canonical string sorted = (parameters.reject { |k, v| k == SIGNATURE_KEYNAME }) # sort the parameters sorted = sorted.sort{ |a, b| a.to_s <=> b.to_s } canonical = "#{verb}\n#{host}\n#{uri}\n" isFirst = true sorted.each { |v| if(isFirst) then isFirst = false else canonical << '&' end canonical << urlencode(v[0]) unless(v[1].nil?) then canonical << '=' canonical << urlencode(v[1]) end } return canonical end def self.get_algorithm(signature_method) return 'sha256' if (signature_method == HMAC_SHA256_ALGORITHM); return 'sha1' end def self.compute_signature(canonical, aws_secret_key, algorithm = 'sha1') digest = OpenSSL::Digest::Digest.new(algorithm) return Base64.encode64(OpenSSL::HMAC.digest(digest, aws_secret_key, canonical)).chomp end end end end
33.625
113
0.675754
386c5a9933f19327ac172257ee1c8863dd3b2cf9
2,511
require_relative 'naming' require_relative 'special_cases' module USCoreTestKit class Generator class MustSupportTestGenerator class << self def generate(ig_metadata, base_output_dir) ig_metadata.groups .reject { |group| SpecialCases.exclude_resource? group.resource } .each { |group| new(group, base_output_dir).generate } end end attr_accessor :group_metadata, :base_output_dir def initialize(group_metadata, base_output_dir) self.group_metadata = group_metadata self.base_output_dir = base_output_dir end def template @template ||= File.read(File.join(__dir__, 'templates', 'must_support.rb.erb')) end def output @output ||= ERB.new(template).result(binding) end def base_output_file_name "#{class_name.underscore}.rb" end def output_file_directory File.join(base_output_dir, profile_identifier) end def output_file_name File.join(output_file_directory, base_output_file_name) end def read_interaction self.class.read_interaction(group_metadata) end def profile_identifier Naming.snake_case_for_profile(group_metadata) end def test_id "us_core_#{group_metadata.reformatted_version}_#{profile_identifier}_must_support_test" end def class_name "#{Naming.upper_camel_case_for_profile(group_metadata)}MustSupportTest" end def module_name "USCore#{group_metadata.reformatted_version.upcase}" end def resource_type group_metadata.resource end def resource_collection_string 'all_scratch_resources' end def must_support_list_string slice_names = group_metadata.must_supports[:slices].map { |slice| slice[:name] } element_names = group_metadata.must_supports[:elements].map { |slice| "#{resource_type}.#{slice[:path]}" } extension_names = group_metadata.must_supports[:extensions].map { |slice| slice[:id] } (slice_names + element_names + extension_names) .sort .map { |name| " * #{name}" } .join("\n") end def generate FileUtils.mkdir_p(output_file_directory) File.open(output_file_name, 'w') { |f| f.write(output) } group_metadata.add_test( id: test_id, file_name: base_output_file_name ) end end end end
27.293478
114
0.652728
bb0d7d5da04624767258e0018b7c116e5d66cf07
43
module Transformer VERSION = "0.3.0" end
10.75
19
0.697674
d56a7a72f41b0acccbeb5610d4e56049b1c85241
783
class Ability include CanCan::Ability def initialize(user) @user = user || User.new # Normal Users can :read, [Board, Post, Tripcode] can :create, [User, Report, Post] can :search, Board # Users can delete a post if they have they have created the post or if they moderate the board. # Take a look at posts#destroy for an explanation. if @user.janitor? can :destroy, Post can :manage, Report end if @user.moderator? can :manage, Post can :manage, Report can :manage, Suspension end if @user.administrator? can :manage, Post can :manage, Report can :manage, Suspension can :manage, Board can :manage, User end can(:manage, :all) if @user.operator? end end
21.75
100
0.623244
4ae2ee72968c44c3378f95306657b685891231ee
628
# frozen_string_literal: true require File.expand_path('bot_config/environment', __dir__) require 'slack-ruby-bot/version' require 'slack-ruby-bot/support/loggable' require 'slack-ruby-bot/about' require 'slack-ruby-bot/config' require 'slack-ruby-bot/hooks' module SlackRubyBot class << self def configure block_given? ? yield(Config) : Config end def config Config end end end require 'slack-ruby-client' require 'slack-ruby-bot/commands' require 'slack-ruby-bot/client' require 'slack-ruby-bot/server' require 'slack-ruby-bot/app' require 'slack-ruby-bot/bot' require 'slack-ruby-bot/mvc'
21.655172
59
0.743631
1cee42774efd8f9e6997fb9dca430360c3f368ec
2,430
require 'seek/annotation_common' module Seek module AssetsCommon include Seek::AnnotationCommon include Seek::ContentBlobCommon include Seek::PreviewHandling include Seek::AssetsStandardControllerActions def find_display_asset(asset = instance_variable_get("@#{controller_name.singularize}")) requested_version = params[:version] || asset.latest_version.version found_version = asset.find_version(requested_version) if found_version&.visible? instance_variable_set("@display_#{asset.class.name.underscore}", asset.find_version(found_version)) else status = found_version.nil? ? :not_found : :forbidden error('This version is not available', 'invalid route', status) false end end def update_relationships(asset, params) Relationship.set_attributions(asset, params[:attributions]) end def request_contact resource = class_for_controller_name.find(params[:id]) details = params[:details] mail = Mailer.request_contact(current_user, resource, details) mail.deliver_later ContactRequestMessageLog.log_request(sender:current_user.person, item:resource, details:details) @resource = resource respond_to do |format| format.js { render template: 'assets/request_contact' } end end # For use in autocompleters def typeahead model_name = controller_name.classify model_class = class_for_controller_name results = model_class.where('title LIKE ?', "#{params[:query]}%").authorized_for('view') items = results.first(params[:limit] || 10).map do |item| contributor_name = item.contributor.try(:person).try(:name) { id: item.id, name: item.title, hint: contributor_name, type: model_name, contributor: contributor_name } end respond_to do |format| format.json { render json: items.to_json } end end # the page to return to on an update validation failure, default to 'edit' if the referer is not found def update_validation_error_return_action previous = Rails.application.routes.recognize_path(request.referrer) if previous && previous[:action] previous[:action] || 'edit' else 'edit' end end def params_for_controller name = controller_name.singularize method = "#{name}_params" send(method) end end end
34.225352
114
0.693827
b9a39362b9d10f5aae57e2c1b9cccb6000a04d03
5,818
class Person < ActiveRecord::Base include WikiEnabled include Freezable include Statistics include MovieListings include Logging class_inheritable_accessor :stub_fields freezable_attribute :name freezable_attribute :birthday freezable_attribute :birthplace freezable_attribute :deathday freezable_attribute :homepage db_depending_objects #depending_objects [ :self, :movies, :jobs ] stub [ :birthday ], :if => Proc.new { |value| value == "n/a" } stub [ :birthplace ], :if => :empty? has_many :casts, :order => 'casts.type, movies.end DESC', :include => :movie, :dependent => :destroy has_many :name_aliases, :as => :related_object # localized summary text has_many :abstracts, :as => :related_object, :extend => LocalFinder, :dependent => true # localized wiki pages has_many :pages, :as => :related_object, :extend => LocalFinder, :order => :name, :dependent => true has_many :movies, :through => :casts, :select => 'DISTINCT movies.*', :order => 'end' has_many :chronological_movies, :class_name => "Movie", :through => :casts, :source => :movie, :select => 'DISTINCT movies.*', :conditions => "movies.end IS NOT NULL AND movies.end <= '#{Date.today.to_s}'", :order => "movies.end ASC" has_many :jobs, :select => 'DISTINCT jobs.*', :through => :casts has_many :highest_rated_movies, :class_name => "Movie", :finder_sql => 'SELECT DISTINCT movies.* FROM movies INNER JOIN casts ON movies.id = casts.movie_id WHERE (casts.person_id = #{id}) ORDER BY movies.vote DESC LIMIT 25' has_many :upcoming_movies, :through => :casts, :source => :movie, :limit => 3, :select => 'DISTINCT movies.*', :order => "movies.end", :conditions => "movies.end > '#{Date.today.to_s}'", :class_name => "Movie" has_many :popular_movies, :through => :casts, :source => :movie, :select => 'DISTINCT movies.*', :limit => 10, :conditions => "movies.end < '#{Date.today.to_s}'", :order => "movies.popularity", :class_name => "Movie" has_one :image, :as => :related_object, :dependent => :destroy alias :portrait :image validates_presence_of :name def all_movies( limit, offset ) movies.slice( offset, limit ) end def aliases name_aliases end def birthday orig_bday = read_attribute(:birthday) ( orig_bday.nil? or orig_bday.to_s == '1900-01-01' ) ? 'n/a' : orig_bday end def birth_year orig_bday = read_attribute(:birthday) ( orig_bday.nil? or orig_bday.to_s == '1900-01-01' ) ? 'n/a' : orig_bday.year end def merge( people ) people.delete_if { |p| p.id == self.id } people.each do |p| p.casts.each do |cast| cast.person = self cast.save! end self.name_aliases << NameAlias.new( :name => p.name, :language => Language.independent_language ) unless p.name == self.name # we need to reload the person, otherwise all casts would # be gone, as AR is to stupid to see that i just removed # the casts from that person, and will use his cached records for casts. p.reload.destroy end self.save end def assoc_column_name Inflector.singularize(self.class.table_name) + "_id" end def to_search_result_xml( xml, language = Locale.base_language ) xml.person do xml.id self.id xml.name self.name xml.abstract self.abstracts.local(language).first.nil? ? "" : self.abstracts.local( language ).first.data xml.birthDay self.birthday, :type => :date end end def self.search( query, lang ) Searcher.search_people( query, lang.code ) end def self.search_by_prefix( query, lang, offset = 0, limit = 100 ) Searcher.search_people_by_prefix( query, lang.code, offset, limit ) end def self.find_orphans Person.find_by_sql( "SELECT people.*, casts.id as cast_id FROM people LEFT JOIN casts ON people.id = casts.person_id WHERE ISNULL(casts.id)" ) end def self.popular Person.find(:all, :limit => 10, :order => 'popularity DESC') end def self.of_the_day Person.find(:first, :limit => 1, :conditions => [ 'person_of_the_day = ?', Date.jd(DateTime.now.jd).to_s ]) end def self.born_today [ 150, 125, 100, 75, 60, 50, 40, 30, 25, 20, 18 ].each do |years_ago| person = Person.find(:first, :limit => 1, :conditions => [ 'birthday = ?', (Time.now.year - years_ago).to_s + "-" + Time.now.to_date.strftime('%m') + "-" + Time.now.to_date.strftime('%d') ], :order => :popularity) return { years_ago => person } unless person.nil? end return nil end def self.popular_actors Person.find( :all, :limit => 10, :include => :casts, :order => 'people.popularity DESC', :conditions => [ 'casts.job_id = ?', Job.actor.id ] ) end def self.person_of_the_day_candidate Person.find_by_sql( 'select * from people where (select count(*) from casts where casts.person_id = people.id) > 9 order by rand() limit 1;' ).first end end
30.783069
175
0.562221
f7245bb4890f2f277026c759646ec2df1af02818
1,167
require 'test_helper' class CategoriesControllerTest < ActionController::TestCase setup do @category = categories(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:categories) end test "should get new" do get :new assert_response :success end test "should create category" do assert_difference('Category.count') do post :create, category: { id: @category.id, name: @category.name, parent: @category.parent } end assert_redirected_to category_path(assigns(:category)) end test "should show category" do get :show, id: @category assert_response :success end test "should get edit" do get :edit, id: @category assert_response :success end test "should update category" do patch :update, id: @category, category: { id: @category.id, name: @category.name, parent: @category.parent } assert_redirected_to category_path(assigns(:category)) end test "should destroy category" do assert_difference('Category.count', -1) do delete :destroy, id: @category end assert_redirected_to categories_path end end
23.34
112
0.703513
281ccc125bc8075107259ada642f73a7b816ed34
315
require 'browser_crawler/version' require 'browser_crawler/options' require 'browser_crawler/engine' require 'browser_crawler/followups/screenshots_indexer' require 'browser_crawler/followups/wraith_integrator' # Crawls web site and extracts links available. module BrowserCrawler # Your code goes here... end
24.230769
55
0.828571
6239f300d09945e2271eb1ec5f7a9507654e58a9
1,246
require 'spec_helper' describe Dragonfly::Encoding::ImageMagickEncoder do before(:all) do sample_file = File.dirname(__FILE__) + '/../../../samples/beach.png' # 280x355, 135KB @image = Dragonfly::TempObject.new(File.new(sample_file)) @encoder = Dragonfly::Encoding::ImageMagickEncoder.new end describe "#encode" do it "should encode the image to the correct format" do image = @encoder.encode(@image, :gif) image.should have_format('gif') end it "should throw :unable_to_handle if the format is not handleable" do lambda{ @encoder.encode(@image, :goofy) }.should throw_symbol(:unable_to_handle) end it "should do nothing if the image is already in the correct format" do image = @encoder.encode(@image, :png) image.should == @image end it "should allow for extra args" do image = @encoder.encode(@image, :jpg, '-quality 1') image.should have_format('jpeg') image.should have_size('1.45KB') end it "should still work even if the image is already in the correct format and args are given" do image = @encoder.encode(@image, :png, '-quality 1') image.should_not == @image end end end
29.666667
99
0.652488
1d2c98ad2e2cda6ba7da09988dd40e195073028f
1,686
# # Be sure to run `pod lib lint CustomField.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 https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'CustomField' s.version = '1.0.3' s.summary = 'Lib for match LRTextField and MFTextField for intern use' # 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 = 'Lib for match LRTextField and MFTextField for intern use of specific project with style and layout for UITextField Custom' s.homepage = 'https://github.com/thaissadami/CustomField.git' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'thaissadami' => 'thaissadami@gmail.com' } s.source = { :git => 'https://github.com/thaissadami/CustomField.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '8.0' s.source_files = 'CustomField/Pod/Classes/**/*' # s.resource_bundles = { # 'CustomField' => ['CustomField/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' end
41.121951
146
0.664294
f8c75c1b6b5e59f90bbb0952f6f7c3c3f8a0cbc4
3,142
user = User.find_by_first_name('a user') admin = User.find_by_first_name('an admin') site_with_calendars = Site.create! :name => 'site with calendar', :title => 'site with calendar title', :host => 'site-with-calendar.com' admin.roles.create!(:name => 'admin', :context => site_with_calendars) site_with_calendars.users << admin site_with_calendars.users << user calendar_without_events = Calendar.create! :site => site_with_calendars, :title => 'a calendar without events', :permalink => 'calendar-without-events', :published_at => Time.parse('2008-01-01 12:00:00') calendar_with_events = Calendar.create! :site => site_with_calendars, :title => 'a calendar with events', :permalink => 'calendar-with-events', :published_at => Time.parse('2008-01-01 12:00:00') time = Time.utc(2009, 2, 3, 15, 0, 0) # 2009-2-8 an_upcoming_event = CalendarEvent.create! :section => calendar_with_events, :title => 'an upcoming event', :body => 'We are so much looking forward for this event', :user => user, :start_date => time + 5.days, :end_date => time + 5.days + 2.hours, :published_at => time # 2009-1-29 to 2009-2-3 an_ongoing_event = CalendarEvent.create! :section => calendar_with_events, :title => 'an ongoing event', :body => 'This event started earlier and will end soon', :user => user, :start_date => time - 5.days, :end_date => time + 2.hours, :published_at => time - 1.week # 2009-1-31 a_past_event = CalendarEvent.create! :section => calendar_with_events, :title => 'a past event', :body => 'The event took place three days ago', :user => user, :start_date => time - 3.days, :end_date => time - 3.days + 2.hours, :published_at => time - 1.week # 2008-2-3 a_event_last_year = CalendarEvent.create! :section => calendar_with_events, :title => 'a event last year', :body => 'We had a lot of fun last year', :user => user, :start_date => time - 1.year, :end_date => time - 1.year + 2.hours, :published_at => nil category_jazz = Category.create! :section => calendar_with_events, :title => 'Jazz' category_rock = Category.create! :section => calendar_with_events, :title => 'Rock' category_punk = Category.create! :section => calendar_with_events, :title => 'Punk' an_upcoming_event.categories = [category_jazz, category_rock] an_ongoing_event.categories = [category_jazz, category_punk] a_past_event.categories = [category_punk] a_event_last_year.categories = [category_rock]
37.404762
79
0.546785
91333af668cf5a63c6acd2b87dfc2ce8e478c549
2,190
require 'json' module Fastlane class JSONReturnValueProcessor def prepare_object(return_value: nil, return_value_type: nil) case return_value_type when nil UI.verbose("return_value_type is nil value: #{return_value}") return process_value_as_string(return_value: return_value) when :string return process_value_as_string(return_value: return_value) when :int return process_value_as_int(return_value: return_value) when :bool return process_value_as_bool(return_value: return_value) when :array_of_strings return process_value_as_array_of_strings(return_value: return_value) when :hash_of_strings return process_value_as_hash_of_strings(return_value: return_value) else UI.verbose("Unknown return type defined: #{return_value_type} for value: #{return_value}") return process_value_as_string(return_value: return_value) end end def process_value_as_string(return_value: nil) if return_value.nil? return_value = "" end return_value end def process_value_as_array_of_strings(return_value: nil) if return_value.nil? return_value = [] end # quirks_mode shouldn't be required for real objects return JSON.generate(return_value) end def process_value_as_hash_of_strings(return_value: nil) if return_value.nil? return_value = {} end # quirks_mode shouldn't be required for real objects return JSON.generate(return_value) end def process_value_as_bool(return_value: nil) if return_value.nil? return_value = false end # quirks_mode because sometimes the built-in library is used for some folks and that needs quirks_mode: true return JSON.generate(return_value.to_s, quirks_mode: true) end def process_value_as_int(return_value: nil) if return_value.nil? return_value = 0 end # quirks_mode because sometimes the built-in library is used for some folks and that needs quirks_mode: true return JSON.generate(return_value.to_s, quirks_mode: true) end end end
30.84507
114
0.708219
01dc97fdc4f52c840686a5c8cc84ef891113e66a
336
require "helper" require "fluent/plugin/out_file_with_header.rb" class FileWithHeaderOutputTest < Test::Unit::TestCase setup do Fluent::Test.setup end test "failure" do flunk end private def create_driver(conf) Fluent::Test::Driver::Output.new(Fluent::Plugin::FileWithHeaderOutput).configure(conf) end end
17.684211
90
0.738095
1878191b9ae13d27566d2111b7dede15000d1b26
17,612
require_relative 'strToArray' require_relative 'read_file_line_by_line' require_relative 'paranthesis_compactor' require_relative 'replace_strings' require_relative 'rollblocks' def compile_named_functions(input_file_contents, named_code_blocks, nested_functions, temporary_nila_file) #This method compiles all the named Nila functions. Below is an example of what is meant #by named/explicit function #def square(input_number) # # input_number*input_number # #end #The above function will compile to #square = function(input_number) { # # return input_number*input_number; # #}; def is_parameterless?(input_function_block) if input_function_block[0].include?("(") false else true end end def lexical_scoped_variables(input_function_block) def remove_properties(variables) variables = variables.sort output_variables = variables.clone rejects = [] variables.each do |element| unless rejects.include?(element) rejected_variables = output_variables.reject{|val| !val.index(Regexp.new("#{element}."))} rejected_variables.each do |val| rejects << val end end end output_variables = output_variables - rejects return output_variables end #This method will pickup and declare all the variables inside a function block. In future, this method will be #merged with the get variables method input_function_block = input_function_block.collect {|element| replace_strings(element)} controlregexp = /(if |Euuf |for |while |def |function |function\()/ variables = [] function_name, parameters = input_function_block[0].split("(") parameters = parameters.split(")")[0].split(",") parameters = parameters.collect { |element| element.strip } input_function_block.each do |line| if line.include? "=" and line.index(controlregexp).nil? current_line_split = line.strip.split("=") if current_line_split[0].include?("return") current_line_split[0] = current_line_split[0].sub("return","").strip end variables << current_line_split[0].rstrip end end parameters.each do |param| if variables.include?(param) variables.delete(param) end end variables = remove_properties(variables) if variables.empty? return [] else return variables.uniq.sort end end def remove_question_marks(input_file_contents, input_list, temporary_nila_file) joined_file_contents = input_file_contents.join input_list.each do |element| if element.include? "?" joined_file_contents = joined_file_contents.gsub(element, element[0...-1]) end end file_id = open(temporary_nila_file, 'w') file_id.write(joined_file_contents) file_id.close() line_by_line_contents = read_file_line_by_line(temporary_nila_file) return line_by_line_contents end def add_auto_return_statement(input_array) joined_array = input_array.join reversed_input_array = input_array.reverse if !joined_array.include?("return ") rejected_array = reversed_input_array.reject { |content| content.lstrip.eql?("") } rejected_array = rejected_array.reject {|content| content.strip.eql?("")} rejected_array = rejected_array[1..-1] unless rejected_array[0].strip.eql?("}") or rejected_array[0].strip.eql?("})") if !rejected_array[0].strip.eql?("end") and !rejected_array[0].strip.include?("--single_line_comment") last_statement = rejected_array[0] replacement_string = "return #{last_statement.lstrip}" input_array[input_array.index(last_statement)] = replacement_string end end end return input_array end def compile_multiple_return(input_array) def find_all_matching_indices(input_string, pattern) locations = [] index = input_string.index(pattern) while index != nil locations << index index = input_string.index(pattern, index+1) end return locations end modified_input_array = input_array.dup return_statements = input_array.dup.reject { |element| !element.include? "return" } multiple_return_statements = return_statements.dup.reject { |element| !element.include? "," } modified_multiple_return_statements = multiple_return_statements.dup return_statement_index = [] multiple_return_statements.each do |statement| location_array = modified_input_array.each_index.select { |index| modified_input_array[index] == statement } return_statement_index << location_array[0] end multiple_return_statements.each_with_index do |return_statement, index| replacement_counter = 0 if return_statement.include? "\"" starting_quotes = find_all_matching_indices(return_statement, "\"") for x in 0...(starting_quotes.length)/2 quotes = return_statement[starting_quotes[x]..starting_quotes[x+1]] replacement_counter += 1 modified_multiple_return_statements[index] = modified_multiple_return_statements[index].sub(quotes, "repstring#{1}") modified_input_array[return_statement_index[index]] = modified_multiple_return_statements[index].sub(quotes, "repstring#{1}") end end end modified_multiple_return_statements = modified_multiple_return_statements.reject { |element| !element.include? "," } return_statement_index = [] modified_multiple_return_statements.each do |statement| location_array = modified_input_array.each_index.select { |index| modified_input_array[index] == statement } return_statement_index << location_array[0] end modified_multiple_return_statements.each_with_index do |return_statement, index| method_call_counter = 0 if return_statement.include? "(" open_paran_location = find_all_matching_indices(return_statement, "(") open_paran_location.each do |paran_index| method_call = return_statement[paran_index..return_statement.index(")", paran_index+1)] method_call_counter += 1 modified_multiple_return_statements[index] = modified_multiple_return_statements[index].sub(method_call, "methodcall#{method_call_counter}") modified_input_array[return_statement_index[index]] = modified_multiple_return_statements[index].sub(method_call, "methodcall#{method_call_counter}") end end end modified_multiple_return_statements = modified_multiple_return_statements.reject { |element| !element.include?(",") } return_statement_index = [] modified_multiple_return_statements.each do |statement| location_array = modified_input_array.each_index.select { |index| modified_input_array[index] == statement } return_statement_index << location_array[0] end return_statement_index.each do |index| original_statement = input_array[index] statement_split = original_statement.split("return ") replacement_split = "return [" + statement_split[1].rstrip + "]\n\n" input_array[index] = replacement_split end return input_array end def coffee_type_function(input_array) input_array = input_array.collect {|element| element.gsub("(function","&F*^u$#N)(&C")} function_name = input_array[0].split("function ")[1].split("(")[0].lstrip input_array[0] = "#{function_name} = function(" + input_array[0].split("function ")[1].split("(")[1].lstrip input_array = input_array.collect {|element| element.gsub("&F*^u$#N)(&C","(function")} return input_array end def compile_function(input_array, temporary_nila_file) modified_input_array = input_array.dup if is_parameterless?(modified_input_array) if modified_input_array[0].include?("--single") modified_input_array[0] = input_array[0].sub "def", "function" interim_string = modified_input_array[0].split("--single") modified_input_array[0] = interim_string[0].rstrip + "() {\n--single" + interim_string[1] elsif modified_input_array[0].include?("--multi") modified_input_array[0] = input_array[0].sub "def", "function" interim_string = modified_input_array[0].split("--multi") modified_input_array[0] = interim_string[0].rstrip + "() {\n--multi" + interim_string[1] else modified_input_array[0] = input_array[0].sub "def", "function" modified_input_array[0] = modified_input_array[0].rstrip + "() {\n" end else if modified_input_array[0].include?("--single") modified_input_array[0] = input_array[0].sub "def", "function" interim_string = modified_input_array[0].split("--single") modified_input_array[0] = interim_string[0].rstrip + " {\n--single" + interim_string[1] elsif modified_input_array[0].include?("--multi") modified_input_array[0] = input_array[0].sub "def", "function" interim_string = modified_input_array[0].split("--multi") modified_input_array[0] = interim_string[0].rstrip + " {\n--multi" + interim_string[1] else modified_input_array[0] = input_array[0].sub "def", "function" modified_input_array[0] = modified_input_array[0].rstrip + " {\n" end end modified_input_array[-1] = input_array[-1].sub "end", "};\n" modified_input_array = compile_parallel_assignment(modified_input_array, temporary_nila_file) modified_input_array = compile_multiple_ruby_func_calls(modified_input_array) modified_input_array = add_auto_return_statement(modified_input_array) modified_input_array = compile_multiple_return(modified_input_array) modified_input_array = coffee_type_function(modified_input_array) modified_input_array = compile_splats(modified_input_array) variables = lexical_scoped_variables(modified_input_array) if !variables.empty? variable_string = "\nvar " + variables.join(", ") + "\n" modified_input_array.insert(1, variable_string) end modified_input_array = remove_question_marks(modified_input_array, variables, temporary_nila_file) return modified_input_array end def extract_function_name(input_code_block) first_line = input_code_block[0] first_line_split = first_line.split(" ") if first_line_split[1].include?("(") function_name, parameters = first_line_split[1].split("(") else function_name = first_line_split[1] end return function_name end def compile_splats(input_function_block) def errorFree(function_params,optional_param) # This method checks for use cases in complex arguments where a default argument is used # after an optional argument. This will result in erroneous output. So this method will # stop it from happening. # Example: # def method_name(a,b,*c,d = 1,c,e) after_splat = function_params[function_params.index(optional_param)+1..-1] if after_splat.reject {|element| !element.include?("=")}.empty? true else raise "You cannot have a default argument after an optional argument!" false end end function_params = input_function_block[0].split("function(")[1].split(")")[0].split(",") unless function_params.reject{|element| !replace_strings(element).include?("*")}.empty? mod_function_params = function_params.reject {|element| replace_strings(element).include?("*")} opt_index = 0 # If there are multiple optional params declared by mistake, only the first optional param is used. optional_param = function_params.reject {|element| !replace_strings(element).include?("*")}[0] if function_params.index(optional_param).eql?(function_params.length-1) mod_function_params.each_with_index do |param,index| input_function_block.insert(index+1,"#{param} = arguments[#{index}]\n\n") opt_index = index + 1 end replacement_string = "#{optional_param.gsub("*","")} = []\n\n" replacement_string += "for (var i=#{opt_index};i<arguments.length;i++) {\n #{optional_param.gsub("*","")}.push(arguments[i]); \n}\n\n" input_function_block.insert(opt_index+1,replacement_string) input_function_block[0] = input_function_block[0].sub(function_params.join(","),"") else before_splat = function_params[0...function_params.index(optional_param)] after_splat = function_params[function_params.index(optional_param)+1..-1] cont_index = 0 if errorFree(function_params,optional_param) before_splat.each_with_index do |param,index| input_function_block.insert(index+1,"#{param} = arguments[#{index}]\n\n") cont_index = index + 1 end after_splat.each_with_index do |param,index| input_function_block.insert(cont_index+1,"#{param} = arguments[arguments.length-#{after_splat.length - index}]\n\n") cont_index = cont_index + 1 end replacement_string = "#{optional_param.gsub("*","")} = []\n\n" replacement_string += "for (var i=#{function_params.index(optional_param)};i < arguments.length-#{after_splat.length};i++) {\n #{optional_param.gsub("*","")}.push(arguments[i]); \n}\n\n" input_function_block.insert(cont_index+1,replacement_string) input_function_block[0] = input_function_block[0].sub(function_params.join(","),"") end end end return strToArray(input_function_block.join) end def compile_multiple_ruby_func_calls(input_file_contents) def replace_complex_strings(input_string) string_counter = 0 if input_string.count("\"") % 2 == 0 while input_string.include?("\"") string_extract = input_string[input_string.index("\"")..input_string.index("\"",input_string.index("\"")+1)] input_string = input_string.sub(string_extract,"--repstring#{string_counter}") string_counter += 1 end end if input_string.count("'") % 2 == 0 while input_string.include?("'") string_extract = input_string[input_string.index("'")..input_string.index("'",input_string.index("'")+1)] input_string = input_string.sub(string_extract,"--repstring#{string_counter}") string_counter += 1 end end input_string = input_string.gsub(/\((\w{0,},)*\w{0,}\)/,"--$k$") return input_string end function_calls = [] replacement_calls = [] function_map = %w{puts p print} javascript_regexp = /(if |for |while |\(function\(|= function\(|((=|:)\s+\{))/ stringified_input = input_file_contents.collect {|element| replace_complex_strings(element)} function_map.each do |func| func_calls = input_file_contents.reject {|line| !(replace_strings(line).include?(func+"(") or replace_strings(line).include?(func+" ") and replace_strings(line).index(javascript_regexp) == nil)} unless func_calls.empty? modified_func_calls = func_calls.collect {|element| replace_complex_strings(element)} modified_func_calls = modified_func_calls.reject {|element| !element.include?(",")} modified_func_calls = modified_func_calls.reject {|element| !compact_paranthesis(element).include?(",")} call_collector = [] modified_func_calls.each_with_index do |ele| call_collector << input_file_contents[stringified_input.index(ele)] end function_calls << modified_func_calls rep_calls = [] call_collector.each do |fcall| multiple_call = fcall.split(func)[1].split(",") multiple_call = multiple_call.collect {|element| "\n#{func} " + element.strip + "\n\n"} rep_calls << multiple_call.join end replacement_calls << rep_calls end end replacement_calls = replacement_calls.flatten function_calls = function_calls.flatten function_calls.each_with_index do |fcall,index| input_file_contents[stringified_input.index(fcall)] = replacement_calls[index] end return strToArray(input_file_contents.join) end joined_file_contents = input_file_contents.join unless named_code_blocks.empty? codeblock_counter = 1 function_names = [] named_code_blocks.each do |codeblock| function_names[codeblock_counter-1] = [] joined_file_contents = joined_file_contents.sub("--named_function[#{codeblock_counter}]\n", compile_function(codeblock, temporary_nila_file).join) codeblock_counter += 1 function_names[codeblock_counter-2] << extract_function_name(codeblock) unless nested_functions.empty? current_nested_functions = nested_functions[codeblock_counter-2] current_nested_functions.each do |nested_function| function_names[codeblock_counter-2] << extract_function_name(nested_function) joined_file_contents = joined_file_contents.sub(nested_function.join, compile_function(nested_function, temporary_nila_file).join) end end end else function_names = [] end file_id = open(temporary_nila_file, 'w') file_id.write(joined_file_contents) file_id.close() line_by_line_contents = compile_multiple_ruby_func_calls(read_file_line_by_line(temporary_nila_file)) return line_by_line_contents, function_names end
25.304598
200
0.690495
036a8bccd533e10b069ccb79de056ed6c5ff3865
498
# frozen_string_literal: true require "shipengine" module TestUtils # @param spy [Spy] - spy from "Spy" library # @return [Array<ShipEngine::Emitter::HttpEvent>] def get_dispatched_events(spy) spy.calls.map { |event| event.args[0] } end def titlecase(str) str.split(/([[:alpha:]]+)/).map(&:capitalize).join end def fuzzy_get_header(header_name_str, headers) headers[header_name_str] || headers[header_name_str.downcase] || headers[titlecase(header_name_str)] end end
26.210526
104
0.714859
b956e2c95155a0d9f9db03a835866114ff8180f2
709
# frozen_string_literal: true require 'spec_helper' describe ArtifactsFinder do let(:project) { create(:project) } describe '#execute' do before do create(:ci_build, :artifacts, project: project) end subject { described_class.new(project, params).execute } context 'with empty params' do let(:params) { {} } it 'returns all artifacts belonging to the project' do expect(subject).to contain_exactly(*project.job_artifacts) end end context 'with sort param' do let(:params) { { sort: 'size_desc' } } it 'sorts the artifacts' do expect(subject).to eq(project.job_artifacts.order_by('size_desc')) end end end end
22.15625
74
0.655853
282dd689ea98f86c126c7ee03fbe7190b37f76fc
817
require "Rover" describe Rover,"#position" do it "should have some intial position" do expect(Rover.new([1,2,"N"]).position).to eq([1,2,"N"]) end it "should raise error if no position is given" do expect{Rover.new.position}.to raise_error(RuntimeError,"Position not found") end end describe Rover,"#move" do it "should raise error if no command is given" do expect{Rover.new([1,2,"N"]).move}.to raise_error(RuntimeError,"no command given") end it "should move foreward " do rov = Rover.new([1,2,"N"]) expect(rov.move("M")).to match_array([1,3,"N"]) end it "should turn right if R is provided" do expect(Rover.new([1,2,"N"]).move("R")).to eq([1,2,"E"]) end it"should turn left if L is provided" do expect(Rover.new([1,2,"N"]).move("L")).to eq([1,2,"W"]) end end
27.233333
85
0.647491
62a1dfa829668cfe49a693e6ae5a36f597750545
149
json.array!(@users) do |user| json.extract! user, :id, :name, :city, :country, :email, :year_of_birth json.url user_url(user, format: :json) end
29.8
73
0.684564
87d4fa00e37e99760ec23dfb0669151d36ce08a7
70
class Crypto::AccountSyncService < Cosmoslike::AccountSyncService end
23.333333
65
0.857143
b9244f5ae9dae00bf5a375c14f81e4915e087eff
987
# frozen_string_literal: true module CKB module Types class LockHashCapacity attr_accessor :capacity, :cells_count, :block_number # @param capacity [String | Integer] integer or hex number # @param cells_count [String | Integer] integer or hex number # @param block_number [String | Integer] integer or hex number def initialize(capacity:, cells_count:, block_number:) @capacity = Utils.to_int(capacity) @cells_count = Utils.to_int(cells_count) @block_number = Utils.to_int(block_number) end def to_h { capacity: Utils.to_hex(@capacity), cells_count: Utils.to_hex(@cells_count), block_number: Utils.to_hex(@block_number) } end def self.from_h(hash) return if hash.nil? new( capacity: hash[:capacity], cells_count: hash[:cells_count], block_number: hash[:block_number] ) end end end end
26.675676
68
0.625127
39346d16458c1336a0c43085a87486e9ab4b0a2c
896
cask 'glyphs' do version '2.6.3,1271' sha256 'be27543241dc5e8c3766c3f14c0edbd696885bade96ebba0feae51525cf94802' url "https://updates.glyphsapp.com/Glyphs#{version.major_minor_patch}-#{version.after_comma}.zip" appcast "https://updates.glyphsapp.com/appcast#{version.major}.xml" name 'Glyphs' homepage 'https://glyphsapp.com/' auto_updates true app 'Glyphs.app' zap trash: [ '~/Library/Application Support/Glyphs', '~/Library/Application Support/com.GeorgSeifert.Glyphs2', '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.georgseifert.glyphs2.sfl*', '~/Library/Caches/com.apple.helpd/SDMHelpData/Other/English/HelpSDMIndexFile/com.GeorgSeifert.Glyphs2.help*', '~/Library/Preferences/com.GeorgSeifert.Glyphs2.plist', ] end
40.727273
156
0.710938
f7faf27c56932d026e36773213168f004d93306a
300
Deface::Override.new( :virtual_path => "spree/admin/users/_lifetime_stats", :name => "add_gdpr_under_lifetime_stats", :insert_after => "[data-hook='admin_user_lifetime_stats']", :original => 'b9f3ea1e30e19d2a4a4f86785b7ba1c2cd6157e5', :partial => "spree/admin/gdpr", :disabled => false )
33.333333
61
0.73
bfc6684375a2449ba066ea0a327348f7cff56ae4
1,520
# Documentation: https://github.com/Homebrew/brew/blob/master/share/doc/homebrew/Formula-Cookbook.md # http://www.rubydoc.info/github/Homebrew/brew/master/Formula # PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST! class Owl2jsonld < Formula desc "" homepage "" url "https://github.com/stain/owl2jsonld/releases/download/0.2.1/owl2jsonld-0.2.1-standalone.jar" version "0.2.1" sha256 "7727f3d97b047e22832c0e472e2a49e41d2319780a045fc667dc990e6b19e705" bottle :unneeded depends_on :java => "1.8+" def install # Need to set JAVA_HOME manually since maven overrides 1.8 with 1.7+ cmd = Language::Java.java_home_cmd("1.8") ENV["JAVA_HOME"] = Utils.popen_read(cmd).chomp libexec.install "owl2jsonld-#{version}-standalone.jar" => "owl2jsonld.jar" bin.write_jar_script libexec/"owl2jsonld.jar", "owl2jsonld" end test do # `test do` will create, run in and delete a temporary directory. # # This test will fail and we won't accept that! For Homebrew/homebrew-core # this will need to be a test that verifies the functionality of the # software. Run the test with `brew test Widoco`. Options passed # to `brew install` such as `--HEAD` also need to be provided to `brew test`. # # The installed folder is not in the path, so use the entire path to any # executables being tested: `system "#{bin}/program", "do", "something"`. assert_match version.to_s, shell_output("#{bin}/owl2jsonld --version") end end
41.081081
100
0.714474
183275f587d95a909c94a5cbd7ffe21d4a38e485
2,139
# Stolen from http://github.com/technoweenie/restful-authentication/tree/master/generators/authenticated/lib # Modified by Dennis Theisen # Thanks a lot ! Rails::Generator::Commands::Create.class_eval do def route(name, path, options = {}) cmd = "map.#{name} '#{path}', :controller => '#{options[:controller]}'" cmd << ", :action => '#{options[:action]}'" if options[:action] add_route(cmd) end def route_root(options = {}) cmd = "map.root :controller => '#{options[:controller]}'" cmd << ", :action => '#{options[:action]}'" if options[:action] add_route(cmd) end private def add_route(cmd) sentinel = 'ActionController::Routing::Routes.draw do |map|' logger.route(cmd) unless options[:pretend] if not File.read("#{RAILS_ROOT}/config/routes.rb").include?(cmd) gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match| "#{match}\n #{cmd}" end end end end end Rails::Generator::Commands::Destroy.class_eval do def route(name, path, options = {}) cmd = "map.#{name} '#{path}', :controller => '#{options[:controller]}'" cmd << ", :action => '#{options[:action]}'" if options[:action] remove_route(cmd) end def route_root(name, path, options = {}) cmd = "map.root :controller => '#{options[:controller]}'" cmd << ", :action => '#{options[:action]}'" if options[:action] remove_route(cmd) end def remove_route(cmd) logger.route(cmd) unless options[:pretend] gsub_file 'config/routes.rb', /\n\s*(#{cmd})/mi, '' end end end Rails::Generator::Commands::List.class_eval do def route(name, path, options = {}) cmd = "map.#{name} '#{path}', :controller => '#{options[:controller]}'" cmd << ", :action => '#{options[:action]}'" if options[:action] logger.route(cmd) end def route_root(name, path, options = {}) cmd = "map.root :controller => '#{options[:controller]}'" cmd << ", :action => '#{options[:action]}'" if options[:action] logger.route(cmd) end end
28.905405
108
0.59093
e8cce4af3bb480b6b82b04fcca8ef566cd664806
1,090
cask 'unity-ios-support-for-editor@2017.2.0b8' do version '2017.2.0b8,c5fc3ca9cbbf' sha256 :no_check url "http://beta.unity3d.com/download/c5fc3ca9cbbf/MacEditorTargetInstaller/UnitySetup-iOS-Support-for-Editor-2017.2.0b8.pkg" name 'iOS Build Support' homepage 'https://unity3d.com/unity/' pkg 'UnitySetup-iOS-Support-for-Editor-2017.2.0b8.pkg' depends_on cask: 'unity@2017.2.0b8' preflight do if File.exist? "/Applications/Unity" FileUtils.move "/Applications/Unity", "/Applications/Unity.temp" end if File.exist? "/Applications/Unity-2017.2.0b8" FileUtils.move "/Applications/Unity-2017.2.0b8", '/Applications/Unity' end end postflight do if File.exist? '/Applications/Unity' FileUtils.move '/Applications/Unity', "/Applications/Unity-2017.2.0b8" end if File.exist? '/Applications/Unity.temp' FileUtils.move '/Applications/Unity.temp', '/Applications/Unity' end end uninstall quit: 'com.unity3d.UnityEditor5.x', delete: '/Applications/Unity-2017.2.0b8/PlaybackEngines/iOSSupport' end
30.277778
127
0.709174
0331ae78375e1eb8516edc23d51d9089f2a61ab7
1,476
require File.dirname(__FILE__) + '/../spec_helper' class AliasObject def value; 5; end def false_value; 6; end end describe "The alias keyword" do before(:each) do @obj = AliasObject.new @meta = class << @obj;self;end end it "creates a new name for an existing method" do @meta.class_eval do alias __value value end @obj.__value.should == 5 end it "adds the new method to the list of methods" do original_methods = @obj.methods @meta.class_eval do alias __value value end (@obj.methods - original_methods).should == ["__value"] end it "adds the new method to the list of public methods" do original_methods = @obj.public_methods @meta.class_eval do alias __value value end (@obj.public_methods - original_methods).should == ["__value"] end it "overwrites an existing method with the target name" do @meta.class_eval do alias false_value value end @obj.false_value.should == 5 end it "is reversible" do @meta.class_eval do alias __value value alias value false_value end @obj.value.should == 6 @meta.class_eval do alias value __value end @obj.value.should == 5 end it "operates on the object's metaclass when used in instance_eval" do @obj.instance_eval do alias __value value end @obj.__value.should == 5 lambda { AliasObject.new.__value }.should raise_error(NoMethodError) end end
22.363636
72
0.668699
eda9ab4ea3c8b556542482dc7768e5d5e159392a
294
class DropHdfsFileReferencesAndAssociatedEvents < ActiveRecord::Migration def up drop_table :hdfs_file_references end def down create_table :hdfs_file_references do |t| t.string :path, :limit => 2048 t.integer :hadoop_instance_id t.timestamps end end end
21
73
0.72449
622e4f242221660b975178cfa6ffe316f02733a7
1,443
module Dawanda # = OAuth # # Provides access to sesitive user data class OAuth API_PREFIX = '/api/v1/oauth' def self.connect key, secret @@consumer = Dawanda::OAuth.create_consumer key, secret @@request_token = @@consumer.get_request_token end def self.rebuild key, secret, params @@consumer = Dawanda::OAuth.create_consumer key, secret @@request_token = ::OAuth::RequestToken.from_hash(@@consumer, params) @@request_token.consumer.options.merge!({:oauth_verifier => params[:oauth_verifier]}) @@access_token = @@request_token.get_access_token end def self.authorize_url @@request_token.authorize_url end def self.access_token @@access_token ||= nil end def self.access_token=(access_token) @@access_token = access_token end def self.get(url, options={}) Dawanda::Response.new(@@access_token.get(url).body) end def self.user Dawanda::User.new(Dawanda::OAuth.get("#{API_PREFIX}/users.json").result) end private def self.create_consumer key, secret @@consumer = ::OAuth::Consumer.new(key, secret, { :site => "http://#{Dawanda.country}.#{Dawanda.domain}", :request_token_path => "/oauth/request_token", :access_token_path => "/oauth/access_token", :authorize_path => "/oauth/authorize" }) end end end
27.226415
91
0.63271
4a8d38a44f6719a12fde70d21c52aab099b35053
2,625
require 'rails_helper' describe BypassParamsManager do describe '#present?' do context 'empty params' do it 'returns false' do expect(described_class.new(empty_params).present?).to be false end end context 'invalid bypass params' do it 'returns true' do expect(described_class.new(invalid_message_no_bypass_params).present?).to be true end end end describe '#valid?' do context 'empty params' do it 'returns false' do expect(described_class.new(empty_params).valid?).to be false end end context 'valid params' do it 'returns true' do expect(described_class.new(valid_bypass_params).valid?).to be true end end context 'invalid params' do it 'returns false' do expect(described_class.new(invalid_message_no_bypass_params).valid?).to be false end end end describe '#approval_requested?' do context 'empty params' do it 'returns false' do expect(described_class.new(empty_params).approval_requested?).to be false end end context 'invalid params' do it 'returns false' do expect(described_class.new(invalid_message_no_bypass_params).approval_requested?).to be false end end context 'valid params approval requested' do it 'returns true' do expect(described_class.new(valid_no_bypass_params).approval_requested?).to be true end end context 'valid params no approval requested' do it 'returns false' do expect(described_class.new(valid_bypass_params).approval_requested?).to be false end end end def empty_params HashWithIndifferentAccess.new( { other_keys: 'other_data' }) end def valid_bypass_params HashWithIndifferentAccess.new( { bypass_approval: { press_office_approval_required: 'false', bypass_message: 'section 12' } }) end def valid_no_bypass_params HashWithIndifferentAccess.new( { bypass_approval: { press_office_approval_required: 'true', bypass_message: '' } }) end def invalid_message_no_bypass_params HashWithIndifferentAccess.new( { bypass_approval: { press_office_approval_required: 'true', bypass_message: 'section 12' } }) end def invalid_no_message_bypass_params HashWithIndifferentAccess.new( { bypass_approval: { press_office_approval_required: 'false', bypass_message: '' } }) end end
24.082569
101
0.651048
018fd4c1b2def422babf82935d0efd53addc3d39
1,854
# -*- encoding: utf-8 -*- # stub: logstash-output-udp 3.0.6 ruby lib Gem::Specification.new do |s| s.name = "logstash-output-udp".freeze s.version = "3.0.6" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "logstash_group" => "output", "logstash_plugin" => "true" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["Elastic".freeze] s.date = "2018-04-06" s.description = "This gem is a Logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/logstash-plugin install gemname. This gem is not a stand-alone program".freeze s.email = "info@elastic.co".freeze s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html".freeze s.licenses = ["Apache License (2.0)".freeze] s.rubygems_version = "2.6.13".freeze s.summary = "Sends events over UDP".freeze s.installed_by_version = "2.6.13" 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_runtime_dependency(%q<logstash-core-plugin-api>.freeze, ["<= 2.99", ">= 1.60"]) s.add_runtime_dependency(%q<logstash-codec-json>.freeze, [">= 0"]) s.add_development_dependency(%q<logstash-devutils>.freeze, [">= 0"]) else s.add_dependency(%q<logstash-core-plugin-api>.freeze, ["<= 2.99", ">= 1.60"]) s.add_dependency(%q<logstash-codec-json>.freeze, [">= 0"]) s.add_dependency(%q<logstash-devutils>.freeze, [">= 0"]) end else s.add_dependency(%q<logstash-core-plugin-api>.freeze, ["<= 2.99", ">= 1.60"]) s.add_dependency(%q<logstash-codec-json>.freeze, [">= 0"]) s.add_dependency(%q<logstash-devutils>.freeze, [">= 0"]) end end
46.35
208
0.675836
e8cdeaa0db4a3de233781683f1e3767189b06064
3,265
# -*- encoding: utf-8 -*- # # Author:: SAWANOBORI Yukihiko <sawanoboriyu@higanworks.com>) # # Copyright (C) 2015, HiganWorks LLC # # 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. # Usage: # # puts your recipes to` apply/` directory. # # An example of .kitchen.yml. # # --- # driver: # name: vagrant # # provisioner: # name: chef_apply # # platforms: # - name: ubuntu-12.04 # - name: centos-6.4 # # suites: # - name: default # run_list: # - recipe1 # - recipe2 # # # The chef-apply runs twice below. # # chef-apply apply/recipe1.rb # chef-apply apply/recipe2.rb require "kitchen/provisioner/chef_base" module Kitchen module Provisioner # Chef Apply provisioner. # # @author SAWANOBORI Yukihiko <sawanoboriyu@higanworks.com>) class ChefApply < ChefBase kitchen_provisioner_api_version 2 plugin_version Kitchen::VERSION default_config :chef_apply_path do |provisioner| provisioner .remote_path_join(%W{#{provisioner[:chef_omnibus_root]} bin chef-apply}) .tap { |path| path.concat(".bat") if provisioner.windows_os? } end default_config :apply_path do |provisioner| provisioner.calculate_path("apply") end expand_path_for :apply_path # (see ChefBase#create_sandbox) def create_sandbox @sandbox_path = Dir.mktmpdir("#{instance.name}-sandbox-") File.chmod(0755, sandbox_path) info("Preparing files for transfer") debug("Creating local sandbox in #{sandbox_path}") prepare_json prepare(:apply) end # (see ChefBase#init_command) def init_command dirs = %w{ apply }.sort.map { |dir| remote_path_join(config[:root_path], dir) } vars = if powershell_shell? init_command_vars_for_powershell(dirs) else init_command_vars_for_bourne(dirs) end prefix_command(shell_code_from_file(vars, "chef_base_init_command")) end # (see ChefSolo#run_command) def run_command level = config[:log_level] lines = [] config[:run_list].map do |recipe| cmd = sudo(config[:chef_apply_path]).dup .tap { |str| str.insert(0, "& ") if powershell_shell? } args = [ "apply/#{recipe}.rb", "--log_level #{level}", "--no-color", ] args << "--logfile #{config[:log_file]}" if config[:log_file] lines << wrap_shell_code( [cmd, *args].join(" ") .tap { |str| str.insert(0, reload_ps1_path) if windows_os? } ) end prefix_command(lines.join("\n")) end end end end
26.762295
101
0.616845
28189db78373dd92843247fac34014c971f62ce4
2,071
require 'active_merchant' require 'support/gateway_support' class SSLVerify def initialize @gateways = GatewaySupport.new.gateways end def test_gateways success, failed, missing, errored, disabled = [], [], [], [], [] puts "Verifying #{@gateways.count} SSL certificates\n\n" @gateways.each do |g| if !g.live_url missing << g unless g.abstract_class next end if !g.ssl_strict disabled << g end uri = URI.parse(g.live_url) result,message = ssl_verify_peer?(uri) case result when :success print '.' success << g when :fail print 'F' failed << {:gateway => g, :message => message} when :error print 'E' errored << {:gateway => g, :message => message} end end puts "\n\n\nFailed Gateways:" failed.each do |f| puts "#{f[:gateway].name} - #{f[:message]}" end puts "\n\nError Gateways:" errored.each do |e| puts "#{e[:gateway].name} - #{e[:message]}" end if missing.size > 0 puts "\n\nGateways missing live_url:" missing.each do |m| puts m.name end end if disabled.size > 0 puts "\n\nGateways with ssl_strict=false:" disabled.each do |d| puts d.name end end end def try_host(http, path) http.get(path) rescue Net::HTTPBadResponse, EOFError, SocketError http.post(path, '') end def ssl_verify_peer?(uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.ca_file = File.dirname(__FILE__) + '/certs/cacert.pem' http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.open_timeout = 60 http.read_timeout = 60 if uri.path.blank? try_host(http, '/') else try_host(http, uri.path) end return :success rescue OpenSSL::SSL::SSLError => ex return :fail, ex.inspect rescue Net::HTTPBadResponse, Errno::ETIMEDOUT, EOFError, SocketError, Errno::ECONNREFUSED, Timeout::Error => ex return :error, ex.inspect end end
22.268817
113
0.597779
382b93f2d2a540b9aa44dd5c19f05201d95d1f8f
645
require 'rails_helper' describe "the add an addition process" do it "adds an addition to a story" do visit stories_path click_on "Add a New Story" fill_in 'Title', :with => "Deez Nuts" fill_in 'Starter sentence for your story', :with => "There was a man with peanuts." fill_in 'Your Name', :with => "Dee" click_on 'Submit' click_on "Deez Nuts" click_on "Add to this story!" fill_in 'Make Your Addition (only one sentence!)', :with => "So spoopy!" fill_in 'Your Name', :with => "Steve" click_on 'Submit' click_on 'Delete Contribution' expect(page).to_not have_content "So spoopy!" end end
32.25
87
0.666667
ac054fcf638c77a274be191d0bd5e305ddd874ba
423
Gem::Specification.new do |s| s.name = 'testrail' s.version = '0.0.1' s.date = '2016-09-07' s.summary = "TestRail Gem-ified" s.description = "Gem wrapper for: https://github.com/gurock/testrail-api/tree/master/ruby" s.authors = ["Nate Reynolds"] s.email = 'nate@n8r.us' s.files = Dir['lib/**/*.rb'] s.homepage = 'https://github.com/nvreynolds/testrail-gemified' end
35.25
92
0.600473
6ac52abb8b84a9c37b4603b919ef0d5d9c51b9a1
784
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module SampleApp class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.2 # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. #Include the authenticity token in remote forms config.action_view.embed_authenticity_token_in_remote_forms = true end end
34.086957
82
0.772959
184db7516eb09da0f2def12375a6d27c73a4e701
9,598
# frozen_string_literal: true module Ci # This class responsible for assigning # proper pending build to runner on runner API request class RegisterJobService attr_reader :runner, :metrics TEMPORARY_LOCK_TIMEOUT = 3.seconds Result = Struct.new(:build, :build_json, :valid?) ## # The queue depth limit number has been determined by observing 95 # percentile of effective queue depth on gitlab.com. This is only likely to # affect 5% of the worst case scenarios. MAX_QUEUE_DEPTH = 45 def initialize(runner) @runner = runner @metrics = ::Gitlab::Ci::Queue::Metrics.new(runner) end def execute(params = {}) db_all_caught_up = ::Ci::Runner.sticking.all_caught_up?(:runner, runner.id) @metrics.increment_queue_operation(:queue_attempt) result = @metrics.observe_queue_time(:process, @runner.runner_type) do process_queue(params) end # Since we execute this query against replica it might lead to false-positive # We might receive the positive response: "hi, we don't have any more builds for you". # This might not be true. If our DB replica is not up-to date with when runner event was generated # we might still have some CI builds to be picked. Instead we should say to runner: # "Hi, we don't have any more builds now, but not everything is right anyway, so try again". # Runner will retry, but again, against replica, and again will check if replication lag did catch-up. if !db_all_caught_up && !result.build metrics.increment_queue_operation(:queue_replication_lag) ::Ci::RegisterJobService::Result.new(nil, false) # rubocop:disable Cop/AvoidReturnFromBlocks else result end end private def process_queue(params) valid = true depth = 0 each_build(params) do |build| depth += 1 @metrics.increment_queue_operation(:queue_iteration) if depth > max_queue_depth @metrics.increment_queue_operation(:queue_depth_limit) valid = false break end # We read builds from replicas # It is likely that some other concurrent connection is processing # a given build at a given moment. To avoid an expensive compute # we perform an exclusive lease on Redis to acquire a build temporarily unless acquire_temporary_lock(build.id) @metrics.increment_queue_operation(:build_temporary_locked) # We failed to acquire lock # - our queue is not complete as some resources are locked temporarily # - we need to re-process it again to ensure that all builds are handled valid = false next end result = process_build(build, params) next unless result if result.valid? @metrics.register_success(result.build) @metrics.observe_queue_depth(:found, depth) return result # rubocop:disable Cop/AvoidReturnFromBlocks else # The usage of valid: is described in # handling of ActiveRecord::StaleObjectError valid = false end end @metrics.increment_queue_operation(:queue_conflict) unless valid @metrics.observe_queue_depth(:conflict, depth) unless valid @metrics.observe_queue_depth(:not_found, depth) if valid @metrics.register_failure Result.new(nil, nil, valid) end # rubocop: disable CodeReuse/ActiveRecord def each_build(params, &blk) queue = ::Ci::Queue::BuildQueueService.new(runner) builds = begin if runner.instance_type? queue.builds_for_shared_runner elsif runner.group_type? queue.builds_for_group_runner else queue.builds_for_project_runner end end if runner.ref_protected? builds = queue.builds_for_protected_runner(builds) end # pick builds that does not have other tags than runner's one builds = queue.builds_matching_tag_ids(builds, runner.tags.ids) # pick builds that have at least one tag unless runner.run_untagged? builds = queue.builds_with_any_tags(builds) end # pick builds that older than specified age if params.key?(:job_age) builds = queue.builds_queued_before(builds, params[:job_age].seconds.ago) end build_ids = retrieve_queue(-> { queue.execute(builds) }) @metrics.observe_queue_size(-> { build_ids.size }, @runner.runner_type) build_ids.each { |build_id| yield Ci::Build.find(build_id) } end # rubocop: enable CodeReuse/ActiveRecord def retrieve_queue(queue_query_proc) ## # We want to reset a load balancing session to discard the side # effects of writes that could have happened prior to this moment. # ::Gitlab::Database::LoadBalancing::Session.clear_session @metrics.observe_queue_time(:retrieve, @runner.runner_type) do queue_query_proc.call end end def process_build(build, params) unless build.pending? @metrics.increment_queue_operation(:build_not_pending) return end if runner.matches_build?(build) @metrics.increment_queue_operation(:build_can_pick) else @metrics.increment_queue_operation(:build_not_pick) return end # In case when 2 runners try to assign the same build, second runner will be declined # with StateMachines::InvalidTransition or StaleObjectError when doing run! or save method. if assign_runner!(build, params) present_build!(build) end rescue ActiveRecord::StaleObjectError # We are looping to find another build that is not conflicting # It also indicates that this build can be picked and passed to runner. # If we don't do it, basically a bunch of runners would be competing for a build # and thus we will generate a lot of 409. This will increase # the number of generated requests, also will reduce significantly # how many builds can be picked by runner in a unit of time. # In case we hit the concurrency-access lock, # we still have to return 409 in the end, # to make sure that this is properly handled by runner. @metrics.increment_queue_operation(:build_conflict_lock) Result.new(nil, nil, false) rescue StateMachines::InvalidTransition @metrics.increment_queue_operation(:build_conflict_transition) Result.new(nil, nil, false) rescue StandardError => ex @metrics.increment_queue_operation(:build_conflict_exception) # If an error (e.g. GRPC::DeadlineExceeded) occurred constructing # the result, consider this as a failure to be retried. scheduler_failure!(build) track_exception_for_build(ex, build) # skip, and move to next one nil end def max_queue_depth MAX_QUEUE_DEPTH end # Force variables evaluation to occur now def present_build!(build) # We need to use the presenter here because Gitaly calls in the presenter # may fail, and we need to ensure the response has been generated. presented_build = ::Ci::BuildRunnerPresenter.new(build) # rubocop:disable CodeReuse/Presenter build_json = ::API::Entities::Ci::JobRequest::Response.new(presented_build).to_json Result.new(build, build_json, true) end def assign_runner!(build, params) build.runner_id = runner.id build.runner_session_attributes = params[:session] if params[:session].present? failure_reason, _ = pre_assign_runner_checks.find { |_, check| check.call(build, params) } if failure_reason @metrics.increment_queue_operation(:runner_pre_assign_checks_failed) build.drop!(failure_reason) else @metrics.increment_queue_operation(:runner_pre_assign_checks_success) build.run! end !failure_reason end def acquire_temporary_lock(build_id) return true unless Feature.enabled?(:ci_register_job_temporary_lock, runner) key = "build/register/#{build_id}" Gitlab::ExclusiveLease .new(key, timeout: TEMPORARY_LOCK_TIMEOUT.to_i) .try_obtain end def scheduler_failure!(build) Gitlab::OptimisticLocking.retry_lock(build, 3, name: 'register_job_scheduler_failure') do |subject| subject.drop!(:scheduler_failure) end rescue StandardError => ex build.doom! # This requires extra exception, otherwise we would loose information # why we cannot perform `scheduler_failure` track_exception_for_build(ex, build) end def track_exception_for_build(ex, build) Gitlab::ErrorTracking.track_exception(ex, build_id: build.id, build_name: build.name, build_stage: build.stage, pipeline_id: build.pipeline_id, project_id: build.project_id ) end def pre_assign_runner_checks { missing_dependency_failure: -> (build, _) { !build.has_valid_build_dependencies? }, runner_unsupported: -> (build, params) { !build.supported_runner?(params.dig(:info, :features)) }, archived_failure: -> (build, _) { build.archived? }, project_deleted: -> (build, _) { build.project.pending_delete? }, builds_disabled: -> (build, _) { !build.project.builds_enabled? }, user_blocked: -> (build, _) { build.user&.blocked? } } end end end Ci::RegisterJobService.prepend_mod_with('Ci::RegisterJobService')
34.035461
108
0.680663
2629618938bf3b804229462d449eef915224a07a
3,708
# This file is copied to spec/ when you run 'rails generate rspec:install' require 'spec_helper' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) # Prevent database truncation if the environment is production abort("The Rails environment is running in production mode!") if Rails.env.production? require 'rspec/rails' # Add additional requires below this line. Rails is not loaded until this point! require 'support/factory_bot' require 'capybara/rails' # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. # # The following line is provided for convenience purposes. It has the downside # of increasing the boot-up time by auto-requiring all files in the support # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. # Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f } # Checks for pending migrations and applies them before tests are run. # If you are not using ActiveRecord, you can remove these lines. begin ActiveRecord::Migration.maintain_test_schema! rescue ActiveRecord::PendingMigrationError => e puts e.to_s.strip exit 1 end RSpec.configure do |config| # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" config.filter_run focus: true config.run_all_when_everything_filtered = true config.use_transactional_fixtures = false config.before(:suite) do DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.strategy = :transaction end config.before(:each, type: :feature) do # :rack_test driver's Rack app under test shares database connection # with the specs, so continue to use transaction strategy for speed. driver_shares_db_connection_with_specs = Capybara.current_driver == :rack_test unless driver_shares_db_connection_with_specs # Driver is probably for an external browser with an app # under test that does *not* share a database connection with the # specs, so use truncation strategy. DatabaseCleaner.strategy = :truncation end end config.before(:each) do DatabaseCleaner.start end config.append_after(:each) do DatabaseCleaner.clean end # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, :type => :controller do # # ... # end # # The different available types are documented in the features, such as in # https://relishapp.com/rspec/rspec-rails/docs config.infer_spec_type_from_file_location! # Filter lines from Rails gems in backtraces. config.filter_rails_from_backtrace! # arbitrary gems may also be filtered via: # config.filter_gems_from_backtrace("gem name") end Shoulda::Matchers.configure do |config| config.integrate do |with| with.test_framework :rspec with.library :rails end end
37.08
86
0.747573
7925df14b5a6542767e52af507399270f44b99bd
38,314
# frozen_string_literal: true # Copyright 2021 Google LLC # # 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 # # https://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. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! require "google/cloud/errors" require "google/cloud/dialogflow/cx/v3/security_settings_pb" module Google module Cloud module Dialogflow module CX module V3 module SecuritySettingsService ## # Client for the SecuritySettingsService service. # # Service for managing security settings for Dialogflow. # class Client include Paths # @private attr_reader :security_settings_service_stub ## # Configure the SecuritySettingsService Client class. # # See {::Google::Cloud::Dialogflow::CX::V3::SecuritySettingsService::Client::Configuration} # for a description of the configuration fields. # # @example # # # Modify the configuration for all SecuritySettingsService clients # ::Google::Cloud::Dialogflow::CX::V3::SecuritySettingsService::Client.configure do |config| # config.timeout = 10.0 # end # # @yield [config] Configure the Client client. # @yieldparam config [Client::Configuration] # # @return [Client::Configuration] # def self.configure @configure ||= begin namespace = ["Google", "Cloud", "Dialogflow", "CX", "V3"] parent_config = while namespace.any? parent_name = namespace.join "::" parent_const = const_get parent_name break parent_const.configure if parent_const.respond_to? :configure namespace.pop end default_config = Client::Configuration.new parent_config default_config.timeout = 60.0 default_config.retry_policy = { initial_delay: 0.1, max_delay: 60.0, multiplier: 1.3, retry_codes: [14] } default_config end yield @configure if block_given? @configure end ## # Configure the SecuritySettingsService Client instance. # # The configuration is set to the derived mode, meaning that values can be changed, # but structural changes (adding new fields, etc.) are not allowed. Structural changes # should be made on {Client.configure}. # # See {::Google::Cloud::Dialogflow::CX::V3::SecuritySettingsService::Client::Configuration} # for a description of the configuration fields. # # @yield [config] Configure the Client client. # @yieldparam config [Client::Configuration] # # @return [Client::Configuration] # def configure yield @config if block_given? @config end ## # Create a new SecuritySettingsService client object. # # @example # # # Create a client using the default configuration # client = ::Google::Cloud::Dialogflow::CX::V3::SecuritySettingsService::Client.new # # # Create a client using a custom configuration # client = ::Google::Cloud::Dialogflow::CX::V3::SecuritySettingsService::Client.new do |config| # config.timeout = 10.0 # end # # @yield [config] Configure the SecuritySettingsService client. # @yieldparam config [Client::Configuration] # def initialize # These require statements are intentionally placed here to initialize # the gRPC module only when it's required. # See https://github.com/googleapis/toolkit/issues/446 require "gapic/grpc" require "google/cloud/dialogflow/cx/v3/security_settings_services_pb" # Create the configuration object @config = Configuration.new Client.configure # Yield the configuration if needed yield @config if block_given? # Create credentials credentials = @config.credentials # Use self-signed JWT if the endpoint is unchanged from default, # but only if the default endpoint does not have a region prefix. enable_self_signed_jwt = @config.endpoint == Client.configure.endpoint && !@config.endpoint.split(".").first.include?("-") credentials ||= Credentials.default scope: @config.scope, enable_self_signed_jwt: enable_self_signed_jwt if credentials.is_a?(::String) || credentials.is_a?(::Hash) credentials = Credentials.new credentials, scope: @config.scope end @quota_project_id = @config.quota_project @quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id @security_settings_service_stub = ::Gapic::ServiceStub.new( ::Google::Cloud::Dialogflow::CX::V3::SecuritySettingsService::Stub, credentials: credentials, endpoint: @config.endpoint, channel_args: @config.channel_args, interceptors: @config.interceptors ) end # Service calls ## # Create security settings in the specified location. # # @overload create_security_settings(request, options = nil) # Pass arguments to `create_security_settings` via a request object, either of type # {::Google::Cloud::Dialogflow::CX::V3::CreateSecuritySettingsRequest} or an equivalent Hash. # # @param request [::Google::Cloud::Dialogflow::CX::V3::CreateSecuritySettingsRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload create_security_settings(parent: nil, security_settings: nil) # Pass arguments to `create_security_settings` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param parent [::String] # Required. The location to create an {::Google::Cloud::Dialogflow::CX::V3::SecuritySettings SecuritySettings} for. # Format: `projects/<Project ID>/locations/<Location ID>`. # @param security_settings [::Google::Cloud::Dialogflow::CX::V3::SecuritySettings, ::Hash] # Required. The security settings to create. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Google::Cloud::Dialogflow::CX::V3::SecuritySettings] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Google::Cloud::Dialogflow::CX::V3::SecuritySettings] # # @raise [::Google::Cloud::Error] if the RPC is aborted. # def create_security_settings request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Dialogflow::CX::V3::CreateSecuritySettingsRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.create_security_settings.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::Dialogflow::CX::V3::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "parent" => request.parent } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.create_security_settings.timeout, metadata: metadata, retry_policy: @config.rpcs.create_security_settings.retry_policy options.apply_defaults timeout: @config.timeout, metadata: @config.metadata, retry_policy: @config.retry_policy @security_settings_service_stub.call_rpc :create_security_settings, request, options: options do |response, operation| yield response, operation if block_given? return response end rescue ::GRPC::BadStatus => e raise ::Google::Cloud::Error.from_error(e) end ## # Retrieves the specified {::Google::Cloud::Dialogflow::CX::V3::SecuritySettings SecuritySettings}. # The returned settings may be stale by up to 1 minute. # # @overload get_security_settings(request, options = nil) # Pass arguments to `get_security_settings` via a request object, either of type # {::Google::Cloud::Dialogflow::CX::V3::GetSecuritySettingsRequest} or an equivalent Hash. # # @param request [::Google::Cloud::Dialogflow::CX::V3::GetSecuritySettingsRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload get_security_settings(name: nil) # Pass arguments to `get_security_settings` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param name [::String] # Required. Resource name of the settings. # Format: `projects/<Project ID>/locations/<Location # ID>/securitySettings/<security settings ID>`. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Google::Cloud::Dialogflow::CX::V3::SecuritySettings] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Google::Cloud::Dialogflow::CX::V3::SecuritySettings] # # @raise [::Google::Cloud::Error] if the RPC is aborted. # def get_security_settings request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Dialogflow::CX::V3::GetSecuritySettingsRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.get_security_settings.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::Dialogflow::CX::V3::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "name" => request.name } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.get_security_settings.timeout, metadata: metadata, retry_policy: @config.rpcs.get_security_settings.retry_policy options.apply_defaults timeout: @config.timeout, metadata: @config.metadata, retry_policy: @config.retry_policy @security_settings_service_stub.call_rpc :get_security_settings, request, options: options do |response, operation| yield response, operation if block_given? return response end rescue ::GRPC::BadStatus => e raise ::Google::Cloud::Error.from_error(e) end ## # Updates the specified {::Google::Cloud::Dialogflow::CX::V3::SecuritySettings SecuritySettings}. # # @overload update_security_settings(request, options = nil) # Pass arguments to `update_security_settings` via a request object, either of type # {::Google::Cloud::Dialogflow::CX::V3::UpdateSecuritySettingsRequest} or an equivalent Hash. # # @param request [::Google::Cloud::Dialogflow::CX::V3::UpdateSecuritySettingsRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload update_security_settings(security_settings: nil, update_mask: nil) # Pass arguments to `update_security_settings` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param security_settings [::Google::Cloud::Dialogflow::CX::V3::SecuritySettings, ::Hash] # Required. [SecuritySettings] object that contains values for each of the # fields to update. # @param update_mask [::Google::Protobuf::FieldMask, ::Hash] # Required. The mask to control which fields get updated. If the mask is not present, # all fields will be updated. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Google::Cloud::Dialogflow::CX::V3::SecuritySettings] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Google::Cloud::Dialogflow::CX::V3::SecuritySettings] # # @raise [::Google::Cloud::Error] if the RPC is aborted. # def update_security_settings request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Dialogflow::CX::V3::UpdateSecuritySettingsRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.update_security_settings.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::Dialogflow::CX::V3::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "security_settings.name" => request.security_settings.name } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.update_security_settings.timeout, metadata: metadata, retry_policy: @config.rpcs.update_security_settings.retry_policy options.apply_defaults timeout: @config.timeout, metadata: @config.metadata, retry_policy: @config.retry_policy @security_settings_service_stub.call_rpc :update_security_settings, request, options: options do |response, operation| yield response, operation if block_given? return response end rescue ::GRPC::BadStatus => e raise ::Google::Cloud::Error.from_error(e) end ## # Returns the list of all security settings in the specified location. # # @overload list_security_settings(request, options = nil) # Pass arguments to `list_security_settings` via a request object, either of type # {::Google::Cloud::Dialogflow::CX::V3::ListSecuritySettingsRequest} or an equivalent Hash. # # @param request [::Google::Cloud::Dialogflow::CX::V3::ListSecuritySettingsRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload list_security_settings(parent: nil, page_size: nil, page_token: nil) # Pass arguments to `list_security_settings` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param parent [::String] # Required. The location to list all security settings for. # Format: `projects/<Project ID>/locations/<Location ID>`. # @param page_size [::Integer] # The maximum number of items to return in a single page. By default 20 and # at most 100. # @param page_token [::String] # The next_page_token value returned from a previous list request. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Gapic::PagedEnumerable<::Google::Cloud::Dialogflow::CX::V3::SecuritySettings>] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Gapic::PagedEnumerable<::Google::Cloud::Dialogflow::CX::V3::SecuritySettings>] # # @raise [::Google::Cloud::Error] if the RPC is aborted. # def list_security_settings request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Dialogflow::CX::V3::ListSecuritySettingsRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.list_security_settings.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::Dialogflow::CX::V3::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "parent" => request.parent } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.list_security_settings.timeout, metadata: metadata, retry_policy: @config.rpcs.list_security_settings.retry_policy options.apply_defaults timeout: @config.timeout, metadata: @config.metadata, retry_policy: @config.retry_policy @security_settings_service_stub.call_rpc :list_security_settings, request, options: options do |response, operation| response = ::Gapic::PagedEnumerable.new @security_settings_service_stub, :list_security_settings, request, response, operation, options yield response, operation if block_given? return response end rescue ::GRPC::BadStatus => e raise ::Google::Cloud::Error.from_error(e) end ## # Deletes the specified {::Google::Cloud::Dialogflow::CX::V3::SecuritySettings SecuritySettings}. # # @overload delete_security_settings(request, options = nil) # Pass arguments to `delete_security_settings` via a request object, either of type # {::Google::Cloud::Dialogflow::CX::V3::DeleteSecuritySettingsRequest} or an equivalent Hash. # # @param request [::Google::Cloud::Dialogflow::CX::V3::DeleteSecuritySettingsRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload delete_security_settings(name: nil) # Pass arguments to `delete_security_settings` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param name [::String] # Required. The name of the {::Google::Cloud::Dialogflow::CX::V3::SecuritySettings SecuritySettings} to delete. # Format: `projects/<Project ID>/locations/<Location # ID>/securitySettings/<Security Settings ID>`. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Google::Protobuf::Empty] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Google::Protobuf::Empty] # # @raise [::Google::Cloud::Error] if the RPC is aborted. # def delete_security_settings request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Dialogflow::CX::V3::DeleteSecuritySettingsRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.delete_security_settings.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::Dialogflow::CX::V3::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "name" => request.name } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.delete_security_settings.timeout, metadata: metadata, retry_policy: @config.rpcs.delete_security_settings.retry_policy options.apply_defaults timeout: @config.timeout, metadata: @config.metadata, retry_policy: @config.retry_policy @security_settings_service_stub.call_rpc :delete_security_settings, request, options: options do |response, operation| yield response, operation if block_given? return response end rescue ::GRPC::BadStatus => e raise ::Google::Cloud::Error.from_error(e) end ## # Configuration class for the SecuritySettingsService API. # # This class represents the configuration for SecuritySettingsService, # providing control over timeouts, retry behavior, logging, transport # parameters, and other low-level controls. Certain parameters can also be # applied individually to specific RPCs. See # {::Google::Cloud::Dialogflow::CX::V3::SecuritySettingsService::Client::Configuration::Rpcs} # for a list of RPCs that can be configured independently. # # Configuration can be applied globally to all clients, or to a single client # on construction. # # @example # # # Modify the global config, setting the timeout for # # create_security_settings to 20 seconds, # # and all remaining timeouts to 10 seconds. # ::Google::Cloud::Dialogflow::CX::V3::SecuritySettingsService::Client.configure do |config| # config.timeout = 10.0 # config.rpcs.create_security_settings.timeout = 20.0 # end # # # Apply the above configuration only to a new client. # client = ::Google::Cloud::Dialogflow::CX::V3::SecuritySettingsService::Client.new do |config| # config.timeout = 10.0 # config.rpcs.create_security_settings.timeout = 20.0 # end # # @!attribute [rw] endpoint # The hostname or hostname:port of the service endpoint. # Defaults to `"dialogflow.googleapis.com"`. # @return [::String] # @!attribute [rw] credentials # Credentials to send with calls. You may provide any of the following types: # * (`String`) The path to a service account key file in JSON format # * (`Hash`) A service account key as a Hash # * (`Google::Auth::Credentials`) A googleauth credentials object # (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html)) # * (`Signet::OAuth2::Client`) A signet oauth2 client object # (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html)) # * (`GRPC::Core::Channel`) a gRPC channel with included credentials # * (`GRPC::Core::ChannelCredentials`) a gRPC credentails object # * (`nil`) indicating no credentials # @return [::Object] # @!attribute [rw] scope # The OAuth scopes # @return [::Array<::String>] # @!attribute [rw] lib_name # The library name as recorded in instrumentation and logging # @return [::String] # @!attribute [rw] lib_version # The library version as recorded in instrumentation and logging # @return [::String] # @!attribute [rw] channel_args # Extra parameters passed to the gRPC channel. Note: this is ignored if a # `GRPC::Core::Channel` object is provided as the credential. # @return [::Hash] # @!attribute [rw] interceptors # An array of interceptors that are run before calls are executed. # @return [::Array<::GRPC::ClientInterceptor>] # @!attribute [rw] timeout # The call timeout in seconds. # @return [::Numeric] # @!attribute [rw] metadata # Additional gRPC headers to be sent with the call. # @return [::Hash{::Symbol=>::String}] # @!attribute [rw] retry_policy # The retry policy. The value is a hash with the following keys: # * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds. # * `:max_delay` (*type:* `Numeric`) - The max delay in seconds. # * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier. # * `:retry_codes` (*type:* `Array<String>`) - The error codes that should # trigger a retry. # @return [::Hash] # @!attribute [rw] quota_project # A separate project against which to charge quota. # @return [::String] # class Configuration extend ::Gapic::Config config_attr :endpoint, "dialogflow.googleapis.com", ::String config_attr :credentials, nil do |value| allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil] allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC allowed.any? { |klass| klass === value } end config_attr :scope, nil, ::String, ::Array, nil config_attr :lib_name, nil, ::String, nil config_attr :lib_version, nil, ::String, nil config_attr(:channel_args, { "grpc.service_config_disable_resolution" => 1 }, ::Hash, nil) config_attr :interceptors, nil, ::Array, nil config_attr :timeout, nil, ::Numeric, nil config_attr :metadata, nil, ::Hash, nil config_attr :retry_policy, nil, ::Hash, ::Proc, nil config_attr :quota_project, nil, ::String, nil # @private def initialize parent_config = nil @parent_config = parent_config unless parent_config.nil? yield self if block_given? end ## # Configurations for individual RPCs # @return [Rpcs] # def rpcs @rpcs ||= begin parent_rpcs = nil parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config.respond_to?(:rpcs) Rpcs.new parent_rpcs end end ## # Configuration RPC class for the SecuritySettingsService API. # # Includes fields providing the configuration for each RPC in this service. # Each configuration object is of type `Gapic::Config::Method` and includes # the following configuration fields: # # * `timeout` (*type:* `Numeric`) - The call timeout in seconds # * `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers # * `retry_policy (*type:* `Hash`) - The retry policy. The policy fields # include the following keys: # * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds. # * `:max_delay` (*type:* `Numeric`) - The max delay in seconds. # * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier. # * `:retry_codes` (*type:* `Array<String>`) - The error codes that should # trigger a retry. # class Rpcs ## # RPC-specific configuration for `create_security_settings` # @return [::Gapic::Config::Method] # attr_reader :create_security_settings ## # RPC-specific configuration for `get_security_settings` # @return [::Gapic::Config::Method] # attr_reader :get_security_settings ## # RPC-specific configuration for `update_security_settings` # @return [::Gapic::Config::Method] # attr_reader :update_security_settings ## # RPC-specific configuration for `list_security_settings` # @return [::Gapic::Config::Method] # attr_reader :list_security_settings ## # RPC-specific configuration for `delete_security_settings` # @return [::Gapic::Config::Method] # attr_reader :delete_security_settings # @private def initialize parent_rpcs = nil create_security_settings_config = parent_rpcs.create_security_settings if parent_rpcs.respond_to? :create_security_settings @create_security_settings = ::Gapic::Config::Method.new create_security_settings_config get_security_settings_config = parent_rpcs.get_security_settings if parent_rpcs.respond_to? :get_security_settings @get_security_settings = ::Gapic::Config::Method.new get_security_settings_config update_security_settings_config = parent_rpcs.update_security_settings if parent_rpcs.respond_to? :update_security_settings @update_security_settings = ::Gapic::Config::Method.new update_security_settings_config list_security_settings_config = parent_rpcs.list_security_settings if parent_rpcs.respond_to? :list_security_settings @list_security_settings = ::Gapic::Config::Method.new list_security_settings_config delete_security_settings_config = parent_rpcs.delete_security_settings if parent_rpcs.respond_to? :delete_security_settings @delete_security_settings = ::Gapic::Config::Method.new delete_security_settings_config yield self if block_given? end end end end end end end end end end
54.969871
153
0.558516
f72dd8974c19e4af982e328dc8f2d0db347a1cdc
109
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'os_platform' require 'minitest/autorun'
21.8
58
0.752294
0173de6c241b94d43343979be047ff9d4317133e
124
class AddManufactureToParts < ActiveRecord::Migration def change add_column :parts, :manufacturer, :string end end
20.666667
53
0.766129
211b6b871b9ef271198451f6fef46857092b4abf
4,447
# # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # module Shell module Commands class Scan < Command def help return <<-EOF Scan a table; pass table name and optionally a dictionary of scanner specifications. Scanner specifications may include one or more of: TIMERANGE, FILTER, LIMIT, STARTROW, STOPROW, TIMESTAMP, MAXLENGTH, or COLUMNS, CACHE or RAW, VERSIONS If no columns are specified, all columns will be scanned. To scan all members of a column family, leave the qualifier empty as in 'col_family'. The filter can be specified in two ways: 1. Using a filterString - more information on this is available in the Filter Language document attached to the HBASE-4176 JIRA 2. Using the entire package name of the filter. Some examples: hbase> scan 'hbase:meta' hbase> scan 'hbase:meta', {COLUMNS => 'info:regioninfo'} hbase> scan 'ns1:t1', {COLUMNS => ['c1', 'c2'], LIMIT => 10, STARTROW => 'xyz'} hbase> scan 't1', {COLUMNS => ['c1', 'c2'], LIMIT => 10, STARTROW => 'xyz'} hbase> scan 't1', {COLUMNS => 'c1', TIMERANGE => [1303668804, 1303668904]} hbase> scan 't1', {REVERSED => true} hbase> scan 't1', {FILTER => "(PrefixFilter ('row2') AND (QualifierFilter (>=, 'binary:xyz'))) AND (TimestampsFilter ( 123, 456))"} hbase> scan 't1', {FILTER => org.apache.hadoop.hbase.filter.ColumnPaginationFilter.new(1, 0)} hbase> scan 't1', {CONSISTENCY => 'TIMELINE'} For setting the Operation Attributes hbase> scan 't1', { COLUMNS => ['c1', 'c2'], ATTRIBUTES => {'mykey' => 'myvalue'}} hbase> scan 't1', { COLUMNS => ['c1', 'c2'], AUTHORIZATIONS => ['PRIVATE','SECRET']} For experts, there is an additional option -- CACHE_BLOCKS -- which switches block caching for the scanner on (true) or off (false). By default it is enabled. Examples: hbase> scan 't1', {COLUMNS => ['c1', 'c2'], CACHE_BLOCKS => false} Also for experts, there is an advanced option -- RAW -- which instructs the scanner to return all cells (including delete markers and uncollected deleted cells). This option cannot be combined with requesting specific COLUMNS. Disabled by default. Example: hbase> scan 't1', {RAW => true, VERSIONS => 10} Besides the default 'toStringBinary' format, 'scan' supports custom formatting by column. A user can define a FORMATTER by adding it to the column name in the scan specification. The FORMATTER can be stipulated: 1. either as a org.apache.hadoop.hbase.util.Bytes method name (e.g, toInt, toString) 2. or as a custom class followed by method name: e.g. 'c(MyFormatterClass).format'. Example formatting cf:qualifier1 and cf:qualifier2 both as Integers: hbase> scan 't1', {COLUMNS => ['cf:qualifier1:toInt', 'cf:qualifier2:c(org.apache.hadoop.hbase.util.Bytes).toInt'] } Note that you can specify a FORMATTER by column only (cf:qualifier). You cannot specify a FORMATTER for all columns of a column family. Scan can also be used directly from a table, by first getting a reference to a table, like such: hbase> t = get_table 't' hbase> t.scan Note in the above situation, you can still provide all the filtering, columns, options, etc as described above. EOF end def command(table, args = {}) scan(table(table), args) end #internal command that actually does the scanning def scan(table, args = {}) now = Time.now formatter.header(["ROW", "COLUMN+CELL"]) #actually do the scanning count = table._scan_internal(args) do |row, cells| formatter.row([ row, cells ]) end formatter.footer(now, count) end end end end #Add the method table.scan that calls Scan.scan ::Hbase::Table.add_shell_command("scan")
38.336207
86
0.706544
28abf4714ab39047f00aa7b0517e5ddb4d647ba9
44
module TradeTracker VERSION = '0.2.3' end
11
19
0.704545
21b784fe3b6087116c1b09c7f9ed70d716bcd7b9
1,347
# Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: MIT # DO NOT MODIFY. THIS CODE IS GENERATED. CHANGES WILL BE OVERWRITTEN. # vcenter - VMware vCenter Server provides a centralized platform for managing your VMware vSphere environments require 'spec_helper' require 'json' require 'date' # Unit tests for VSphereAutomation::VCenter::VcenterSystemConfigDeploymentTypeConvertToVcsaEmbeddedTask # Automatically generated by openapi-generator (https://openapi-generator.tech) # Please update as you see appropriate describe 'VcenterSystemConfigDeploymentTypeConvertToVcsaEmbeddedTask' do before do # run before each test @instance = VSphereAutomation::VCenter::VcenterSystemConfigDeploymentTypeConvertToVcsaEmbeddedTask.new end after do # run after each test end describe 'test an instance of VcenterSystemConfigDeploymentTypeConvertToVcsaEmbeddedTask' do it 'should create an instance of VcenterSystemConfigDeploymentTypeConvertToVcsaEmbeddedTask' do expect(@instance).to be_instance_of(VSphereAutomation::VCenter::VcenterSystemConfigDeploymentTypeConvertToVcsaEmbeddedTask) end end describe 'test attribute "spec"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
35.447368
129
0.798812
87aec828717e30d3c3819e697d7ba952a3eb8535
1,683
module Unimatrix::Authorization class RequiresResourceOwner def before( controller ) client_id = Unimatrix.configuration.client_id client_secret = Unimatrix.configuration.client_secret access_token = if controller.params[ 'access_token' ].present? controller.params[ 'access_token' ] else controller.retrieve_client_token( client_id, client_secret ) end if access_token.present? resource_owner = controller.retrieve_resource_owner( access_token ) if resource_owner.present? && resource_owner.is_a?( Array ) && resource_owner.first.type_name == 'resource_owner' controller.resource_owner = resource_owner else controller.render_error( ::MissingPolicyError ) end else controller.render_error( ::MissingTokenError ) end end end module ClassMethods def requires_resource_owner( options = {} ) before_action( RequiresResourceOwner.new, options ) end end def self.included( controller ) controller.extend( ClassMethods ) end def resource_owner=( attributes ) @resource_owner = attributes end def resource_owner @resource_owner ||= begin retrieve_resource_owner( params[ :access_token ] ) end end # In Rails app, this is overwritten by #retrieve_resource_owner in railtie.rb def retrieve_resource_owner( access_token ) if access_token request_resource_owner( access_token ) end end def request_resource_owner( access_token ) Operation.new( '/resource_owner' ).where( access_token: access_token ).read end end
25.5
79
0.68568
0109de047fd9e03b152710ae16bdf6de92f83baa
1,844
Pod::Spec.new do |s| s.name = 'NSString-HTML' s.version = '0.0.1' s.summary = "Decode and encode HTML character entities." s.homepage = "https://github.com/Koolistov/NSString-HTML" s.author = 'Johan Kool' s.source = { :git => 'https://github.com/Koolistov/NSString-HTML.git', :commit => 'cd36c9bb4e5bf18f42f6f986a957c10da51c83d4' } s.ios.deployment_target = '4.3.5' s.source_files = '*.{h,m}' s.license = { :type => 'Copyright', :text => <<-LICENSE Copyright 2009-2011 Koolistov Pte Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Neither the name of KOOLISTOV PTE. LTD. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. LICENSE } end
80.173913
758
0.737527
b94b5502a5d60585e967397a3a2b01beb2df7432
1,364
module PulsarSdk module Options class Connection < Base DEFAULT_PORT = 6650 attr_accessor :logical_addr, :physical_addr, :connection_timeout, :operation_timeout, :auth_provider, :tls_options, :keepalive [:logical_addr, :physical_addr].each do |x| define_method "#{x}=" do |v| return instance_variable_set("@#{x}", v) if v.nil? v = v.is_a?(::URI) ? v : ::URI.parse(v) v.port = DEFAULT_PORT if v.port.nil? instance_variable_set("@#{x}", v) end end def connecting_through_proxy? logical_addr == physical_addr end def proxy_to_broker_url connecting_through_proxy? ? logical_addr : nil end def port_and_host_from(name) v = instance_variable_get("@#{name}") return if v.nil? [v.port, v.host] end private def set_default self.logical_addr = ENV.fetch("PULSAR_BROKER_URL", nil) # 连接5秒超时 self.connection_timeout = 5 # Set the operation timeout (default: 30 seconds) # Producer-create, subscribe and unsubscribe operations will be retried until this interval self.operation_timeout = 30 self.keepalive = 30 end end end end
26.230769
99
0.573314
e89bc500802fbd4d1427f88a320ad0da15b690e8
1,691
# # Be sure to run `pod lib lint Chargebee.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 https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'Chargebee' s.version = '0.3.4' s.summary = 'Chargebee iOS SDK' # 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 Chargebee iOS SDK aims at simplifying recurring payments integration DESC s.homepage = 'https://www.chargebee.com' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.source = { :git => 'https://github.com/cb-haripriyan/chargebee-ios.git', :tag => s.version.to_s } s.authors = { 'cb-prabu' => 'prabu@chargebeeinc.com', 'cb-haripriyan' => 'hari@chargebeeinc.com' } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '8.0' s.source_files = 'Chargebee/Classes/**/*' s.swift_version = '5.0' # s.resource_bundles = { # 'Chargebee' => ['Chargebee/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' end
38.431818
111
0.630988
87131decc75891a1ffea0e315c83d9dcd2af3868
609
class ReviewsController < ApplicationController before_action :authenticate_user! def new @image = Image.find(params[:image_id]) @review = @image.reviews.new end def create @image = Image.find(params[:image_id]) @review = @image.reviews.new(review_params) if @review.save # redirect_to user_path(@image.user) respond_to do |format| format.html { redirect_to user_image_path(@image.user, @image) } format.js end else render :new end end private def review_params params.require(:review).permit(:author, :review) end end
21
72
0.668309
0823058a79c8aa097b767070eb27339a88721999
497
# frozen_string_literal: true require 'test_helper' class Gecko::Record::PurchaseOrderLineItemAdapterTest < Minitest::Test include TestingAdapter include SharedAdapterExamples let(:adapter) { @client.PurchaseOrderLineItem } let(:plural_name) { "purchase_order_line_items" } let(:record_class) { Gecko::Record::PurchaseOrderLineItem } def test_initializes_adapter assert_instance_of(Gecko::Record::PurchaseOrderLineItemAdapter, @client.PurchaseOrderLineItem) end end
29.235294
98
0.788732
21ef94ac5d1873c7ddefab851b362f31bcd72534
1,927
require 'spec_helper' describe MergeRequestsFinder do let(:user) { create :user } let(:user2) { create :user } let(:project1) { create(:empty_project) } let(:project2) { create(:empty_project, forked_from_project: project1) } let(:project3) { create(:empty_project, :archived, forked_from_project: project1) } let!(:merge_request1) { create(:merge_request, :simple, author: user, source_project: project2, target_project: project1) } let!(:merge_request2) { create(:merge_request, :simple, author: user, source_project: project2, target_project: project1, state: 'closed') } let!(:merge_request3) { create(:merge_request, :simple, author: user, source_project: project2, target_project: project2) } let!(:merge_request4) { create(:merge_request, :simple, author: user, source_project: project3, target_project: project3) } before do project1.team << [user, :master] project2.team << [user, :developer] project3.team << [user, :developer] project2.team << [user2, :developer] end describe "#execute" do it 'filters by scope' do params = { scope: 'authored', state: 'opened' } merge_requests = MergeRequestsFinder.new(user, params).execute expect(merge_requests.size).to eq(3) end it 'filters by project' do params = { project_id: project1.id, scope: 'authored', state: 'opened' } merge_requests = MergeRequestsFinder.new(user, params).execute expect(merge_requests.size).to eq(1) end it 'filters by non_archived' do params = { non_archived: true } merge_requests = MergeRequestsFinder.new(user, params).execute expect(merge_requests.size).to eq(3) end it 'filters by iid' do params = { project_id: project1.id, iids: merge_request1.iid } merge_requests = MergeRequestsFinder.new(user, params).execute expect(merge_requests).to contain_exactly(merge_request1) end end end
37.784314
142
0.70109
21eb305015805b4aff7f43f79ef0089d637f6a2e
163
require 'shared_user_without_omniauth' class UserOnEngine < ActiveRecord::Base self.table_name = 'users' include Shim include SharedUserWithoutOmniauth end
20.375
39
0.815951
5de560881ec71d9d19f4bc965d6c602d33867800
377
require 'finacle_api/common/serializable_object' require 'finacle_api/models/amount' module FinacleApi module ODAcctInq module ResponseEntity class AcctBalAmt < SerializableObject attr_accessor :amount_value, :currency_code def to_amount Amount.new(value: amount_value, currency: currency_code) end end end end end
20.944444
66
0.713528
1a243ee24ff252d72be9ac7afd0ab850de54c66f
2,039
describe ManageIQ::Providers::Lenovo::PhysicalInfraManager::AuthenticatableProvider do let(:described_class_path) { described_class.name.underscore } let(:auth) do FactoryBot.create(:authentication, :userid => 'admin', :password => 'password', :authtype => 'default') end subject(:physical_infra_manager) do manager = FactoryBot.create(:physical_infra, :name => 'LXCA', :hostname => '10.243.9.123', :port => '443', :ipaddress => 'https://10.243.9.123') manager.authentications = [auth] manager end describe 'change password' do context 'with invalid password' do it 'will not change password' do VCR.use_cassette("#{described_class_path}/change_password_with_invalid_password") do expect do physical_infra_manager.raw_change_password('invalid_pass', 'invalid_pass') end.to raise_error(MiqException::Error, 'The request to change the password for user ID CHG_PASS could not be completed because of an authentication issue.') end end end context 'with invalid new password' do it 'will not change password' do VCR.use_cassette("#{described_class_path}/change_password_with_invalid_new_password") do expect do physical_infra_manager.raw_change_password('invalid_pass', 'invalid') end.to raise_error(MiqException::Error, 'The request to change the password for user ID CHG_PASS could not be completed because of a password policy violation.') end end end context 'with valid new password' do it 'will change password' do VCR.use_cassette("#{described_class_path}/change_password_with_valid_password") do expect(physical_infra_manager.raw_change_password('password', 'valid@123')).to be_truthy end end end end end
40.78
171
0.630701
7adb7f6341f8a976af39f70b692e5230f58f74f9
1,402
module Terraforming module Resource class IAMInstanceProfile include Terraforming::Util def self.tf(client: Aws::IAM::Client.new) self.new(client).tf end def self.tfstate(client: Aws::IAM::Client.new) self.new(client).tfstate end def initialize(client) @client = client end def tf apply_template(@client, "tf/iam_instance_profile") end def tfstate iam_instance_profiles.inject({}) do |resources, profile| attributes = { "arn" => profile.arn, "id" => profile.instance_profile_name, "name" => profile.instance_profile_name, "path" => profile.path, "role" => profile.roles[0].role_name, "roles.#" => profile.roles.length.to_s, } resources["aws_iam_instance_profile.#{module_name_of(profile)}"] = { "type" => "aws_iam_instance_profile", "primary" => { "id" => profile.instance_profile_name, "attributes" => attributes } } resources end end private def iam_instance_profiles @client.list_instance_profiles.map(&:instance_profiles).flatten end def module_name_of(profile) normalize_module_name(profile.instance_profile_name) end end end end
25.035714
78
0.573466
62703dc23a9623ad257f9dae1ae93e0f1c5bd99b
2,700
require 'spec_helper' describe 'java::oracle_i386' do let(:chef_run) do runner = ChefSpec::ServerRunner.new runner.converge(described_recipe) end it 'should include the set_java_home recipe' do expect(chef_run).to include_recipe('java::set_java_home') end it 'should configure a java_ark[jdk] resource' do pending 'Testing LWRP use is not required at this time, this is tested post-converge.' this_should_not_get_executed end describe 'conditionally includes set attributes' do context 'when java_home is set' do let(:chef_run) do runner = ChefSpec::ServerRunner.new( platform: 'ubuntu', version: '12.04' ) runner.node.set['java']['java_home'] = '/some/path' runner.converge(described_recipe) end it 'does not include set_attributes_from_version' do expect(chef_run).to_not include_recipe('java::set_attributes_from_version') end end context 'when java_home is not set' do let(:chef_run) do runner = ChefSpec::ServerRunner.new( platform: 'ubuntu', version: '12.04' ) runner.converge(described_recipe) end it 'does not include set_attributes_from_version' do expect(chef_run).to include_recipe('java::set_attributes_from_version') end end end describe 'default-java' do context 'ubuntu' do let(:chef_run) do ChefSpec::ServerRunner.new( platform: 'ubuntu', version: '12.04' ).converge(described_recipe) end it 'includes default_java_symlink' do expect(chef_run).to include_recipe('java::default_java_symlink') end end context 'centos' do let(:chef_run) do ChefSpec::ServerRunner.new( platform: 'centos', version: '6.4' ).converge(described_recipe) end it 'does not include default_java_symlink' do expect(chef_run).to_not include_recipe('java::default_java_symlink') end end end describe 'JCE installation' do context 'when jce is disabled' do let(:chef_run) do ChefSpec::ServerRunner.new.converge(described_recipe) end it 'does not include jce recipe' do expect(chef_run).to_not include_recipe('java::oracle_jce') end end context 'when jce is enabled' do let(:chef_run) do ChefSpec::ServerRunner.new do |node| node.set['java']['oracle']['jce']['enabled'] = true end.converge(described_recipe) end it 'does include jce recipe' do expect(chef_run).to include_recipe('java::oracle_jce') end end end end
26.732673
90
0.642963
338912c9f5f4916b966d90e4799091cd5a16dc8d
220
class AddBrowserPreference < ActiveRecord::Migration def self.up add_column :users, :use_browser, :boolean, :default => false, :null => false end def self.down remove_column :users, :use_browser end end
22
80
0.718182
e2de0608a75a7d3c543f0f8eb964bf55f9a628c0
1,660
# A method for retrieving external trusted facts module Puppet::TrustedExternal def retrieve(certname) command = Puppet[:trusted_external_command] return nil unless command Puppet.debug _("Retrieving trusted external data from %{command}") % {command: command} setting_type = Puppet.settings.setting(:trusted_external_command).type if setting_type == :file return fetch_data(command, certname) end # command is a directory. Thus, data is a hash of <basename> => <data> for # each executable file in command. For example, if the files 'servicenow.rb', # 'unicorn.sh' are in command, then data is the following hash: # { 'servicenow' => <servicenow.rb output>, 'unicorn' => <unicorn.sh output> } data = {} Puppet::FileSystem.children(command).each do |file| abs_path = Puppet::FileSystem.expand_path(file) executable_file = Puppet::FileSystem.file?(abs_path) && Puppet::FileSystem.executable?(abs_path) unless executable_file Puppet.debug _("Skipping non-executable file %{file}") % { file: abs_path } next end basename = file.basename(file.extname).to_s unless data[basename].nil? raise Puppet::Error, _("There is more than one '%{basename}' script in %{dir}") % { basename: basename, dir: command } end data[basename] = fetch_data(abs_path, certname) end data end module_function :retrieve def fetch_data(command, certname) result = Puppet::Util::Execution.execute([command, certname], { :combine => false, :failonfail => true, }) JSON.parse(result) end module_function :fetch_data end
39.52381
126
0.680723
87c76571885be2d23b5b43620032c0e6e703d8f2
1,163
# A facter fact to determine the root home directory. # This varies on PE supported platforms and may be # reconfigured by the end user. module Facter::Util::RootHome class << self def get_root_home root_ent = Facter::Util::Resolution.exec("getent passwd root") # The home directory is the sixth element in the passwd entry # If the platform doesn't have getent, root_ent will be nil and we should # return it straight away. root_ent && root_ent.split(":")[5] end end end Facter.add(:root_home) do setcode { Facter::Util::RootHome.get_root_home } end Facter.add(:root_home) do confine :kernel => :darwin setcode do str = Facter::Util::Resolution.exec("dscacheutil -q user -a name root") hash = {} str.split("\n").each do |pair| key,value = pair.split(/:/) hash[key] = value end hash['dir'].strip end end Facter.add(:root_home) do confine :kernel => :aix root_home = nil setcode do str = Facter::Util::Resolution.exec("lsuser -c -a home root") str && str.split("\n").each do |line| next if line =~ /^#/ root_home = line.split(/:/)[1] end root_home end end
25.282609
77
0.656062
79051a21d7bb7acf0fc49b24ed5f13771d499373
364
class Sale < ActiveRecord::Base has_one :configuracion, dependent: :destroy has_one :client, dependent: :destroy has_many :lineFurnitures, dependent: :destroy has_many :furnitures, :through => :lineFurnitures accepts_nested_attributes_for :configuracion, :allow_destroy => true accepts_nested_attributes_for :lineFurnitures, :allow_destroy => true end
40.444444
71
0.793956
6131cfaae11f9d0334b1f976f18ed65de2644d61
217
class ChangeItemsNameTypeToText < ActiveRecord::Migration def self.up change_column :gallery_items, :description, :text end def self.down change_column :gallery_items, :description, :string end end
21.7
57
0.75576
e92a27387748a24525061a5a007db3c1ae3af2bc
528
ActiveAdmin.register AdminUser do menu priority: 2 permit_params :email, :password, :password_confirmation index do selectable_column id_column column :email column :current_sign_in_at column :sign_in_count column :created_at actions end filter :email filter :current_sign_in_at filter :sign_in_count filter :created_at form do |f| f.inputs "Admin Details" do f.input :email f.input :password f.input :password_confirmation end f.actions end end
17.6
57
0.700758
03042601cec049847b0d77a7dc49b5454c60f137
532
class Wireshark < Cask url 'http://wiresharkdownloads.riverbed.com/wireshark/osx/Wireshark%201.10.3%20Intel%2064.dmg' homepage 'http://www.wireshark.org' version '1.10.3' sha1 '5fa924b3c8c3e5bd80662b95047cea51b12ec0e8' link :none install 'Wireshark 1.10.3 Intel 64.pkg' uninstall :pkgutil => 'org.wireshark.*', :files => %w(capinfos dftest dumpcap editcap mergecap randpkt rawshark text2pcap tshark wireshark).map { |file| '/usr/local/bin/' << file} end
40.923077
96
0.656015
d5cc8c2b1dc94cbbf72878e90f17e5a28d796418
834
require 'restfulie/common' module Restfulie module Client autoload :MasterDelegator, 'restfulie/client/master_delegator' autoload :HTTP, 'restfulie/client/http' autoload :Configuration, 'restfulie/client/configuration' autoload :EntryPoint, 'restfulie/client/entry_point' autoload :Base, 'restfulie/client/base' autoload :Mikyung, 'restfulie/client/mikyung' autoload :Cache, 'restfulie/client/cache' autoload :Feature, 'restfulie/client/feature' autoload :Dsl, 'restfulie/client/dsl' autoload :StackNavigator, 'restfulie/client/stack_navigator' mattr_accessor :cache_provider, :cache_store Restfulie::Client.cache_store = ActiveSupport::Cache::MemoryStore.new Restfulie::Client.cache_provider = Restfulie::Client::Cache::Fake.new end end require 'restfulie/client/ext'
33.36
73
0.755396
e94dce57b64429d9d7a0d7195e0e91701abe3061
6,064
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class GraphQL < RegexLexer desc 'GraphQL' tag 'graphql' filenames '*.graphql', '*.gql' mimetypes 'application/graphql' name = /[_A-Za-z][_0-9A-Za-z]*/ state :root do rule %r/\b(?:query|mutation|subscription)\b/, Keyword, :query_definition rule %r/\{/ do token Punctuation push :query_definition push :selection_set end rule %r/\bfragment\b/, Keyword, :fragment_definition rule %r/\bscalar\b/, Keyword, :value rule %r/\b(?:type|interface|enum)\b/, Keyword, :type_definition rule %r/\b(?:input|schema)\b/, Keyword, :type_definition rule %r/\bunion\b/, Keyword, :union_definition rule %r/\bextend\b/, Keyword mixin :basic # Markdown descriptions rule %r/(""")(\n)(.*?)(\n)(""")/m do |m| token Str::Double, m[1] token Text::Whitespace, m[2] delegate Markdown, m[3] token Text::Whitespace, m[4] token Str::Double, m[5] end end state :basic do rule %r/\s+/m, Text::Whitespace rule %r/#.*$/, Comment rule %r/[!,]/, Punctuation end state :has_directives do rule %r/(@#{name})(\s*)(\()/ do groups Keyword, Text::Whitespace, Punctuation push :arguments end rule %r/@#{name}\b/, Keyword end state :fragment_definition do rule %r/\bon\b/, Keyword mixin :query_definition end state :query_definition do mixin :has_directives rule %r/\b#{name}\b/, Name rule %r/\(/, Punctuation, :variable_definitions rule %r/\{/, Punctuation, :selection_set mixin :basic end state :type_definition do rule %r/\bimplements\b/, Keyword rule %r/\b#{name}\b/, Name rule %r/\(/, Punctuation, :variable_definitions rule %r/\{/, Punctuation, :type_definition_set mixin :basic end state :union_definition do rule %r/\b#{name}\b/, Name rule %r/\=/, Punctuation, :union_definition_variant mixin :basic end state :union_definition_variant do rule %r/\b#{name}\b/ do token Name pop! push :union_definition_pipe end mixin :basic end state :union_definition_pipe do rule %r/\|/ do token Punctuation pop! push :union_definition_variant end rule %r/(?!\||\s+|#[^\n]*)/ do pop! 2 end mixin :basic end state :type_definition_set do rule %r/\}/ do token Punctuation pop! 2 end rule %r/\b(#{name})(\s*)(\()/ do groups Name, Text::Whitespace, Punctuation push :variable_definitions end rule %r/\b#{name}\b/, Name rule %r/:/, Punctuation, :type_names mixin :basic end state :arguments do rule %r/\)/ do token Punctuation pop! end rule %r/\b#{name}\b/, Name rule %r/:/, Punctuation, :value mixin :basic end state :variable_definitions do rule %r/\)/ do token Punctuation pop! end rule %r/\$#{name}\b/, Name::Variable rule %r/\b#{name}\b/, Name rule %r/:/, Punctuation, :type_names rule %r/\=/, Punctuation, :value mixin :basic end state :type_names do rule %r/\b(?:Int|Float|String|Boolean|ID)\b/, Name::Builtin, :pop! rule %r/\b#{name}\b/, Name, :pop! rule %r/\[/, Punctuation, :type_name_list mixin :basic end state :type_name_list do rule %r/\b(?:Int|Float|String|Boolean|ID)\b/, Name::Builtin rule %r/\b#{name}\b/, Name rule %r/\]/ do token Punctuation pop! 2 end mixin :basic end state :selection_set do mixin :has_directives rule %r/\}/ do token Punctuation pop! pop! if state?(:query_definition) || state?(:fragment_definition) end rule %r/\b(#{name})(\s*)(\()/ do groups Name, Text::Whitespace, Punctuation push :arguments end rule %r/\b(#{name})(\s*)(:)/ do groups Name, Text::Whitespace, Punctuation end rule %r/\b#{name}\b/, Name rule %r/(\.\.\.)(\s+)(on)\b/ do groups Punctuation, Text::Whitespace, Keyword end rule %r/\.\.\./, Punctuation rule %r/\{/, Punctuation, :selection_set mixin :basic end state :list do rule %r/\]/ do token Punctuation pop! pop! if state?(:value) end mixin :value end state :object do rule %r/\}/ do token Punctuation pop! pop! if state?(:value) end rule %r/\b(#{name})(\s*)(:)/ do groups Name, Text::Whitespace, Punctuation push :value end mixin :basic end state :value do pop_unless_list = ->(t) { ->(m) { token t pop! unless state?(:list) } } # Multiline strings rule %r/""".*?"""/m, Str::Double rule %r/\$#{name}\b/, &pop_unless_list[Name::Variable] rule %r/\b(?:true|false|null)\b/, &pop_unless_list[Keyword::Constant] rule %r/[+-]?[0-9]+\.[0-9]+(?:[eE][+-]?[0-9]+)?/, &pop_unless_list[Num::Float] rule %r/[+-]?[1-9][0-9]*(?:[eE][+-]?[0-9]+)?/, &pop_unless_list[Num::Integer] rule %r/"(\\[\\"]|[^"])*"/, &pop_unless_list[Str::Double] rule %r/\b#{name}\b/, &pop_unless_list[Name] rule %r/\{/, Punctuation, :object rule %r/\[/, Punctuation, :list mixin :basic end end end end
23.145038
86
0.503793
01b54ea2ed44198023ed17c7ddf1255dfa76f6ea
4,221
# frozen_string_literal: true class SushiService def initialize(customer_id, platform, requestor_id) @customer_id = customer_id @platform = platform @requestor_id = requestor_id end def status fulcrum_status = ::SwaggerClient::SUSHIServiceStatus.new fulcrum_status.description = "COUNTER Usage Reports for Fulcrum platform." fulcrum_status.service_active = true fulcrum_status.registry_url = Rails.application.routes.url_helpers.api_sushi_url fulcrum_status.note = "You must be a platform administrator to retrieve reports." can_read = ::SwaggerClient::SUSHIServiceStatusAlerts.new can_read.alert = "If you can read this ..." can_read.date_time = DateTime.now.to_f # rubocop:disable Style/DateTime too_close = ::SwaggerClient::SUSHIServiceStatusAlerts.new too_close.alert = "You are too CLOSE!" too_close.date_time = DateTime.now.to_f # rubocop:disable Style/DateTime fulcrum_status.alerts = [can_read, too_close] [fulcrum_status] end def members member = ::SwaggerClient::SUSHIConsortiumMemberList.new member.customer_id = @customer_id member.requestor_id = User.find(@requestor_id)&.email member.name = Greensub::Institution.find(@customer_id).name member.notes = Greensub::Institution.find(@customer_id).entity_id member.institution_id = [] [member] end def reports(_search = nil) platform_master_report = ::SwaggerClient::SUSHIReportList.new platform_master_report.report_name = 'Platform Master Report' platform_master_report.report_id = 'PR' platform_master_report.release = '5' platform_master_report.report_description = 'A customizable report that summarizes activity across a provider’s platforms and allows the user to apply filters and select other configuration options.' platform_master_report.path = Rails.application.routes.url_helpers.api_sushi_report_url(:pr) platform_usage = ::SwaggerClient::SUSHIReportList.new platform_usage.report_name = 'Platform Usage' platform_usage.report_id = 'PR_P1' platform_usage.release = '5' platform_usage.report_description = 'A Standard View of the Platform Master Report offering platform-level usage summarized by metric type.' platform_usage.path = Rails.application.routes.url_helpers.api_sushi_report_url(:pr_p1) # TODO: Filter reports by search parameter [platform_master_report, platform_usage] end def report(id) # Attribute mapping from ruby-style variable name to JSON key. # def self.attribute_map # { # :'created' => :'Created', # :'created_by' => :'Created_By', # :'customer_id' => :'Customer_ID', # :'report_id' => :'Report_ID', # :'release' => :'Release', # :'report_name' => :'Report_Name', # :'institution_name' => :'Institution_Name', # :'institution_id' => :'Institution_ID', # :'report_filters' => :'Report_Filters', # :'report_attributes' => :'Report_Attributes', # :'exceptions' => :'Exceptions' # } # end report_header = ::SwaggerClient::SUSHIReportHeader.new # case id # when /dr|dr_d1|dr_d2/i # :'report_items' => :'Array<COUNTERDatabaseUsage>' # when /ir|ir_a1|ir_m1/i # :'report_items' => :'Array<COUNTERItemUsage>' # when /pr|pr_p1/i # :'report_items' => :'Array<COUNTERPlatformUsage>' # when /tr|tr_b1|tr_b2|tr_b3|tr_j1|tr_j2|tr_j3|tr_j4/i # :'report_items' => :'Array<COUNTERTitleUsage>' # end # report_items = [] # Attribute mapping from ruby-style variable name to JSON key. # def self.attribute_map # { # :'report_header' => :'Report_Header', # :'report_items' => :'Report_Items' # } # end attributes = { Report_Header: report_header, Report_Items: report_items } case id when /dr|dr_d1|dr_d2/i ::SwaggerClient::COUNTERDatabaseReport when /ir|ir_a1|ir_m1/i ::SwaggerClient::COUNTERItemReport when /pr|pr_p1/i ::SwaggerClient::COUNTERPlatformReport when /tr|tr_b1|tr_b2|tr_b3|tr_j1|tr_j2|tr_j3|tr_j4/i ::SwaggerClient::COUNTERTitleReport end.new(attributes) end end
38.724771
203
0.693201