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
ab9f9394dec8620cba435c5ed449dbd03c98feb1
197
class CreateComments < ActiveRecord::Migration[5.0] def change create_table :comments do |t| t.references :post, index: true t.text :content t.timestamps end end end
17.909091
51
0.659898
bfd8537cbdd6bf12baafe16b85988f78cc69809b
541
# given a string, return the character after every letter "r" # # pirates_say_arrrrrrrrr("are you really learning Ruby?") # => "eenu" # pirates_say_arrrrrrrrr("Katy Perry is on the radio!") # => "rya" # pirates_say_arrrrrrrrr("Pirates say arrrrrrrrr") # => "arrrrrrrr" def pirates_say_arrrrrrrrr(string) new_string = "" add_next = false string.size.times do |index| current_char = string[index] new_string << current_char if add_next add_next = (current_char == "r" || current_char == "R") end new_string end
31.823529
74
0.693161
0815131b3a24101957e4e1f7f65c723d431f51d4
2,728
Pod::Spec.new do |s| s.name = 'ARAnalytics' s.version = '1.2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'Use multiple major analytics platforms with one clean simple API.' s.homepage = 'http://github.com/orta/ARAnalytics' s.author = { 'orta' => '[email protected]' } s.source = { :git => 'https://github.com/orta/ARAnalytics.git' , :tag => "1.2"} s.description = 'Using subspecs you can define your analytics provider with the same API.' s.platform = :ios testflight_sdk = { :spec_name => "TestFlight", :dependency => "TestFlightSDK", :import_file => "TestFlight" } mixpanel = { :spec_name => "Mixpanel", :dependency => "Mixpanel", :import_file => "Mixpanel" } localytics = { :spec_name => "Localytics", :dependency => "Localytics-iOS-Client", :import_file => "LocalyticsSession" } flurry = { :spec_name => "Flurry", :dependency => "FlurrySDK", :import_file => "Flurry" } google = { :spec_name => "GoogleAnalytics", :dependency => "GoogleAnalytics-iOS-SDK", :import_file => "GAI" } kissmetrics = { :spec_name => "KISSmetrics", :dependency => "KISSmetrics", :import_file => "KISSMetricsAPI" } crittercism = { :spec_name => "Crittercism", :dependency => "CrittercismSDK", :import_file => "Crittercism" } countly = { :spec_name => "Countly", :dependency => "Countly", :import_file => "Countly" } bugsnag = { :spec_name => "Bugsnag", :dependency => "Bugsnag", :import_file => "Bugsnag" } crashlytics = { :spec_name => "Crashlytics" } $all_analytics = [testflight_sdk, mixpanel, localytics, flurry, google, kissmetrics, crittercism, crashlytics, bugsnag, countly] # bring in all files via the core package s.subspec "Core" do |ss| ss.source_files = ['*.{h,m}', 'Providers/ARAnalyticalProvider.{h,m}', 'Providers/ARAnalyticsProviders.h'] end # make specs for each analytics $all_analytics.each do |analytics_spec| s.subspec analytics_spec[:spec_name] do |ss| # All subspecs require the core ss.dependency 'ARAnalytics/Core' # Each subspec adds a compiler flag saying that the spec was included ss.prefix_header_contents = "#define AR_#{analytics_spec[:spec_name].upcase}_EXISTS 1" ss.source_files = ["Providers/#{analytics_spec[:spec_name]}Provider.{h,m}"] # If there's a podspec dependency include it if analytics_spec[:dependency] ss.dependency analytics_spec[:dependency] end end end end
55.673469
146
0.605205
d5cc58f002ba70ef894753893d51ab470e7d4e27
4,092
require 'twilio-ruby/rest/base_client' module Twilio module REST class LookupsClient < BaseClient API_VERSION = 'v1' DEFAULTS = { host: 'lookups.twilio.com', port: 443, use_ssl: true, ssl_verify_peer: true, ssl_ca_file: File.dirname(__FILE__) + '/../../../conf/cacert.pem', timeout: 30, proxy_addr: nil, proxy_port: nil, proxy_user: nil, proxy_pass: nil, retry_limit: 1 } attr_reader :phone_numbers ## # Instantiate a new HTTP Lookups client to talk to Twilio. The parameters # +account_sid+, +auth_token+ and +workspace_sid are required, unless you # have configured them already using the block configure syntax, and used # to generate the HTTP basic auth header in each request. The +options+ # parameter is a hash of connection configuration options. the following # keys are supported: # # === <tt>host: 'lookups.twilio.com'</tt> # # The domain to which you'd like the client to make HTTP requests. Useful # for testing. Defaults to 'lookups.twilio.com'. # # === <tt>port: 443</tt> # # The port on which to connect to the above domain. Defaults to 443 and # should be left that way except in testing environments. # # === <tt>use_ssl: true</tt> # # Declare whether ssl should be used for connections to the above domain. # Defaults to true and should be left alone except when testing. # # === <tt>ssl_verify_peer: true</tt> # # Declare whether to verify the host's ssl cert when setting up the # connection to the above domain. Defaults to true, but can be turned off # to avoid ssl certificate verification failures in environments without # the necessary ca certificates. # # === <tt>ssl_ca_file: '/path/to/ca/file'</tt> # # Specify the path to the certificate authority bundle you'd like to use # to verify Twilio's SSL certificate on each request. If not specified, a # certificate bundle extraced from Firefox is packaged with the gem and # used by default. # # === <tt>timeout: 30</tt> # # Set the time in seconds to wait before timing out the HTTP request. # Defaults to 30 seconds. If you aren't fetching giant pages of call or # SMS logs you can safely decrease this to something like 3 seconds or # lower. In paricular if you are sending SMS you can set this to 1 second # or less and swallow the exception if you don't care about the response. # # === <tt>proxy_addr: 'proxy.host.domain'</tt> # # The domain of a proxy through which you'd like the client to make HTTP # requests. Defaults to nil. # # === <tt>proxy_port: 3128</tt> # # The port on which to connect to the above proxy. Defaults to nil. # # === <tt>proxy_user: 'username'</tt> # # The user name to use for authentication with the proxy. Defaults to nil. # # === <tt>proxy_pass: 'password'</tt> # # The password to use for authentication with the proxy. Defaults to nil. # # === <tt>retry_limit: 1</tt> # # The number of times to retry a request that has failed before throwing # an exception. Defaults to one. def inspect # :nodoc: "<Twilio::REST::LookupsClient @account_sid=#{@account_sid}>" end protected ## # Get the default config values. def get_defaults DEFAULTS end ## # Set up +phone_numbers+ attribute. def set_up_subresources # :doc: @phone_numbers = Twilio::REST::Lookups::PhoneNumbers.new "/#{API_VERSION}/PhoneNumbers", self end ## # Builds up full request path def build_full_path(path, params, method) path = path.dup path << "?#{url_encode(params)}" if method == :get && !params.empty? path end end end end
34.677966
101
0.609971
ac9c067154f3ee931f8337a5edbf8703806cecac
43
module CryptoPrices VERSION = "0.1.0" end
14.333333
19
0.72093
6a27cfedbc2cb145133a77f0f7bb841721564888
356
cask 'macmoney' do version '3.7.1' sha256 '65c24dafbb957f2f050c10dafe39756f04a1dc12e2d8f3016e00a5347dcb5171' url 'http://www.devon.riceball.net/downloads/macmoney37.zip' name 'MacMoney' homepage 'http://www.devon.riceball.net/display.php?file=m01' license :commercial container :nested => "MacMoney_#{version}.dmg" app 'MacMoney.app' end
27.384615
75
0.758427
2129cffcbd43070aea7abcea14076cb1d3799bed
1,077
# メインのサンプルユーザーを1人作成する User.create!(name: "wakaharariku", email: "[email protected]", password: "riku1123", password_confirmation: "riku1123", admin: true, activated: true, activated_at: Time.zone.now) # 追加のユーザーをまとめて生成する 99.times do |n| name = Faker::Name.name email = "example-#{n+1}@railstutorial.org" password = "password" User.create!(name: name, email: email, password: password, password_confirmation: password, activated: true, activated_at: Time.zone.now) end # ユーザーの一部を対象にマイクロポストを生成する users = User.order(:created_at).take(6) 50.times do content = Faker::Lorem.sentence(word_count: 5) users.each { |user| user.microposts.create!(content: content) } end # 以下のリレーションシップを作成する users = User.all user = users.first following = users[2..50] followers = users[3..40] following.each { |followed| user.follow(followed) } followers.each { |follower| follower.follow(user) }
28.342105
65
0.618384
3356521a4fd76f596db92612953e41ec7659e80c
2,964
# # Copyright 2015-2016, Chef Software, 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. # name "omnibus-toolchain" friendly_name "Omnibus Toolchain" maintainer "Chef Software Inc" homepage "https://www.chef.io" license "Apache-2.0" license_file "LICENSE" build_iteration 1 # Do not use __FILE__ after this point, use current_file. If you use __FILE__ # after this point, any dependent defs (ex: angry-omnibus-toolchain) that # use instance_eval will fail to work correctly. current_file ||= __FILE__ version_file = File.expand_path("../../../VERSION", current_file) build_version IO.read(version_file).strip if windows? install_dir "#{default_root}/opscode/#{name}" package_name "omnibus-toolchain" else install_dir "#{default_root}/#{name}" end override :ruby, version: "2.7.4" override :gtar, version: "1.32" # riding berkshelf master is hard when you're at the edge of versions override :berkshelf, version: "v7.2.2" # 1.1.1i+ builds on m1 mac override :openssl, version: "1.1.1k" if solaris? # More recent versions of git build on Solaris but "git name-rev" doesn't work properly which fails Chef Infra tests override :git, version: "2.24.1" # Solaris fails compile on libtool version 2.4.2 and 2.4.6 override :libtool, version: "2.4" # Newer versions of ncurses cause libedit build failures on Solaris override :ncurses, version: "5.9" end # creates required build directories dependency "preparation" # Split the toolchain defs into their own software def so we can have # a custom whitelist dependency "omnibus-toolchain" dependency "ruby-cleanup" exclude '\.git*' exclude 'bundler\/git' package :rpm do signing_passphrase ENV["OMNIBUS_RPM_SIGNING_PASSPHRASE"] end # This is so that angry-omnibus-toolchain will end up with the correct name proj_to_work_around_cleanroom = self package :pkg do identifier "com.getchef.pkg.#{proj_to_work_around_cleanroom.name}" signing_identity "Chef Software, Inc. (EU3VF8YLX2)" end compress :dmg msi_upgrade_code = "3A542C80-3784-4C03-A2CE-94FED4EB7002" project_location_dir = name package :msi do fast_msi true upgrade_code msi_upgrade_code wix_candle_extension "WixUtilExtension" wix_light_extension "WixUtilExtension" signing_identity "AF21BA8C9E50AE20DA9907B6E2D4B0CC3306CA03", machine_store: true parameters ProjectLocationDir: project_location_dir end package :appx do signing_identity "AF21BA8C9E50AE20DA9907B6E2D4B0CC3306CA03", machine_store: true end
30.244898
118
0.772267
e892d1f8dbf021d79b75bd8c8deec9149c2674a7
633
class Groups::BoardsController < Groups::ApplicationController include BoardsResponses before_action :assign_endpoint_vars before_action :boards, only: :index def index respond_with_boards end def show @board = boards.find(params[:id]) respond_with_board end private def boards @boards ||= Boards::ListService.new(group, current_user).execute end def assign_endpoint_vars @boards_endpoint = group_boards_url(group) @namespace_path = group.to_param @labels_endpoint = group_labels_url(group) end def serialize_as_json(resource) resource.as_json(only: [:id]) end end
19.181818
68
0.737757
aba9ce7070bf895bc9c3e489653eb6feb9f6ae50
783
# frozen_string_literal: true module NanoRpc # NanoRpc::Accounts wraps the concept of a set of Nano accounts # * It exposes `addresses` as a persistent attribute # * It exposes accounts-specific RPC methods (such as bulk creation) # * It provides a number of convenience methods via mixins class Accounts include NanoRpc::AccountsHelper include NanoRpc::AccountsMethods include NanoRpc::Proxy attr_reader :addresses def initialize(addresses = nil, opts = {}) unless addresses.is_a?(Array) raise NanoRpc::MissingParameters, 'Missing argument: addresses (str[])' end @addresses = addresses super(opts) end def inspect "#{inspect_prefix}, @addresses=\"#{@addresses}\">" end end end
26.1
71
0.675607
287dbc193f2b2093b28ee795987d14e9cde50daf
139
require './test/test_helper' class NavigationTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end end
17.375
54
0.719424
6aea650a5378bb3469d8099cc6d021746f3dd08b
250
# frozen_string_literal: true class AccessCode < ActiveRecord::Base validates :code, presence: true, uniqueness: true scope :active, -> { where(active: true) } scope :by_code, ->(value) { active.where('lower(code) = ?', value.downcase) } end
27.777778
79
0.696
1dbbd7e1fbe58c888bce9d45c108548331ab12fb
4,798
# frozen_string_literal: true class MyMissingDataError < StandardError end # Calculate scores given the content of a completed response and its questionnaire definition class CalculateScores < ActiveInteraction::Base include ConversionHelper hash :content, strip: false # strip: false means allow all keys hash :questionnaire, strip: false # Enriches the questionnaire outcomes with scores # # @param content [Hash] the response values as a hash (keys are strings) # @param questionnaire [Hash] the questionnaire definition hash (keys can be symbols) def execute @scores = {} questionnaire[:scores].each do |score| calculate_and_add_score(score) end @scores end private def to_number(value, qids) return nil if value.blank? my_value = possibly_substitute_for_number(value, qids) # my_value can be either a string or a number (float or int) at this point. str_or_num_to_num(my_value) end # This method substitutes the given string value for a number if this substitution # was defined in the questionnaire. # # If the value of a question in the response content hash belongs to a question # that has an options attribute, and the value is one of the options, then # check if this option has the `numeric_value` attribute, and if so, return # this numeric_value. Otherwise, return the guveb value unchanged. def possibly_substitute_for_number(value, qids) question = questionnaire[:questions].find { |quest| quest[:id] == qids.to_sym } return value unless question.present? && question.key?(:options) unified_options = unify_options(question[:options]) current_option = unified_options.find { |option| option[:title] == value } return value unless current_option.present? && current_option.key?(:numeric_value) current_option[:numeric_value] end def unify_options(question_options) roptions = [] question_options.each do |question_option| roptions << if question_option.is_a?(Hash) question_option else { title: question_option } end end roptions end def calculate_and_add_score(score) value = calculate_score(score) @scores[score[:id].to_s] = value.to_s rescue MyMissingDataError # This just means the score won't be calculated nil end def calculate_score(score) data = gather_data(score) value = perform_operation(data, score) round_result(value, score) end def read_from_content(qids) return content[qids] if content.key?(qids) && content[qids].present? @scores[qids] end def exists_in_content?(qids) (content.key?(qids) && content[qids].present?) || (@scores.key?(qids) && @scores[qids].present?) end def gather_data(score) result = [] score[:ids].each do |qid| qids = qid.to_s unless exists_in_content?(qids) raise MyMissingDataError, "id #{qids} not found in the enriched response" if score[:require_all].present? next end numeric_value = to_number(read_from_content(qids), qids) if numeric_value.blank? raise MyMissingDataError, "no numeric value for #{qids} could be determined" if score[:require_all].present? next end numeric_value = preprocess_value(numeric_value, qid, score) if numeric_value.present? result << numeric_value end result end def perform_operation(data, score) case score[:operation] when :average perform_operation_average(data) when :sum perform_operation_sum(data) else raise "unknown operation: #{score[:operation]}" end end def perform_operation_average(data) raise MyMissingDataError, 'trying to calculate the average of an empty array' if data.size.zero? return data[0] if data.size == 1 # no need to convert to float if we have just one integer data.sum(0.0) / data.size end def perform_operation_sum(data) raise MyMissingDataError, 'trying to calculate the sum of an empty array' if data.size.zero? return data[0] if data.size == 1 # no need to convert to float if we have just one integer data.sum(0) end def round_result(value, score) return value unless score.key?(:round_to_decimals) value.round(score[:round_to_decimals]) end def preprocess_value(numeric_value, qid, score) return numeric_value unless score.key?(:preprocessing) && score[:preprocessing].key?(qid) preprocessing_step = score[:preprocessing][qid] Questionnaire::PREPROCESSING_STEPS.each do |step| next unless preprocessing_step.key?(step[:name]) numeric_value = numeric_value.send(step[:method], str_or_num_to_num(preprocessing_step[step[:name]])) end numeric_value end end
31.359477
116
0.705294
7a02b369304ba982754518ffedf67c7857a1358d
1,372
=begin #FastAPI #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 0.1.0 Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.0.0 =end module OpenapiClient class ApiError < StandardError attr_reader :code, :response_headers, :response_body # Usage examples: # ApiError.new # ApiError.new("message") # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") # ApiError.new(:code => 404, :message => "Not Found") def initialize(arg = nil) if arg.is_a? Hash if arg.key?(:message) || arg.key?('message') super(arg[:message] || arg['message']) else super arg end arg.each do |k, v| instance_variable_set "@#{k}", v end else super arg end end # Override to_s to display a friendly error message def to_s message end def message if @message.nil? msg = "Error message: the server returns an error" else msg = @message end msg += "\nHTTP status code: #{code}" if code msg += "\nResponse headers: #{response_headers}" if response_headers msg += "\nResponse body: #{response_body}" if response_body msg end end end
23.655172
107
0.611516
112c1eba22e86ba822ab8b7eb014a0d89ac76865
1,217
require Pathname.new(__FILE__).parent.to_s + '/shared_connection_db_helpers' module Marty; module RSpec; module SharedConnection @@classes_to_exclude_from_shared = ['Marty::Log'] mattr_accessor :classes_to_exclude_from_shared EXCL_LAMBDA = lambda { classes_to_exclude_from_shared }.freeze class ActiveRecord::Base mattr_accessor :shared_connection class << self alias_method :orig_connection, :connection end def self.clear_connection @@shared_connection = nil end clear_connection def self.connection # Workaround to fix a bug in Rails 6 with shared connections # https://github.com/rails/rails/issues/36757 model_name_str = if name == 'primary::SchemaMigration' name else model_name end EXCL_LAMBDA.call.include?(model_name_str) ? orig_connection : @@shared_connection || ConnectionPool::Wrapper.new(size: 1) { retrieve_connection } end def self.reset_shared_connection @@shared_connection = ConnectionPool::Wrapper. new(size: 1) { retrieve_connection } end end end end end
30.425
76
0.655711
ac85092eb9d3c15f20cc54ffe611beba4687fd3f
444
# frozen_string_literal: true module Spree module Gallery module ProductGalleryDecorator attr_accessor :viewable_ids def self.prepended(base) def images @images ||= Spree::Image.where(id: @product.variant_images.distinct(false).select(:image_id).group(:image_id).unscope(:order).map(&:image_id)).order(:position) end end ::Spree::Gallery::ProductGallery.prepend self end end end
24.666667
169
0.684685
b958c9170c8c337a12174923558eeea1da3a7bf5
1,835
# # Cookbook Name: zookeeper # Recipe: zookeeper_service.rb # # Copyright (c) 2012 Dell 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. # # Author: Paul Webster # class ZookeeperService < ServiceObject def create_proposal @logger.debug("zookeeper create_proposal: entering") base = super # Get the node list. nodes = Node.all nodes.delete_if { |n| n.nil? } # Find the slave nodes for the zookeeper servers. # The number of slaves to use depends on the number of failed # nodes to support. We follow the (2F+1) rule so we stop allocating # at the first 5 slave nodes found. slave_nodes = Barclamp.find_by_name("hadoop").active_proposals[0].active_config.get_nodes_by_role("hadoop-slavenode") slave_fqdns = Array.new node_cnt = 0 slave_nodes.each { |x| slave_fqdns << x node_cnt = node_cnt +1 break if node_cnt >= 5 } # Check for errors or add the proposal elements. if !slave_fqdns.nil? && slave_fqdns.length > 0 slave_fqdns.each do |node| add_role_to_instance_and_node(node.name, base.name, "zookeeper-server") end else @logger.debug("zookeeper create_proposal: No slave nodes found, proposal bind failed") end @logger.debug("zookeeper create_proposal: exiting") base end end
31.101695
121
0.700272
1a59f44de457acb9e323180397a1872d92f2414c
2,219
require 'httparty' require 'json' module CricApi class Request include HTTParty base_uri 'https://cricketlive.herokuapp.com' def initialize(service, page) @options = { query: {site: service, page: page} } end def cricket self.class.get("/api/cricket", @options) end def matches self.class.get("/api/matches", @options) end def matchCalendar self.class.get("/api/matchCalendar", @options) end def getNews self.class.get("/api/news", @options) end def cricketScore(id) self.class.post("/api/cricketScore", :body => { :unique_id => id } ) end def playerStats(id) self.class.post("/api/playerStats", :body => { :pid => id } ) end def ballByball(id) self.class.post("/api/ballByBall", :body => { :unique_id => id } ) end def commentry(id) self.class.post("/api/commentry", :body => { :unique_id => id } ) end def news(id) self.class.post("/api/news", :body => { :unique_id => id } ) end def score(id) self.class.post("/api/score", :body => { :unique_id => id } ) end def getLiveScores updates = [] scores = cricket data = scores['data']['data'] data.each do |match| updates.push(cricketScore(match['unique_id'])) end return updates end def liveUpdates match_update = cricket live_updates = matches live_updates['data']['matches'].each do |update| data = match_update['data']['data'] # binding.pry for item in data # binding.pry if item['unique_id'] == update['unique_id'] update['title'] = item['title'] update['description'] = item['description'] # binding.pry break; end end end return live_updates end def jsonRead(filename) file = File.read(filename) data_hash = JSON.parse(file) # file.close return data_hash end end end
18.338843
55
0.521406
1a3f544ac14f942512e131afe2241b131670847b
263
class FakeRSpec @@befores = Hash.new([]) def self.before(scope, &blk) @@befores[scope] << blk end def self.befores @@befores end def self.include(modjewel) super(modjewel) end def self.reset! @@befores = Hash.new([]) end end
13.15
30
0.612167
ffb5d8332124536e007298825f8bc08d16627419
658
#! /usr/bin/env ruby require 'spec_helper' require 'puppet/indirector/run/local' describe Puppet::Run::Local do it "should be a subclass of Puppet::Indirector::Code" do Puppet::Run::Local.superclass.should equal(Puppet::Indirector::Code) end it "should call runner.run on save and return the runner" do Puppet::Status.indirection.stubs(:find).returns Puppet::Status.new runner = Puppet::Run.new runner.stubs(:run).returns(runner) request = Puppet::Indirector::Request.new(:indirection, :save, "anything", nil) request.instance = runner = Puppet::Run.new Puppet::Run::Local.new.save(request).should == runner end end
29.909091
83
0.715805
1dd16a918e35a41a50faef36d31b7c2611f241d7
138
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_ledger_session'
34.5
76
0.804348
61ec4c51bf732245400afbd9f35374b00183473a
133
class AuthorSerializer < ActiveModel::Serializer attributes :id, :first_name, :last_name, :position, :paper_id end
16.625
48
0.691729
bf2a15c9673ea21b7debb375bfcc35cd1bde2c29
2,454
# server-based syntax # ====================== # Defines a single server with a list of roles and multiple properties. # You can define all roles on a single server, or split them: # server "example.com", user: "deploy", roles: %w{app db web}, my_property: :my_value # server "example.com", user: "deploy", roles: %w{app web}, other_property: :other_value # server "db.example.com", user: "deploy", roles: %w{db} # role-based syntax # ================== # Defines a role with one or multiple servers. The primary server in each # group is considered to be the first unless any hosts have the primary # property set. Specify the username and a domain or IP for the server. # Don't use `:all`, it's a meta role. # role :app, %w{[email protected]}, my_property: :my_value # role :web, %w{[email protected] [email protected]}, other_property: :other_value # role :db, %w{[email protected]} role :web, '[email protected]' role :app, '[email protected]' role :db, '[email protected]', :primary => true set :nginx_server_name, 'thing.pennsicuniversity.org' set :puma_preload_app, true set :puma_init_active_record, true set :sidekiq_monit_conf_dir, '/etc/monit/conf-available' set :sidekiq_user, 'explorer' #set :sidekiq_monit_use_sudo, false # Configuration # ============= # You can set any configuration variable like in config/deploy.rb # These variables are then only loaded and set in this stage. # For available Capistrano configuration variables see the documentation page. # http://capistranorb.com/documentation/getting-started/configuration/ # Feel free to add new variables to customise your setup. # Custom SSH Options # ================== # You may pass any option but keep in mind that net/ssh understands a # limited set of options, consult the Net::SSH documentation. # http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start # # Global options # -------------- # set :ssh_options, { # keys: %w(/home/rlisowski/.ssh/id_rsa), # forward_agent: false, # auth_methods: %w(password) # } # # The server-based syntax can be used to override options: # ------------------------------------ # server "example.com", # user: "user_name", # roles: %w{web app}, # ssh_options: { # user: "user_name", # overrides user setting above # keys: %w(/home/user_name/.ssh/id_rsa), # forward_agent: false, # auth_methods: %w(publickey password) # # password: "please use keys" # }
34.56338
88
0.685819
5de6af7f57f1b7ec417566c24aa415798927fd3a
215
module Critical module OutputHandler end end require 'critical/output_handler/base' require 'critical/output_handler/dispatcher' require 'critical/output_handler/deferred' require 'critical/output_handler/text'
23.888889
44
0.84186
7a74709d32e79bbbabead61f72660f0b037dc148
2,380
require 'spec_helper' module Bosh::Director describe Api::DeploymentManager do let(:deployment) { Models::Deployment.make(name: 'DEPLOYMENT_NAME') } let(:task) { double('Task') } let(:username) { 'FAKE_USER' } let(:options) { {foo: 'bar'} } before do Bosh::Director::Models::DirectorAttribute.make(name: 'uuid', value: 'fake-director-uuid') allow(Config).to receive(:base_dir).and_return('/tmp') end describe '#create_deployment' do before do allow(subject).to receive(:write_file) end context 'when sufficient disk space is available' do before do allow(subject).to receive_messages(check_available_disk_space: true) allow(SecureRandom).to receive_messages(uuid: 'FAKE_UUID') allow(Dir).to receive_messages(tmpdir: 'FAKE_TMPDIR') end it 'enqueues a DJ job' do cloud_config = Models::CloudConfig.make runtime_config = Models::RuntimeConfig.make create_task = subject.create_deployment(username, 'FAKE_TMPDIR/deployment-FAKE_UUID', cloud_config, runtime_config, deployment, options) expect(create_task.description).to eq('create deployment') expect(create_task.deployment_name).to eq('DEPLOYMENT_NAME') end it 'passes a nil cloud config id and runtime config id if there is no cloud config or runtime config' do expected_manifest_path = File.join('FAKE_TMPDIR', 'deployment-FAKE_UUID') expect(JobQueue).to receive_message_chain(:new, :enqueue) do |_, job_class, _, params, _| expect(job_class).to eq(Jobs::UpdateDeployment) expect(params).to eq([expected_manifest_path, nil, nil, options]) end subject.create_deployment(username, 'FAKE_TMPDIR/deployment-FAKE_UUID', nil, nil, deployment, options) end end end describe '#delete_deployment' do it 'enqueues a DJ job' do delete_task = subject.delete_deployment(username, deployment, options) expect(delete_task.description).to eq('delete deployment DEPLOYMENT_NAME') expect(delete_task.deployment_name).to eq('DEPLOYMENT_NAME') end end describe '#find_by_name' do it 'finds a deployment by name' do expect(subject.find_by_name(deployment.name)).to eq deployment end end end end
36.615385
146
0.67437
d5c5b1d5fe8773cf502754007f852b0ce06e84c8
355
class ApplicationSerializer < ActiveModel::Serializer attributes :name, :shortname, :archived, :deploy_freeze attribute :status_notes, key: :notes attribute :repo_url, key: :repository_url attribute :default_branch, key: :repository_default_branch attribute :on_aws, key: :hosted_on_aws attribute :cd_enabled?, key: :continuously_deployed end
39.444444
60
0.794366
d5b826f7758ba9564a212649b4e21909bab794c7
129
class ChangeColumnName < ActiveRecord::Migration[6.0] def change rename_column :dailychecklists, :user, :user_id end end
21.5
53
0.75969
ffb935809731702794fcc78ed3aa7043c9a6839b
1,009
module Address class Selling include ActiveModel::Model attr_accessor :cpf, :observation, :cadastre validates :cpf, cpf: true, presence: true validates :observation, presence: true validate :cpf_valid? private def cpf_valid? @cadastre = ::Candidate::Cadastre.find_by_cpf(self.cpf) rescue nil if @cadastre.nil? errors.add(:cpf, 'CPF não existe na base de dados') return false end if %w(1 2 4 5).include? @cadastre.program_id.to_s unless @cadastre.current_situation_id == 4 && @cadastre.current_procedural.procedural_status_id == 8 errors.add(:cpf, 'Situação do CPF não é válida para esta operação') end elsif %w(3 6).include?(@cadastre.program_id.to_s) unless %w(3 4).include?(@cadastre.current_situation_id.to_s) && @cadastre.current_procedural.procedural_status_id == 8 errors.add(:cpf, 'Situação do CPF não é válida para esta operação') end end end end end
28.027778
126
0.662042
911588bb69fbfb67035f5dca09aa457bb39ce3c3
861
Given(/^I am viewing the TodoMVC Vue example$/) do visit('http://todomvc.com/examples/vue/') end When(/^I enter a todo$/) do input = find('.new-todo') input.set('Write Future Sync slides') input.native.send_keys(:return) end Then(/^I see my todo in the list$/) do find('.todo-list .todo label', :text => 'Write Future Sync slides') end Given(/^I have (\d+) todo items in the list$/) do |number| input = find('.new-todo') number.to_i.times do input.set("Todo item #{number}") input.native.send_keys(:return) end page.assert_selector('.todo', :count => number) end When(/^I delete (\d+) todo items$/) do |number| number.to_i.times do first('.destroy', :visible => false, :wait => true).trigger('click') end end Then(/^I see (\d+) todo items in the list$/) do |number| page.assert_selector('.todo', :count => number) end
24.6
72
0.651568
3938feb1ddbec5804c89bbd2b1de5c9906b78e42
239
require 'shopping_cart/engine' module ShoppingCart mattr_accessor :product_class mattr_accessor :user_class def self.product_class @@product_class.constantize end def self.user_class @@user_class.constantize end end
15.933333
31
0.778243
113c745b25aa34804a42b1805da18e8e26f68ef6
523
module Flor class Timer < FlorModel def to_trigger_message d = self.data(false) m = d['message'] m['timer_id'] = self.id sm = d['m'] { 'point' => 'trigger', 'exid' => self.exid, 'nid' => self.onid, 'bnid' => self.nid, 'type' => self.type, 'schedule' => self.schedule, 'timer_id' => self.id, 'message' => m, 'sm' => sm } end def ntime_t @ntime_t ||= Time.parse(ntime) end end end
14.942857
36
0.456979
ffc5cbf18059a18d0a60a885eed70caaea4f6863
311
Sequel.migration do change do create_table :product do primary_key :id BigDecimal :price, size: [10, 2] String :description end create_table :line_item do primary_key :id BigDecimal :quantity, size: [10, 2] foreign_key :product_id, :product end end end
19.4375
42
0.639871
1cddc3ef589c17dc368bf75f14edf7ac8ab60dbe
1,110
cask '[email protected]' do version '2017.4.14f1,b28150134d55' sha256 :no_check url "https://download.unity3d.com/download_unity/b28150134d55/MacEditorTargetInstaller/UnitySetup-iOS-Support-for-Editor-2017.4.14f1.pkg" name 'iOS Build Support' homepage 'https://unity3d.com/unity/' pkg 'UnitySetup-iOS-Support-for-Editor-2017.4.14f1.pkg' depends_on cask: '[email protected]' preflight do if File.exist? "/Applications/Unity" FileUtils.move "/Applications/Unity", "/Applications/Unity.temp" end if File.exist? "/Applications/Unity-2017.4.14f1" FileUtils.move "/Applications/Unity-2017.4.14f1", '/Applications/Unity' end end postflight do if File.exist? '/Applications/Unity' FileUtils.move '/Applications/Unity', "/Applications/Unity-2017.4.14f1" 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.4.14f1/PlaybackEngines/iOSSupport' end
30.833333
139
0.714414
2845a49a379bb0e804f556322e1c194104370bd5
237
class CreateGroups < ActiveRecord::Migration[5.2] def change create_table :groups, id: :uuid do |t| t.references :school, foreign_key: true, type: :uuid, index: true t.string :name t.timestamps end end end
21.545455
71
0.658228
03e17b83b906fb092845a2aea4ad5c86aff2d638
8,320
# ----------------------------------------------------------------------------- # # GEOS implementation additions written in Ruby # # ----------------------------------------------------------------------------- module RGeo module Geos module ZMGeometryMethods # :nodoc: include Feature::Instance def initialize(factory, zgeometry, mgeometry) @factory = factory @zgeometry = zgeometry @mgeometry = mgeometry end def inspect # :nodoc: "#<#{self.class}:0x#{object_id.to_s(16)} #{as_text.inspect}>" end def to_s # :nodoc: as_text end def hash @factory.hash ^ @zgeometry.hash ^ @mgeometry.hash end def factory @factory end def z_geometry @zgeometry end def m_geometry @mgeometry end def dimension @zgeometry.dimension end def geometry_type @zgeometry.geometry_type end def srid @factory.srid end def envelope @factory.create_feature(nil, @zgeometry.envelope, @mgeometry.envelope) end def as_text @factory.instance_variable_get(:@wkt_generator).generate(self) end def as_binary @factory.instance_variable_get(:@wkb_generator).generate(self) end def is_empty? @zgeometry.is_empty? end def is_simple? @zgeometry.is_simple? end def boundary @factory.create_feature(nil, @zgeometry.boundary, @mgeometry.boundary) end def equals?(rhs) @zgeometry.equals?(RGeo::Feature.cast(rhs, self).z_geometry) end def disjoint?(rhs) @zgeometry.disjoint?(RGeo::Feature.cast(rhs, self).z_geometry) end def intersects?(rhs) @zgeometry.intersects?(RGeo::Feature.cast(rhs, self).z_geometry) end def touches?(rhs) @zgeometry.touches?(RGeo::Feature.cast(rhs, self).z_geometry) end def crosses?(rhs) @zgeometry.crosses?(RGeo::Feature.cast(rhs, self).z_geometry) end def within?(rhs) @zgeometry.within?(RGeo::Feature.cast(rhs, self).z_geometry) end def contains?(rhs) @zgeometry.contains?(RGeo::Feature.cast(rhs, self).z_geometry) end def overlaps?(rhs) @zgeometry.overlaps?(RGeo::Feature.cast(rhs, self).z_geometry) end def relate?(rhs, pattern) @zgeometry.relate?(RGeo::Feature.cast(rhs, self).z_geometry, pattern) end alias relate relate? # DEPRECATED def distance(rhs) @zgeometry.distance(RGeo::Feature.cast(rhs, self).z_geometry) end def buffer(distance_) @factory.create_feature(nil, @zgeometry.buffer(distance_), @mgeometry.buffer(distance_)) end def convex_hull @factory.create_feature(nil, @zgeometry.convex_hull, @mgeometry.convex_hull) end def intersection(rhs) rhs = RGeo::Feature.cast(rhs, self) @factory.create_feature(nil, @zgeometry.intersection(rhs.z_geometry), @mgeometry.intersection(rhs.m_geometry)) end def union(rhs) rhs = RGeo::Feature.cast(rhs, self) @factory.create_feature(nil, @zgeometry.union(rhs.z_geometry), @mgeometry.union(rhs.m_geometry)) end def difference(rhs) rhs = RGeo::Feature.cast(rhs, self) @factory.create_feature(nil, @zgeometry.difference(rhs.z_geometry), @mgeometry.difference(rhs.m_geometry)) end def sym_difference(rhs) rhs = RGeo::Feature.cast(rhs, self) @factory.create_feature(nil, @zgeometry.sym_difference(rhs.z_geometry), @mgeometry.sym_difference(rhs.m_geometry)) end def rep_equals?(rhs) rhs = RGeo::Feature.cast(rhs, self) rhs.is_a?(self.class) && @factory.eql?(rhs.factory) && @zgeometry.rep_equals?(rhs.z_geometry) && @mgeometry.rep_equals?(rhs.m_geometry) end alias eql? rep_equals? alias == equals? alias - difference alias + union alias * intersection def marshal_dump # :nodoc: [@factory, @factory.marshal_wkb_generator.generate(self)] end def marshal_load(data) # :nodoc: copy_state_from(data[0].marshal_wkb_parser.parse(data[1])) end def encode_with(coder) # :nodoc: coder["factory"] = @factory coder["wkt"] = @factory.psych_wkt_generator.generate(self) end def init_with(coder) # :nodoc: copy_state_from(coder["factory"].psych_wkt_parser.parse(coder["wkt"])) end private def copy_state_from(obj) @factory = obj.factory @zgeometry = obj.z_geometry @mgeometry = obj.m_geometry end end module ZMPointMethods # :nodoc: def x @zgeometry.x end def y @zgeometry.y end def z @zgeometry.z end def m @mgeometry.m end def coordinates [x, y].tap do |coords| coords << z if @factory.property(:has_z_coordinate) coords << m if @factory.property(:has_m_coordinate) end end end module ZMLineStringMethods # :nodoc: def length @zgeometry.length end def start_point point_n(0) end def end_point point_n(num_points - 1) end def is_closed? @zgeometry.is_closed? end def is_ring? @zgeometry.is_ring? end def num_points @zgeometry.num_points end def point_n(n) @factory.create_feature(ZMPointImpl, @zgeometry.point_n(n), @mgeometry.point_n(n)) end def points result_ = [] zpoints_ = @zgeometry.points mpoints_ = @mgeometry.points zpoints_.size.times do |i_| result_ << @factory.create_feature(ZMPointImpl, zpoints_[i_], mpoints_[i_]) end result_ end def coordinates points.map(&:coordinates) end end module ZMPolygonMethods # :nodoc: def area @zgeometry.area end def centroid @factory.create_feature(ZMPointImpl, @zgeometry.centroid, @mgeometry.centroid) end def point_on_surface @factory.create_feature(ZMPointImpl, @zgeometry.centroid, @mgeometry.centroid) end def exterior_ring @factory.create_feature(ZMLineStringImpl, @zgeometry.exterior_ring, @mgeometry.exterior_ring) end def num_interior_rings @zgeometry.num_interior_rings end def interior_ring_n(n) @factory.create_feature(ZMLineStringImpl, @zgeometry.interior_ring_n(n), @mgeometry.interior_ring_n(n)) end def interior_rings result_ = [] zrings_ = @zgeometry.interior_rings mrings_ = @mgeometry.interior_rings zrings_.size.times do |i_| result_ << @factory.create_feature(ZMLineStringImpl, zrings_[i_], mrings_[i_]) end result_ end def coordinates ([exterior_ring] + interior_rings).map(&:coordinates) end end module ZMGeometryCollectionMethods # :nodoc: def num_geometries @zgeometry.num_geometries end alias size num_geometries def geometry_n(n) @factory.create_feature(nil, @zgeometry.geometry_n(n), @mgeometry.geometry_n(n)) end alias [] geometry_n def each if block_given? num_geometries.times do |i| yield geometry_n(i) end self else enum_for end end include ::Enumerable end module ZMMultiLineStringMethods # :nodoc: def length @zgeometry.length end def is_closed? @zgeometry.is_closed? end def coordinates each.map(&:coordinates) end end module ZMMultiPolygonMethods # :nodoc: def area @zgeometry.area end def centroid @factory.create_feature(ZMPointImpl, @zgeometry.centroid, @mgeometry.centroid) end def point_on_surface @factory.create_feature(ZMPointImpl, @zgeometry.centroid, @mgeometry.centroid) end def coordinates each.map(&:coordinates) end end end end
23.636364
143
0.597837
ace2537fc0ea9e58154ffe3b124dea0b7613789d
1,886
# frozen_string_literal: true module QA module Page module Project module Issue class Index < Page::Base view 'app/helpers/projects_helper.rb' do element :assignee_link end view 'app/views/projects/issues/export_csv/_button.html.haml' do element :export_as_csv_button end view 'app/views/projects/issues/export_csv/_modal.html.haml' do element :export_issues_button element :export_issues_modal end view 'app/views/projects/issues/_issue.html.haml' do element :issue element :issue_link, 'link_to issue.title' # rubocop:disable QA/ElementWithPattern end view 'app/views/shared/issuable/_assignees.html.haml' do element :avatar_counter end view 'app/views/shared/issuable/_nav.html.haml' do element :closed_issues_link end def avatar_counter find_element(:avatar_counter) end def click_issue_link(title) click_link(title) end def click_closed_issues_link click_element :closed_issues_link end def click_export_as_csv_button click_element(:export_as_csv_button) end def click_export_issues_button click_element(:export_issues_button) end def export_issues_modal find_element(:export_issues_modal) end def has_assignee_link_count?(count) all_elements(:assignee_link, count: count) end def has_issue?(issue) has_element? :issue, issue_title: issue.title end end end end end end QA::Page::Project::Issue::Index.prepend_if_ee('QA::EE::Page::Project::Issue::Index')
26.194444
94
0.600212
e837bc8398051c9f774571db10e8dd65d33e5f01
1,157
require 'spec_helper' describe Mocatra do it 'has a version number' do expect(Mocatra::VERSION).not_to be nil end it "returns ok" do get '/' expect(last_response).to be_ok expect(last_response.body).to eq({"version"=>"1", "result"=>"OK"}.to_json) end it "returns 404 not found" do get '/user' expect(last_response.status).to eq 404 expect(last_response.body).to eq({"version"=>"1", "result"=>"not found"}.to_json) end context "when content type is application/json" do it "returns ok" do header "CONTENT_TYPE", "application/json" post('/', "{\"version\":1.1,\"method\":\"index\",\"params\":{\"account\":\"hoge\"}}") expect(last_response).to be_ok expect(last_response.body).to eq({"version"=>"1", "result"=>"OK"}.to_json) end end describe ".record_path" do it "returns the record_path" do expect(Mocatra::App.record_path).to eq File.expand_path("../../records", __FILE__) end end describe ".record_path=" do it "sets the record_path" do Mocatra::App.record_path = "./mocs" expect(Mocatra::App.record_path).to eq "./mocs" end end end
27.547619
91
0.639585
bb0a745a8cda1754787d0cf2ea13e501f3b36bc4
2,688
RSpec.describe 'find pattern' do it 'finds first seven letter word' do words = ["capricious", "berry", "unicorn", "bag", "apple", "festering", "pretzel", "pencil"] found = nil words.each do |word| if word.length == 7 found = word break end end expect(found).to eq("unicorn") end it 'no waldo' do words = ["scarf", "sandcastle", "flag", "pretzel", "crow", "key"] found = nil words.each do |word| # Your code goes here if word == 'waldo' found = word break end end expect(found).to eq(nil) end it 'found waldo' do words = ["noise", "dog", "fair", "house", "waldo", "bucket", "fish"] found = nil # Your code goes here words.each do |word| if word == 'waldo' found = word break end end expect(found).to eq("waldo") end it 'no three letter words' do words = ["piglet", "porridge", "bear", "blueberry"] # Your code goes here found = nil words.each { |word| if word.length == 3 found = word break end } expect(found).to eq(nil) end it 'finds 13' do numbers = [2, 13, 19, 8, 3, 27] # Your code goes here found = nil numbers.each { |num| if num == 13 found = num break end } expect(found).to eq(13) end it 'first even number' do numbers = [3, 7, 13, 11, 10, 2, 17] # Your code goes here found = nil numbers.each { |num| if num.even? found = num break end } expect(found).to eq(10) end it 'first multiple of 3' do numbers = [2, 8, 9, 27, 24, 5] # Your code goes here found = nil numbers.each { |num| if num % 3 == 0 found = num break end } expect(found).to eq(9) end it 'first word starting with q' do words = ["weirdo", "quill", "fast", "quaint", "quitter", "koala"] # Your code goes here found = nil words.each { |word| if word[0] == 'q' found = word break end } expect(found).to eq("quill") end it 'first word ending with er' do words = ["biggest", "pour", "blight", "finger", "pie", "border"] # Your code goes here found = nil words.each { |word| if word[-2..-1] == 'er' found = word break end } expect(found).to eq("finger") end it 'first number greater than 20' do numbers = [1, 8, 19, 21, 29, 31, 34] # Your code goes here found = nil numbers.each { |num| if num > 20 found = num break end } expect(found).to eq(21) end end
18.285714
96
0.517857
e9dc89dcca706ee6193b4b4aa3b896c6e8c9f339
106
require '/tmp/kitchen/spec/spec_helper.rb' describe package('httpd') do it { should be_installed } end
17.666667
42
0.745283
e2226d9db927504d7b2af5335016b2fe5c214dbf
5,331
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress CSS using a preprocessor. # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Include generic and useful information about system operation, but avoid logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). config.log_level = :info # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "flow_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Log disallowed deprecations. config.active_support.disallowed_deprecation = :log # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require "syslog/logger" # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Inserts middleware to perform automatic connection switching. # The `database_selector` hash is used to pass options to the DatabaseSelector # middleware. The `delay` is used to determine how long to wait after a write # to send a subsequent read to the primary. # # The `database_resolver` class is used by the middleware to determine which # database is appropriate to use based on the time delay. # # The `database_resolver_context` class is used by the middleware to set # timestamps for the last write to the primary. The resolver uses the context # class timestamps to determine how long to wait before reading from the # replica. # # By default Rails will store a last write timestamp in the session. The # DatabaseSelector middleware is designed as such you can define your own # strategy for connection switching and pass that into the middleware through # these configuration options. # config.active_record.database_selector = { delay: 2.seconds } # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end
44.057851
114
0.765147
4adaed4b37051a446dd7d8490e7763ca969b6740
232
class CreateProducts < ActiveRecord::Migration def self.up create_table :products do |t| t.string :name, :limit => 255, :null => false t.timestamps end end def self.down drop_table :products end end
17.846154
51
0.655172
265cf9071eb1d511b57b9f290739c3fe7c9bdb77
5,081
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'net/ssh' class MetasploitModule < Msf::Auxiliary include Msf::Auxiliary::Scanner include Msf::Auxiliary::Report include Msf::Auxiliary::CommandShell include Msf::Exploit::Remote::SSH def initialize(info = {}) super(update_info(info, 'Name' => 'SSH Username Enumeration', 'Description' => %q{ This module uses a time-based attack to enumerate users on an OpenSSH server. On some versions of OpenSSH under some configurations, OpenSSH will return a "permission denied" error for an invalid user faster than for a valid user. }, 'Author' => ['kenkeiras'], 'References' => [ ['CVE', '2006-5229'], ['OSVDB', '32721'], ['BID', '20418'] ], 'License' => MSF_LICENSE )) register_options( [ Opt::Proxies, Opt::RPORT(22), OptPath.new('USER_FILE', [true, 'File containing usernames, one per line', nil]), OptInt.new('THRESHOLD', [true, 'Amount of seconds needed before a user is considered ' \ 'found', 10]) ], self.class ) register_advanced_options( [ OptInt.new('RETRY_NUM', [true , 'The number of attempts to connect to a SSH server' \ ' for each user', 3]), OptInt.new('SSH_TIMEOUT', [false, 'Specify the maximum time to negotiate a SSH session', 10]), OptBool.new('SSH_DEBUG', [false, 'Enable SSH debugging output (Extreme verbosity!)', false]) ] ) end def rport datastore['RPORT'] end def retry_num datastore['RETRY_NUM'] end def threshold datastore['THRESHOLD'] end # Returns true if a nonsense username appears active. def check_false_positive(ip) user = Rex::Text.rand_text_alphanumeric(8) result = attempt_user(user, ip) return(result == :success) end def check_user(ip, user, port) pass = Rex::Text.rand_text_alphanumeric(64_000) factory = ssh_socket_factory opt_hash = { :auth_methods => ['password', 'keyboard-interactive'], :port => port, :use_agent => false, :password => pass, :config => false, :proxy => factory, :non_interactive => true } opt_hash.merge!(:verbose => :debug) if datastore['SSH_DEBUG'] start_time = Time.new begin ::Timeout.timeout(datastore['SSH_TIMEOUT']) do Net::SSH.start(ip, user, opt_hash) end rescue Rex::ConnectionError return :connection_error rescue Net::SSH::Disconnect, ::EOFError return :success rescue ::Timeout::Error return :success rescue Net::SSH::Exception end finish_time = Time.new if finish_time - start_time > threshold :success else :fail end end def do_report(ip, user, port) service_data = { address: ip, port: rport, service_name: 'ssh', protocol: 'tcp', workspace_id: myworkspace_id } credential_data = { origin_type: :service, module_fullname: fullname, username: user, }.merge(service_data) login_data = { core: create_credential(credential_data), status: Metasploit::Model::Login::Status::UNTRIED, }.merge(service_data) create_credential_login(login_data) end # Because this isn't using the AuthBrute mixin, we don't have the # usual peer method def peer(rhost=nil) "#{rhost}:#{rport} - SSH -" end def user_list if File.readable? datastore['USER_FILE'] File.new(datastore['USER_FILE']).read.split else raise ArgumentError, "Cannot read file #{datastore['USER_FILE']}" end end def attempt_user(user, ip) attempt_num = 0 ret = nil while attempt_num <= retry_num and (ret.nil? or ret == :connection_error) if attempt_num > 0 Rex.sleep(2 ** attempt_num) vprint_status("#{peer(ip)} Retrying '#{user}' due to connection error") end ret = check_user(ip, user, rport) attempt_num += 1 end ret end def show_result(attempt_result, user, ip) case attempt_result when :success print_good("#{peer(ip)} User '#{user}' found") do_report(ip, user, rport) when :connection_error print_error("#{peer(ip)} User '#{user}' on could not connect") when :fail print_error("#{peer(ip)} User '#{user}' not found") end end def run_host(ip) print_status "#{peer(ip)} Checking for false positives" if check_false_positive(ip) print_error "#{peer(ip)} throws false positive results. Aborting." return else print_status "#{peer(ip)} Starting scan" user_list.each{ |user| show_result(attempt_user(user, ip), user, ip) } end end end
26.05641
85
0.599882
62a6b0e0eca3e30a13e9110c022dc7b51810ddc3
101
module InfluxDB module Arel module Nodes class In < Equality end end end end
11.222222
25
0.613861
7adfed2e716d044ad13070f0431fae722b091cae
1,139
require "spec_helper" describe Multiblock::Wrapper do let(:wrapper) { described_class.new } it "should register block" do wrapper.foo { "foo" } wrapper.call(:foo).should == "foo" end it "should call registered block by String" do wrapper.foo { "foo" } wrapper.call("foo").should == "foo" end it "should return nil when calling unregistered block" do wrapper.call(:foo).should be_nil end it "should return nil when calling unregistered block with arguments" do wrapper.call(:foo).should be_nil end it "should pass arguments to called block" do wrapper.foo { |arg| arg } wrapper.call(:foo, "foo").should == "foo" end it "should raise ArgumentError exception when registering without block" do lambda { wrapper.foo }.should raise_exception(ArgumentError, "No block given when registering 'foo' block.") end context "with custom default block" do let(:wrapper) { described_class.new { "default" } } it "should call custom default block when calling unregistered block" do wrapper.call(:foo).should == "default" end end end
23.729167
91
0.67691
4ad240992b2abf6f4cc57d9798001de9698ab29e
639
# frozen_string_literal: true Capybara::SpecHelper.spec '#frame_title', requires: [:frames] do before do @session.visit('/within_frames') end it 'should return the title in a frame' do @session.within_frame('frameOne') do expect(@session.driver.frame_title).to eq 'This is the title of frame one' end end it 'should return the title in FrameTwo' do @session.within_frame('frameTwo') do expect(@session.driver.frame_title).to eq 'This is the title of frame two' end end it 'should return the title in the main frame' do expect(@session.driver.frame_title).to eq 'With Frames' end end
26.625
80
0.704225
1ad070de1eaa3d505b411eabd99e39c441ed672a
2,185
# frozen_string_literal: true require 'spec_helper' require Rails.root.join( 'db', 'migrate', '20200831222347_insert_project_feature_flags_plan_limits.rb' ) RSpec.describe InsertProjectFeatureFlagsPlanLimits do let(:migration) { described_class.new } let(:plans) { table(:plans) } let(:plan_limits) { table(:plan_limits) } let!(:default_plan) { plans.create!(name: 'default') } let!(:free_plan) { plans.create!(name: 'free') } let!(:bronze_plan) { plans.create!(name: 'bronze') } let!(:silver_plan) { plans.create!(name: 'silver') } let!(:gold_plan) { plans.create!(name: 'gold') } let!(:default_plan_limits) do plan_limits.create!(plan_id: default_plan.id, project_feature_flags: 200) end context 'when on Gitlab.com' do before do expect(Gitlab).to receive(:com?).at_most(:twice).and_return(true) end describe '#up' do it 'updates the project_feature_flags plan limits' do migration.up expect(plan_limits.pluck(:plan_id, :project_feature_flags)).to contain_exactly( [default_plan.id, 200], [free_plan.id, 50], [bronze_plan.id, 100], [silver_plan.id, 150], [gold_plan.id, 200] ) end end describe '#down' do it 'removes the project_feature_flags plan limits' do migration.up migration.down expect(plan_limits.pluck(:plan_id, :project_feature_flags)).to contain_exactly( [default_plan.id, 200], [free_plan.id, 0], [bronze_plan.id, 0], [silver_plan.id, 0], [gold_plan.id, 0] ) end end end context 'when on self-hosted' do before do expect(Gitlab).to receive(:com?).at_most(:twice).and_return(false) end describe '#up' do it 'does not change the plan limits' do migration.up expect(plan_limits.pluck(:project_feature_flags)).to contain_exactly(200) end end describe '#down' do it 'does not change the plan limits' do migration.up migration.down expect(plan_limits.pluck(:project_feature_flags)).to contain_exactly(200) end end end end
26.975309
87
0.639359
bbb29e5b2bf6eb177aa98c6deeeacaee3c94a1ab
40
module SnowSync VERSION = "3.1.6" end
10
19
0.675
ed8cb9f40fb03d93c6a9c8b0a22a03d2d2108b3e
687
class Allocator attr_reader :registers def initialize @registers = [] end def size @registers.size end def allocate(value, at=nil) return allocate_value_at(value, at) if at register = @registers.select { |r| r.free? }.first || grow register.value = value @registers.index register end private def grow register = Register.new @registers.push register register end def allocate_value_at(value, at) @registers[at] = value at end class Register attr_accessor :value def discard @free = true end def free? @free || !@value end def to_s @value.inspect end end end
14.3125
62
0.62591
4a84759210a4a768b76b70408e9d04e2ef540812
562
# frozen_string_literal: true module RTask module TaskStatus # The task has been initialized but has not yet been scheduled. CREATED = 'created' # The task has been scheduled for execution but has not yet begun executing. PENDING = 'pending' # The task is running but has not yet completed. RUNNING = 'running' # The task completed execution successfully. COMPLETED = 'completed' # The task has been canceled. CANCELED = 'canceled' # The task completed due to an exception. FAULTED = 'faulted' end end
23.416667
80
0.688612
edc2a9df0a9f095538bb6c637b35a35c8f30dbcd
1,125
Pod::Spec.new do |s| s.name = "ActionCableClient" s.version = "0.2.5.1" s.summary = "A Swift client for the Rails ActionCable WebSocket server." s.description = <<-DESC ActionCable is a new WebSocket server being released with Rails 5 which makes it easy to add real-time features to your app. This Swift client makes it dead-simple to connect with that server, abstracting away everything except what you need to get going. DESC s.homepage = "https://github.com/danielrhodes/Swift-ActionCableClient" s.license = 'MIT' s.author = { "Daniel Rhodes" => "[email protected]" } s.source = { :git => "https://github.com/danielrhodes/Swift-ActionCableClient.git", :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/danielrhodes' s.pod_target_xcconfig = { 'SWIFT_VERSION' => '5' } s.ios.deployment_target = '10.0' s.tvos.deployment_target = '10.0' s.requires_arc = true s.source_files = 'Source/Classes/**/*' s.frameworks = 'Foundation' s.dependency 'Starscream', '~> 3.1.1' end
46.875
257
0.651556
21c641e819c76e1c1a60bf91f6e9f7c7f79d9cec
3,173
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) $LOAD_PATH.unshift File.expand_path("../..", __FILE__) # Needs to be required and started before danger require "simplecov" SimpleCov.start do add_filter "/spec/" end require "danger" require "webmock" require "webmock/rspec" require "json" Dir["spec/support/**/*.rb"].each { |file| require(file) } RSpec.configure do |config| config.filter_gems_from_backtrace "bundler" config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.shared_context_metadata_behavior = :apply_to_host_groups config.filter_run_when_matching :focus config.example_status_persistence_file_path = "spec/examples.txt" if config.files_to_run.one? config.default_formatter = "doc" end config.disable_monkey_patching! config.order = :random Kernel.srand config.seed # Custom config.include Danger::Support::GitLabHelper, host: :gitlab config.include Danger::Support::GitHubHelper, host: :github config.include Danger::Support::BitbucketServerHelper, host: :bitbucket_server config.include Danger::Support::BitbucketCloudHelper, host: :bitbucket_cloud config.include Danger::Support::VSTSHelper, host: :vsts config.include Danger::Support::CIHelper, use: :ci_helper end # Now that we could be using Danger's plugins in Danger Danger::Plugin.clear_external_plugins WebMock.disable_net_connect!(allow: "coveralls.io") def make_temp_file(contents) file = Tempfile.new("dangefile_tests") file.write contents file end # rubocop:disable Lint/NestedMethodDefinition def testing_ui @output = StringIO.new @err = StringIO.new def @output.winsize [20, 9999] end cork = Cork::Board.new(out: @output, err: @err) def cork.string out.string.gsub(/\e\[([;\d]+)?m/, "") end def cork.err_string err.string.gsub(/\e\[([;\d]+)?m/, "") end cork end # rubocop:enable Lint/NestedMethodDefinition def testing_dangerfile env = Danger::EnvironmentManager.new(stub_env, testing_ui) dm = Danger::Dangerfile.new(env, testing_ui) end def fixture_txt(file) File.read("spec/fixtures/#{file}.txt") end def fixture(file) File.read("spec/fixtures/#{file}.json") end def comment_fixture(file) File.read("spec/fixtures/#{file}.html") end def diff_fixture(file) File.read("spec/fixtures/#{file}.diff") end def violation_factory(message, sticky: false, file: nil, line: nil) Danger::Violation.new(message, sticky, file, line) end def violations_factory(messages, sticky: false) messages.map { |s| violation_factory(s, sticky: sticky) } end def markdown_factory(message) Danger::Markdown.new(message) end def markdowns_factory(messages) messages.map { |s| markdown_factory(s) } end def with_git_repo(origin: "[email protected]:artsy/eigen") Dir.mktmpdir do |dir| Dir.chdir dir do `git init` File.open(dir + "/file1", "w") {} `git add .` `git commit -m "ok"` `git checkout -b new --quiet` File.open(dir + "/file2", "w") {} `git add .` `git commit -m "another"` `git remote add origin #{origin}` yield dir end end end
24.596899
80
0.720769
3846394b81a22ed69fab988c1982ba15401dc343
4,777
require 'json' require 'salus/scanners/node_audit' # Yarn Audit scanner integration. Flags known malicious or vulnerable # dependencies in javascript projects that are packaged with yarn. # https://yarnpkg.com/en/docs/cli/audit module Salus::Scanners class YarnAudit < NodeAudit # the command was previously 'yarn audit --json', which had memory allocation issues # see https://github.com/yarnpkg/yarn/issues/7404 AUDIT_COMMAND = 'yarn audit --no-color'.freeze def should_run? @repository.yarn_lock_present? end def run shell_return = Dir.chdir(@repository.path_to_repo) do command = "#{AUDIT_COMMAND} #{scan_deps}" shell_return = run_shell(command) excpts = @config.fetch('exceptions', []).map { |e| e["advisory_id"].to_i } report_info(:ignored_cves, excpts) return report_success if shell_return.success? stdout_lines = shell_return.stdout.split("\n") table_start_pos = stdout_lines.index { |l| l.start_with?("┌─") && l.end_with?("─┐") } table_end_pos = stdout_lines.rindex { |l| l.start_with?("└─") && l.end_with?("─┘") } # if no table in output if table_start_pos.nil? || table_end_pos.nil? report_error(shell_return.stderr, status: shell_return.status) report_stderr(shell_return.stderr) return report_failure end table_lines = stdout_lines[table_start_pos..table_end_pos] # lines contain 1 or more vuln tables vulns = parse_output(table_lines) vuln_ids = vulns.map { |v| v['ID'] } report_info(:vulnerabilities, vuln_ids.uniq) vulns.reject! { |v| excpts.include?(v['ID']) } # vulns were all whitelisted return report_success if vulns.empty? log(format_vulns(vulns)) report_stdout(vulns.to_json) report_failure end end def version shell_return = run_shell('yarn audit --version') # stdout looks like "1.22.0\n" shell_return.stdout&.strip end private def parse_output(lines) vulns = Set.new i = 0 while i < lines.size if lines[i].start_with?("┌─") && lines[i].end_with?("─┐") vuln = {} elsif lines[i].start_with? "│ " line_split = lines[i].split("│") curr_key = line_split[1].strip val = line_split[2].strip if curr_key != "" && curr_key != 'Path' vuln[curr_key] = val prev_key = curr_key elsif curr_key == 'Path' prev_key = curr_key elsif prev_key != 'Path' vuln[prev_key] += ' ' + val end elsif lines[i].start_with?("└─") && lines[i].end_with?("─┘") vulns.add(vuln) end i += 1 end vulns = vulns.to_a vulns.each { |vln| normalize_vuln(vln) }.sort { |a, b| a['ID'] <=> b['ID'] } end def scan_deps dep_types = @config.fetch('exclude_groups', []) return '' if dep_types.empty? if dep_types.include?('devDependencies') && dep_types.include?('dependencies') && dep_types.include?('optionalDependencies') report_error("No dependencies were scanned!") return '' elsif dep_types.include?('devDependencies') && dep_types.include?('dependencies') report_warn(:scanner_misconfiguration, "Scanning only optionalDependencies!") end command = ' --groups ' command << 'dependencies ' unless dep_types.include?('dependencies') command << 'devDependencies ' unless dep_types.include?('devDependencies') command << 'optionalDependencies ' unless dep_types.include?('optionalDependencies') end # severity and vuln title in the yarn output looks like # | low | Prototype Pollution | # which are stored in the vuln hash as "low" ==> "Prototype Pollution" # need to update that to # 1) "severity" => "low" # 2) "title" => "Prototype Pollution" # # Also, add a separate id field def normalize_vuln(vuln) sev_levels = %w[info low moderate high critical] sev_levels.each do |sev| if vuln[sev] vuln['Severity'] = sev vuln['Title'] = vuln[sev] vuln.delete(sev) break end end # "More info" looks like https://www.npmjs.com/advisories/1179 # need to extract the id at the end id = vuln["More info"].split("https://www.npmjs.com/advisories/")[1] vuln['ID'] = id.to_i end def format_vulns(vulns) str = "" vulns.each do |vul| vul.each do |k, v| str += "#{k}: #{v}\n" end str += "\n" end str end end end
31.635762
93
0.59305
2106401b1b48de541474a9202c4dd06cc924fc63
2,390
# frozen_string_literal: true module RuboCop module Cop module Style # Enforces that optional keyword parameters are placed at the # end of the parameters list. # # This improves readability, because when looking through the source, # it is expected to find required parameters at the beginning of parameters list # and optional parameters at the end. # # @example # # bad # def some_method(first: false, second:, third: 10) # # body omitted # end # # # good # def some_method(second:, first: false, third: 10) # # body omitted # end # # # bad # do_something do |first: false, second:, third: 10| # # body omitted # end # # # good # do_something do |second:, first: false, third: 10| # # body omitted # end # class KeywordParametersOrder < Base include RangeHelp extend AutoCorrector MSG = 'Place optional keyword parameters at the end of the parameters list.' def on_kwoptarg(node) kwarg_nodes = node.right_siblings.select(&:kwarg_type?) return if kwarg_nodes.empty? add_offense(node) do |corrector| if node.parent.find(&:kwoptarg_type?) == node corrector.insert_before(node, "#{kwarg_nodes.map(&:source).join(', ')}, ") arguments = node.each_ancestor(:def, :defs, :block).first.arguments append_newline_to_last_kwoptarg(arguments, corrector) unless parentheses?(arguments) remove_kwargs(kwarg_nodes, corrector) end end end private def append_newline_to_last_kwoptarg(arguments, corrector) last_argument = arguments.last return if last_argument.kwrestarg_type? || last_argument.blockarg_type? last_kwoptarg = arguments.reverse.find(&:kwoptarg_type?) corrector.insert_after(last_kwoptarg, "\n") unless arguments.parent.block_type? end def remove_kwargs(kwarg_nodes, corrector) kwarg_nodes.each do |kwarg| with_space = range_with_surrounding_space(range: kwarg.source_range) corrector.remove(range_with_surrounding_comma(with_space, :left)) end end end end end end
31.447368
98
0.60795
38da647885d3146cc5a27bfc9e9d5fc1f37c4613
1,286
# frozen_string_literal: true require 'singleton' module Apress module Api module Callbacks class Config include Singleton class << self delegate :add_service, :services, to: :instance delegate :allowed_client?, :add_client, to: :instance delegate :add_handler, :handlers, to: :instance delegate :valid_event?, to: :instance end def add_service(event:, service:) events[event] << service end def add_handler(service:, event:, handler:) (handlers_config[service][event] ||= []) << handler end def add_client(access_id) clients << access_id end def allowed_client?(client) clients.include?(client.access_id) end def services(event) events[event] end def handlers(service:, event:) handlers_config.fetch(service).fetch(event) end private def handlers_config @handlers_config ||= ::Hash.new { |hash, key| hash[key] = {} } end def events @events ||= ::Hash.new { |hash, key| hash[key] = [] } end def clients @clients ||= Set.new end end end end end
22.172414
72
0.550544
5d6036b4ea62b658412f9f10e1fa4564408edfb0
805
# frozen_string_literal: true module Valkyrie::Persistence::Postgres module ORM # ActiveRecord class which the Postgres adapter uses for persisting data. # @!attribute id # @return [UUID] ID of the record # @!attribute metadata # @return [Hash] Hash of all metadata. # @!attribute created_at # @return [DateTime] Date created # @!attribute updated_at # @return [DateTime] Date updated # @!attribute internal_resource # @return [String] Name of {Valkyrie::Resource} model - used for casting. # class Resource < ActiveRecord::Base def disable_optimistic_locking! @disable_optimistic_locking = true end def locking_enabled? return false if @disable_optimistic_locking true end end end end
28.75
79
0.667081
e81b77ccc5649186cee84538b5a84c25b035f11d
979
set :application, 't4c' set :repo_url, '[email protected]:sigmike/code4gamecredits.git' # ask :branch, proc { `git rev-parse --abbrev-ref HEAD`.chomp } set :deploy_to, "/home/apps/p4c" set :scm, :git set :rvm_type, :user set :rvm_ruby_version, '2.0.0-p247' set :rvm_custom_path, '~/.rvm' set :format, :pretty # set :log_level, :debug # set :pty, true set :linked_files, %w{config/database.yml config/config.yml} set :linked_dirs, %w{log tmp} # set :default_env, { path: "/opt/ruby/bin:$PATH" } set :keep_releases, 5 namespace :deploy do desc 'Restart application' task :restart do on roles(:app), in: :sequence, wait: 5 do execute :touch, release_path.join('tmp/restart.txt') end end after :restart, :clear_cache do on roles(:web), in: :groups, limit: 3, wait: 10 do # Here we can do anything such as: # within release_path do # execute :rake, 'cache:clear' # end end end after :finishing, 'deploy:cleanup' end
22.25
63
0.663943
873068f9eb7652f4244a10e961625335369f4274
256
# frozen_string_literal: true module Interactive class Render def initialize(item) @item = item end def call " id:#{@item.id}\n\n done:\n#{@item.done}\n\n title:\n#{@item.title}\n\n body:\n#{@item.body}" end end end
16
104
0.59375
6a26eae2a3e73901b17f48e4d0a94a29be7e842d
13,129
# Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. # Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key` # by default. You can change it below and use your own secret key. # config.secret_key = '9d3483a5bf63e8d05b6b763eb69f38258c5317df9dc436e70f54c2b046b392e171ce7d711c2bac5c5ccc872dd7aab5aafd8b7a8bbeeceeb866f339b2b12b17b4' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = '[email protected]' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [:email] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # encryptor), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = '181f67758249ca2a73fe05c6fc9cadd4e2771cc974ca607d1a0c092492711ec31a6584299b476d7a4989dcc47d623ffc7061a3a0d1667786a9280b3697154c92' # Send a notification email when the user's password is changed # config.send_password_change_notification = false # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in # unconfirmed_email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # Invalidates all the remember me tokens when the user signs out. config.expire_all_remember_me_on_sign_out = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. config.password_length = 8..72 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = true # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # When set to false, does not sign a user in automatically after their password is # reset. Defaults to true, so a user is signed in automatically after a reset. # config.sign_in_after_reset_password = true # ==> Configuration for :encryptable # Allow you to use another encryption algorithm besides bcrypt (default). You can use # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) # and :restful_authentication_sha1 (then you should set stretches to 10, and copy # REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using OmniAuth, Devise cannot automatically set OmniAuth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' end
49.357143
154
0.75139
ab6e8bd85b91a8f7efe901175f169c6525f79637
604
require 'test_helper' module Elasticsearch module Test class XPackLicenseDeleteTest < Minitest::Test context "License: Delete" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal '_xpack/license', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.license.delete end end end end end
22.37037
79
0.614238
212a698b2018263042bad556d6e0e25eecdc3f83
2,783
# -*- encoding: utf-8 -*- # stub: selenium-webdriver 3.142.7 ruby lib Gem::Specification.new do |s| s.name = "selenium-webdriver".freeze s.version = "3.142.7" s.required_rubygems_version = Gem::Requirement.new("> 1.3.1".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "changelog_uri" => "https://github.com/SeleniumHQ/selenium/blob/master/rb/CHANGES", "source_code_uri" => "https://github.com/SeleniumHQ/selenium/tree/master/rb" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["Alex Rodionov".freeze, "Titus Fortner".freeze, "Thomas Walpole".freeze] s.date = "2019-12-27" s.description = "WebDriver is a tool for writing automated tests of websites. It aims to mimic the behaviour of a real user, and as such interacts with the HTML of the application.".freeze s.email = ["[email protected]".freeze, "[email protected]".freeze, "[email protected]".freeze] s.homepage = "https://github.com/SeleniumHQ/selenium".freeze s.licenses = ["Apache-2.0".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.3".freeze) s.rubygems_version = "3.2.7".freeze s.summary = "The next generation developer focused tool for automated testing of webapps".freeze s.installed_by_version = "3.2.7" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 end if s.respond_to? :add_runtime_dependency then s.add_runtime_dependency(%q<childprocess>.freeze, [">= 0.5", "< 4.0"]) s.add_runtime_dependency(%q<rubyzip>.freeze, [">= 1.2.2"]) s.add_development_dependency(%q<ffi>.freeze, [">= 0"]) s.add_development_dependency(%q<rack>.freeze, ["~> 2.0"]) s.add_development_dependency(%q<rake>.freeze, [">= 0"]) s.add_development_dependency(%q<rspec>.freeze, ["~> 3.0"]) s.add_development_dependency(%q<rubocop>.freeze, ["~> 0.67.0"]) s.add_development_dependency(%q<rubocop-performance>.freeze, [">= 0"]) s.add_development_dependency(%q<rubocop-rspec>.freeze, [">= 0"]) s.add_development_dependency(%q<webmock>.freeze, ["~> 3.5"]) s.add_development_dependency(%q<yard>.freeze, ["~> 0.9.11"]) else s.add_dependency(%q<childprocess>.freeze, [">= 0.5", "< 4.0"]) s.add_dependency(%q<rubyzip>.freeze, [">= 1.2.2"]) s.add_dependency(%q<ffi>.freeze, [">= 0"]) s.add_dependency(%q<rack>.freeze, ["~> 2.0"]) s.add_dependency(%q<rake>.freeze, [">= 0"]) s.add_dependency(%q<rspec>.freeze, ["~> 3.0"]) s.add_dependency(%q<rubocop>.freeze, ["~> 0.67.0"]) s.add_dependency(%q<rubocop-performance>.freeze, [">= 0"]) s.add_dependency(%q<rubocop-rspec>.freeze, [">= 0"]) s.add_dependency(%q<webmock>.freeze, ["~> 3.5"]) s.add_dependency(%q<yard>.freeze, ["~> 0.9.11"]) end end
52.509434
207
0.678764
e962c04383a13d1eee5e3816401c24fd59f43e35
34,319
# frozen_string_literal: true # = net/smtp.rb # # Copyright (c) 1999-2007 Yukihiro Matsumoto. # # Copyright (c) 1999-2007 Minero Aoki. # # Written & maintained by Minero Aoki <[email protected]>. # # Documented by William Webber and Minero Aoki. # # This program is free software. You can re-distribute and/or # modify this program under the same terms as Ruby itself. # # $Id$ # # See Net::SMTP for documentation. # require 'net/protocol' require 'digest/md5' require 'timeout' begin require 'openssl' rescue LoadError end module Net # Module mixed in to all SMTP error classes module SMTPError # This *class* is a module for backward compatibility. # In later release, this module becomes a class. attr_reader :response def initialize(response, message: nil) @response = response @message = message end def message @message || response.message end end # Represents an SMTP authentication error. class SMTPAuthenticationError < ProtoAuthError include SMTPError end # Represents SMTP error code 4xx, a temporary error. class SMTPServerBusy < ProtoServerError include SMTPError end # Represents an SMTP command syntax error (error code 500) class SMTPSyntaxError < ProtoSyntaxError include SMTPError end # Represents a fatal SMTP error (error code 5xx, except for 500) class SMTPFatalError < ProtoFatalError include SMTPError end # Unexpected reply code returned from server. class SMTPUnknownError < ProtoUnknownError include SMTPError end # Command is not supported on server. class SMTPUnsupportedCommand < ProtocolError include SMTPError end # # == What is This Library? # # This library provides functionality to send internet # mail via SMTP, the Simple Mail Transfer Protocol. For details of # SMTP itself, see [RFC2821] (http://www.ietf.org/rfc/rfc2821.txt). # # == What is This Library NOT? # # This library does NOT provide functions to compose internet mails. # You must create them by yourself. If you want better mail support, # try RubyMail or TMail or search for alternatives in # {RubyGems.org}[https://rubygems.org/] or {The Ruby # Toolbox}[https://www.ruby-toolbox.com/]. # # FYI: the official documentation on internet mail is: [RFC2822] (http://www.ietf.org/rfc/rfc2822.txt). # # == Examples # # === Sending Messages # # You must open a connection to an SMTP server before sending messages. # The first argument is the address of your SMTP server, and the second # argument is the port number. Using SMTP.start with a block is the simplest # way to do this. This way, the SMTP connection is closed automatically # after the block is executed. # # require 'net/smtp' # Net::SMTP.start('your.smtp.server', 25) do |smtp| # # Use the SMTP object smtp only in this block. # end # # Replace 'your.smtp.server' with your SMTP server. Normally # your system manager or internet provider supplies a server # for you. # # Then you can send messages. # # msgstr = <<END_OF_MESSAGE # From: Your Name <[email protected]> # To: Destination Address <[email protected]> # Subject: test message # Date: Sat, 23 Jun 2001 16:26:43 +0900 # Message-Id: <[email protected]> # # This is a test message. # END_OF_MESSAGE # # require 'net/smtp' # Net::SMTP.start('your.smtp.server', 25) do |smtp| # smtp.send_message msgstr, # '[email protected]', # '[email protected]' # end # # === Closing the Session # # You MUST close the SMTP session after sending messages, by calling # the #finish method: # # # using SMTP#finish # smtp = Net::SMTP.start('your.smtp.server', 25) # smtp.send_message msgstr, 'from@address', 'to@address' # smtp.finish # # You can also use the block form of SMTP.start/SMTP#start. This closes # the SMTP session automatically: # # # using block form of SMTP.start # Net::SMTP.start('your.smtp.server', 25) do |smtp| # smtp.send_message msgstr, 'from@address', 'to@address' # end # # I strongly recommend this scheme. This form is simpler and more robust. # # === HELO domain # # In almost all situations, you must provide a third argument # to SMTP.start/SMTP#start. This is the domain name which you are on # (the host to send mail from). It is called the "HELO domain". # The SMTP server will judge whether it should send or reject # the SMTP session by inspecting the HELO domain. # # Net::SMTP.start('your.smtp.server', 25 # helo: 'mail.from.domain') { |smtp| ... } # # === SMTP Authentication # # The Net::SMTP class supports three authentication schemes; # PLAIN, LOGIN and CRAM MD5. (SMTP Authentication: [RFC2554]) # To use SMTP authentication, pass extra arguments to # SMTP.start/SMTP#start. # # # PLAIN # Net::SMTP.start('your.smtp.server', 25 # user: 'Your Account', secret: 'Your Password', authtype: :plain) # # LOGIN # Net::SMTP.start('your.smtp.server', 25 # user: 'Your Account', secret: 'Your Password', authtype: :login) # # # CRAM MD5 # Net::SMTP.start('your.smtp.server', 25 # user: 'Your Account', secret: 'Your Password', authtype: :cram_md5) # class SMTP < Protocol VERSION = "0.2.1" Revision = %q$Revision$.split[1] # The default SMTP port number, 25. def SMTP.default_port 25 end # The default mail submission port number, 587. def SMTP.default_submission_port 587 end # The default SMTPS port number, 465. def SMTP.default_tls_port 465 end class << self alias default_ssl_port default_tls_port end def SMTP.default_ssl_context(ssl_context_params = nil) context = OpenSSL::SSL::SSLContext.new context.set_params(ssl_context_params ? ssl_context_params : {}) context end # # Creates a new Net::SMTP object. # # +address+ is the hostname or ip address of your SMTP # server. +port+ is the port to connect to; it defaults to # port 25. # # This method does not open the TCP connection. You can use # SMTP.start instead of SMTP.new if you want to do everything # at once. Otherwise, follow SMTP.new with SMTP#start. # def initialize(address, port = nil) @address = address @port = (port || SMTP.default_port) @esmtp = true @capabilities = nil @socket = nil @started = false @open_timeout = 30 @read_timeout = 60 @error_occurred = false @debug_output = nil @tls = false @starttls = :auto @ssl_context_tls = nil @ssl_context_starttls = nil end # Provide human-readable stringification of class state. def inspect "#<#{self.class} #{@address}:#{@port} started=#{@started}>" end # # Set whether to use ESMTP or not. This should be done before # calling #start. Note that if #start is called in ESMTP mode, # and the connection fails due to a ProtocolError, the SMTP # object will automatically switch to plain SMTP mode and # retry (but not vice versa). # attr_accessor :esmtp # +true+ if the SMTP object uses ESMTP (which it does by default). alias :esmtp? :esmtp # true if server advertises STARTTLS. # You cannot get valid value before opening SMTP session. def capable_starttls? capable?('STARTTLS') end def capable?(key) return nil unless @capabilities @capabilities[key] ? true : false end private :capable? # true if server advertises AUTH PLAIN. # You cannot get valid value before opening SMTP session. def capable_plain_auth? auth_capable?('PLAIN') end # true if server advertises AUTH LOGIN. # You cannot get valid value before opening SMTP session. def capable_login_auth? auth_capable?('LOGIN') end # true if server advertises AUTH CRAM-MD5. # You cannot get valid value before opening SMTP session. def capable_cram_md5_auth? auth_capable?('CRAM-MD5') end def auth_capable?(type) return nil unless @capabilities return false unless @capabilities['AUTH'] @capabilities['AUTH'].include?(type) end private :auth_capable? # Returns supported authentication methods on this server. # You cannot get valid value before opening SMTP session. def capable_auth_types return [] unless @capabilities return [] unless @capabilities['AUTH'] @capabilities['AUTH'] end # true if this object uses SMTP/TLS (SMTPS). def tls? @tls end alias ssl? tls? # Enables SMTP/TLS (SMTPS: SMTP over direct TLS connection) for # this object. Must be called before the connection is established # to have any effect. +context+ is a OpenSSL::SSL::SSLContext object. def enable_tls(context = nil) raise 'openssl library not installed' unless defined?(OpenSSL::VERSION) raise ArgumentError, "SMTPS and STARTTLS is exclusive" if @starttls == :always @tls = true @ssl_context_tls = context end alias enable_ssl enable_tls # Disables SMTP/TLS for this object. Must be called before the # connection is established to have any effect. def disable_tls @tls = false @ssl_context_tls = nil end alias disable_ssl disable_tls # Returns truth value if this object uses STARTTLS. # If this object always uses STARTTLS, returns :always. # If this object uses STARTTLS when the server support TLS, returns :auto. def starttls? @starttls end # true if this object uses STARTTLS. def starttls_always? @starttls == :always end # true if this object uses STARTTLS when server advertises STARTTLS. def starttls_auto? @starttls == :auto end # Enables SMTP/TLS (STARTTLS) for this object. # +context+ is a OpenSSL::SSL::SSLContext object. def enable_starttls(context = nil) raise 'openssl library not installed' unless defined?(OpenSSL::VERSION) raise ArgumentError, "SMTPS and STARTTLS is exclusive" if @tls @starttls = :always @ssl_context_starttls = context end # Enables SMTP/TLS (STARTTLS) for this object if server accepts. # +context+ is a OpenSSL::SSL::SSLContext object. def enable_starttls_auto(context = nil) raise 'openssl library not installed' unless defined?(OpenSSL::VERSION) raise ArgumentError, "SMTPS and STARTTLS is exclusive" if @tls @starttls = :auto @ssl_context_starttls = context end # Disables SMTP/TLS (STARTTLS) for this object. Must be called # before the connection is established to have any effect. def disable_starttls @starttls = false @ssl_context_starttls = nil end # The address of the SMTP server to connect to. attr_reader :address # The port number of the SMTP server to connect to. attr_reader :port # Seconds to wait while attempting to open a connection. # If the connection cannot be opened within this time, a # Net::OpenTimeout is raised. The default value is 30 seconds. attr_accessor :open_timeout # Seconds to wait while reading one block (by one read(2) call). # If the read(2) call does not complete within this time, a # Net::ReadTimeout is raised. The default value is 60 seconds. attr_reader :read_timeout # Set the number of seconds to wait until timing-out a read(2) # call. def read_timeout=(sec) @socket.read_timeout = sec if @socket @read_timeout = sec end # # WARNING: This method causes serious security holes. # Use this method for only debugging. # # Set an output stream for debug logging. # You must call this before #start. # # # example # smtp = Net::SMTP.new(addr, port) # smtp.set_debug_output $stderr # smtp.start do |smtp| # .... # end # def debug_output=(arg) @debug_output = arg end alias set_debug_output debug_output= # # SMTP session control # # # :call-seq: # start(address, port = nil, helo: 'localhost', user: nil, secret: nil, authtype: nil, tls_verify: true, tls_hostname: nil, ssl_context_params: nil) { |smtp| ... } # start(address, port = nil, helo = 'localhost', user = nil, secret = nil, authtype = nil) { |smtp| ... } # # Creates a new Net::SMTP object and connects to the server. # # This method is equivalent to: # # Net::SMTP.new(address, port).start(helo: helo_domain, user: account, secret: password, authtype: authtype, tls_verify: flag, tls_hostname: hostname, ssl_context_params: nil) # # === Example # # Net::SMTP.start('your.smtp.server') do |smtp| # smtp.send_message msgstr, '[email protected]', ['[email protected]'] # end # # === Block Usage # # If called with a block, the newly-opened Net::SMTP object is yielded # to the block, and automatically closed when the block finishes. If called # without a block, the newly-opened Net::SMTP object is returned to # the caller, and it is the caller's responsibility to close it when # finished. # # === Parameters # # +address+ is the hostname or ip address of your smtp server. # # +port+ is the port to connect to; it defaults to port 25. # # +helo+ is the _HELO_ _domain_ provided by the client to the # server (see overview comments); it defaults to 'localhost'. # # The remaining arguments are used for SMTP authentication, if required # or desired. +user+ is the account name; +secret+ is your password # or other authentication token; and +authtype+ is the authentication # type, one of :plain, :login, or :cram_md5. See the discussion of # SMTP Authentication in the overview notes. # If +tls_verify+ is true, verify the server's certificate. The default is true. # If the hostname in the server certificate is different from +address+, # it can be specified with +tls_hostname+. # # Additional SSLContext params can be added to +ssl_context_params+ hash argument and are passed to # +OpenSSL::SSL::SSLContext#set_params+ # # +tls_verify: true+ is equivalent to +ssl_context_params: { verify_mode: OpenSSL::SSL::VERIFY_PEER }+. # # === Errors # # This method may raise: # # * Net::SMTPAuthenticationError # * Net::SMTPServerBusy # * Net::SMTPSyntaxError # * Net::SMTPFatalError # * Net::SMTPUnknownError # * Net::OpenTimeout # * Net::ReadTimeout # * IOError # def SMTP.start(address, port = nil, *args, helo: nil, user: nil, secret: nil, password: nil, authtype: nil, tls_verify: true, tls_hostname: nil, ssl_context_params: nil, &block) raise ArgumentError, "wrong number of arguments (given #{args.size + 2}, expected 1..6)" if args.size > 4 helo ||= args[0] || 'localhost' user ||= args[1] secret ||= password || args[2] authtype ||= args[3] new(address, port).start(helo: helo, user: user, secret: secret, authtype: authtype, tls_verify: tls_verify, tls_hostname: tls_hostname, ssl_context_params: ssl_context_params, &block) end # +true+ if the SMTP session has been started. def started? @started end # # :call-seq: # start(helo: 'localhost', user: nil, secret: nil, authtype: nil, tls_verify: true, tls_hostname: nil, ssl_context_params: nil) { |smtp| ... } # start(helo = 'localhost', user = nil, secret = nil, authtype = nil) { |smtp| ... } # # Opens a TCP connection and starts the SMTP session. # # === Parameters # # +helo+ is the _HELO_ _domain_ that you'll dispatch mails from; see # the discussion in the overview notes. # # If both of +user+ and +secret+ are given, SMTP authentication # will be attempted using the AUTH command. +authtype+ specifies # the type of authentication to attempt; it must be one of # :login, :plain, and :cram_md5. See the notes on SMTP Authentication # in the overview. # If +tls_verify+ is true, verify the server's certificate. The default is true. # If the hostname in the server certificate is different from +address+, # it can be specified with +tls_hostname+. # # Additional SSLContext params can be added to +ssl_context_params+ hash argument and are passed to # +OpenSSL::SSL::SSLContext#set_params+ # # +tls_verify: true+ is equivalent to +ssl_context_params: { verify_mode: OpenSSL::SSL::VERIFY_PEER }+. # # === Block Usage # # When this methods is called with a block, the newly-started SMTP # object is yielded to the block, and automatically closed after # the block call finishes. Otherwise, it is the caller's # responsibility to close the session when finished. # # === Example # # This is very similar to the class method SMTP.start. # # require 'net/smtp' # smtp = Net::SMTP.new('smtp.mail.server', 25) # smtp.start(helo: helo_domain, user: account, secret: password, authtype: authtype) do |smtp| # smtp.send_message msgstr, '[email protected]', ['[email protected]'] # end # # The primary use of this method (as opposed to SMTP.start) # is probably to set debugging (#set_debug_output) or ESMTP # (#esmtp=), which must be done before the session is # started. # # === Errors # # If session has already been started, an IOError will be raised. # # This method may raise: # # * Net::SMTPAuthenticationError # * Net::SMTPServerBusy # * Net::SMTPSyntaxError # * Net::SMTPFatalError # * Net::SMTPUnknownError # * Net::OpenTimeout # * Net::ReadTimeout # * IOError # def start(*args, helo: nil, user: nil, secret: nil, password: nil, authtype: nil, tls_verify: true, tls_hostname: nil, ssl_context_params: nil) raise ArgumentError, "wrong number of arguments (given #{args.size}, expected 0..4)" if args.size > 4 helo ||= args[0] || 'localhost' user ||= args[1] secret ||= password || args[2] authtype ||= args[3] if defined?(OpenSSL::VERSION) ssl_context_params = ssl_context_params ? ssl_context_params : {} unless ssl_context_params.has_key?(:verify_mode) ssl_context_params[:verify_mode] = tls_verify ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE end if @tls && @ssl_context_tls.nil? @ssl_context_tls = SMTP.default_ssl_context(ssl_context_params) end if @starttls && @ssl_context_starttls.nil? @ssl_context_starttls = SMTP.default_ssl_context(ssl_context_params) end @tls_hostname = tls_hostname end if block_given? begin do_start helo, user, secret, authtype return yield(self) ensure do_finish end else do_start helo, user, secret, authtype return self end end # Finishes the SMTP session and closes TCP connection. # Raises IOError if not started. def finish raise IOError, 'not yet started' unless started? do_finish end private def tcp_socket(address, port) begin Socket.tcp address, port, nil, nil, connect_timeout: @open_timeout rescue Errno::ETIMEDOUT #raise Net:OpenTimeout instead for compatibility with previous versions raise Net::OpenTimeout, "Timeout to open TCP connection to "\ "#{address}:#{port} (exceeds #{@open_timeout} seconds)" end end def do_start(helo_domain, user, secret, authtype) raise IOError, 'SMTP session already started' if @started if user or secret check_auth_method(authtype || DEFAULT_AUTH_TYPE) check_auth_args user, secret end s = tcp_socket(@address, @port) logging "Connection opened: #{@address}:#{@port}" @socket = new_internet_message_io(tls? ? tlsconnect(s, @ssl_context_tls) : s) check_response critical { recv_response() } do_helo helo_domain if ! tls? and (starttls_always? or (capable_starttls? and starttls_auto?)) unless capable_starttls? raise SMTPUnsupportedCommand.new(nil, message: "STARTTLS is not supported on this server") end starttls @socket = new_internet_message_io(tlsconnect(s, @ssl_context_starttls)) # helo response may be different after STARTTLS do_helo helo_domain end authenticate user, secret, (authtype || DEFAULT_AUTH_TYPE) if user @started = true ensure unless @started # authentication failed, cancel connection. s.close if s @socket = nil end end def ssl_socket(socket, context) OpenSSL::SSL::SSLSocket.new socket, context end def tlsconnect(s, context) verified = false s = ssl_socket(s, context) logging "TLS connection started" s.sync_close = true s.hostname = @tls_hostname || @address ssl_socket_connect(s, @open_timeout) verified = true s ensure s.close unless verified end def new_internet_message_io(s) InternetMessageIO.new(s, read_timeout: @read_timeout, debug_output: @debug_output) end def do_helo(helo_domain) res = @esmtp ? ehlo(helo_domain) : helo(helo_domain) @capabilities = res.capabilities rescue SMTPError if @esmtp @esmtp = false @error_occurred = false retry end raise end def do_finish quit if @socket and not @socket.closed? and not @error_occurred ensure @started = false @error_occurred = false @socket.close if @socket @socket = nil end # # Message Sending # public # # Sends +msgstr+ as a message. Single CR ("\r") and LF ("\n") found # in the +msgstr+, are converted into the CR LF pair. You cannot send a # binary message with this method. +msgstr+ should include both # the message headers and body. # # +from_addr+ is a String representing the source mail address. # # +to_addr+ is a String or Strings or Array of Strings, representing # the destination mail address or addresses. # # === Example # # Net::SMTP.start('smtp.example.com') do |smtp| # smtp.send_message msgstr, # '[email protected]', # ['[email protected]', '[email protected]'] # end # # === Errors # # This method may raise: # # * Net::SMTPServerBusy # * Net::SMTPSyntaxError # * Net::SMTPFatalError # * Net::SMTPUnknownError # * Net::ReadTimeout # * IOError # def send_message(msgstr, from_addr, *to_addrs) raise IOError, 'closed session' unless @socket mailfrom from_addr rcptto_list(to_addrs) {data msgstr} end alias send_mail send_message alias sendmail send_message # obsolete # # Opens a message writer stream and gives it to the block. # The stream is valid only in the block, and has these methods: # # puts(str = ''):: outputs STR and CR LF. # print(str):: outputs STR. # printf(fmt, *args):: outputs sprintf(fmt,*args). # write(str):: outputs STR and returns the length of written bytes. # <<(str):: outputs STR and returns self. # # If a single CR ("\r") or LF ("\n") is found in the message, # it is converted to the CR LF pair. You cannot send a binary # message with this method. # # === Parameters # # +from_addr+ is a String representing the source mail address. # # +to_addr+ is a String or Strings or Array of Strings, representing # the destination mail address or addresses. # # === Example # # Net::SMTP.start('smtp.example.com', 25) do |smtp| # smtp.open_message_stream('[email protected]', ['[email protected]']) do |f| # f.puts 'From: [email protected]' # f.puts 'To: [email protected]' # f.puts 'Subject: test message' # f.puts # f.puts 'This is a test message.' # end # end # # === Errors # # This method may raise: # # * Net::SMTPServerBusy # * Net::SMTPSyntaxError # * Net::SMTPFatalError # * Net::SMTPUnknownError # * Net::ReadTimeout # * IOError # def open_message_stream(from_addr, *to_addrs, &block) # :yield: stream raise IOError, 'closed session' unless @socket mailfrom from_addr rcptto_list(to_addrs) {data(&block)} end alias ready open_message_stream # obsolete # # Authentication # public DEFAULT_AUTH_TYPE = :plain def authenticate(user, secret, authtype = DEFAULT_AUTH_TYPE) check_auth_method authtype check_auth_args user, secret public_send auth_method(authtype), user, secret end def auth_plain(user, secret) check_auth_args user, secret res = critical { get_response('AUTH PLAIN ' + base64_encode("\0#{user}\0#{secret}")) } check_auth_response res res end def auth_login(user, secret) check_auth_args user, secret res = critical { check_auth_continue get_response('AUTH LOGIN') check_auth_continue get_response(base64_encode(user)) get_response(base64_encode(secret)) } check_auth_response res res end def auth_cram_md5(user, secret) check_auth_args user, secret res = critical { res0 = get_response('AUTH CRAM-MD5') check_auth_continue res0 crammed = cram_md5_response(secret, res0.cram_md5_challenge) get_response(base64_encode("#{user} #{crammed}")) } check_auth_response res res end private def check_auth_method(type) unless respond_to?(auth_method(type), true) raise ArgumentError, "wrong authentication type #{type}" end end def auth_method(type) "auth_#{type.to_s.downcase}".intern end def check_auth_args(user, secret, authtype = DEFAULT_AUTH_TYPE) unless user raise ArgumentError, 'SMTP-AUTH requested but missing user name' end unless secret raise ArgumentError, 'SMTP-AUTH requested but missing secret phrase' end end def base64_encode(str) # expects "str" may not become too long [str].pack('m0') end IMASK = 0x36 OMASK = 0x5c # CRAM-MD5: [RFC2195] def cram_md5_response(secret, challenge) tmp = Digest::MD5.digest(cram_secret(secret, IMASK) + challenge) Digest::MD5.hexdigest(cram_secret(secret, OMASK) + tmp) end CRAM_BUFSIZE = 64 def cram_secret(secret, mask) secret = Digest::MD5.digest(secret) if secret.size > CRAM_BUFSIZE buf = secret.ljust(CRAM_BUFSIZE, "\0") 0.upto(buf.size - 1) do |i| buf[i] = (buf[i].ord ^ mask).chr end buf end # # SMTP command dispatcher # public # Aborts the current mail transaction def rset getok('RSET') end def starttls getok('STARTTLS') end def helo(domain) getok("HELO #{domain}") end def ehlo(domain) getok("EHLO #{domain}") end def mailfrom(from_addr) getok("MAIL FROM:<#{from_addr}>") end def rcptto_list(to_addrs) raise ArgumentError, 'mail destination not given' if to_addrs.empty? ok_users = [] unknown_users = [] to_addrs.flatten.each do |addr| begin rcptto addr rescue SMTPAuthenticationError unknown_users << addr.dump else ok_users << addr end end raise ArgumentError, 'mail destination not given' if ok_users.empty? ret = yield unless unknown_users.empty? raise SMTPAuthenticationError, "failed to deliver for #{unknown_users.join(', ')}" end ret end def rcptto(to_addr) getok("RCPT TO:<#{to_addr}>") end # This method sends a message. # If +msgstr+ is given, sends it as a message. # If block is given, yield a message writer stream. # You must write message before the block is closed. # # # Example 1 (by string) # smtp.data(<<EndMessage) # From: [email protected] # To: [email protected] # Subject: I found a bug # # Check vm.c:58879. # EndMessage # # # Example 2 (by block) # smtp.data {|f| # f.puts "From: [email protected]" # f.puts "To: [email protected]" # f.puts "Subject: I found a bug" # f.puts "" # f.puts "Check vm.c:58879." # } # def data(msgstr = nil, &block) #:yield: stream if msgstr and block raise ArgumentError, "message and block are exclusive" end unless msgstr or block raise ArgumentError, "message or block is required" end res = critical { check_continue get_response('DATA') socket_sync_bak = @socket.io.sync begin @socket.io.sync = false if msgstr @socket.write_message msgstr else @socket.write_message_by_block(&block) end ensure @socket.io.flush @socket.io.sync = socket_sync_bak end recv_response() } check_response res res end def quit getok('QUIT') end private def validate_line(line) # A bare CR or LF is not allowed in RFC5321. if /[\r\n]/ =~ line raise ArgumentError, "A line must not contain CR or LF" end end def getok(reqline) validate_line reqline res = critical { @socket.writeline reqline recv_response() } check_response res res end def get_response(reqline) validate_line reqline @socket.writeline reqline recv_response() end def recv_response buf = ''.dup while true line = @socket.readline buf << line << "\n" break unless line[3,1] == '-' # "210-PIPELINING" end Response.parse(buf) end def critical return Response.parse('200 dummy reply code') if @error_occurred begin return yield() rescue Exception @error_occurred = true raise end end def check_response(res) unless res.success? raise res.exception_class.new(res) end end def check_continue(res) unless res.continue? raise SMTPUnknownError.new(res, message: "could not get 3xx (#{res.status}: #{res.string})") end end def check_auth_response(res) unless res.success? raise SMTPAuthenticationError.new(res) end end def check_auth_continue(res) unless res.continue? raise res.exception_class.new(res) end end # This class represents a response received by the SMTP server. Instances # of this class are created by the SMTP class; they should not be directly # created by the user. For more information on SMTP responses, view # {Section 4.2 of RFC 5321}[http://tools.ietf.org/html/rfc5321#section-4.2] class Response # Parses the received response and separates the reply code and the human # readable reply text def self.parse(str) new(str[0,3], str) end # Creates a new instance of the Response class and sets the status and # string attributes def initialize(status, string) @status = status @string = string end # The three digit reply code of the SMTP response attr_reader :status # The human readable reply text of the SMTP response attr_reader :string # Takes the first digit of the reply code to determine the status type def status_type_char @status[0, 1] end # Determines whether the response received was a Positive Completion # reply (2xx reply code) def success? status_type_char() == '2' end # Determines whether the response received was a Positive Intermediate # reply (3xx reply code) def continue? status_type_char() == '3' end # The first line of the human readable reply text def message @string.lines.first end # Creates a CRAM-MD5 challenge. You can view more information on CRAM-MD5 # on Wikipedia: https://en.wikipedia.org/wiki/CRAM-MD5 def cram_md5_challenge @string.split(/ /)[1].unpack1('m') end # Returns a hash of the human readable reply text in the response if it # is multiple lines. It does not return the first line. The key of the # hash is the first word the value of the hash is an array with each word # thereafter being a value in the array def capabilities return {} unless @string[3, 1] == '-' h = {} @string.lines.drop(1).each do |line| k, *v = line[4..-1].split(' ') h[k] = v end h end # Determines whether there was an error and raises the appropriate error # based on the reply code of the response def exception_class case @status when /\A4/ then SMTPServerBusy when /\A50/ then SMTPSyntaxError when /\A53/ then SMTPAuthenticationError when /\A5/ then SMTPFatalError else SMTPUnknownError end end end def logging(msg) @debug_output << msg + "\n" if @debug_output end end # class SMTP SMTPSession = SMTP # :nodoc: end
30.210387
190
0.631487
e9c24bf97261c7b49977c900fb073758b4ea840a
138
require 'rails_helper' RSpec.describe AdminSignupNotifierJob, type: :job do pending "add some examples to (or delete) #{__FILE__}" end
23
56
0.768116
1c077cf2e63eed077d01e9b201bf0e7f1bd3a668
963
# frozen_string_literal: true module ZohoHub # Adds the ability to do API requests (GET / PUT and POST requests) when included in a class. module WithConnection def self.included(base) base.extend ClassMethods end module ClassMethods def get(path, params = {}) ZohoHub.connection.get(path, params) end def post(path, params = {}) ZohoHub.connection.post(path, params.to_json) end def put(path, params = {}) ZohoHub.connection.put(path, params.to_json) end def delete(path, params = {}) ZohoHub.connection.delete(path, params) end end def get(path, params = {}) self.class.get(path, params) end def post(path, params = {}) self.class.post(path, params) end def put(path, params = {}) self.class.put(path, params) end def delete(path, params = {}) self.class.delete(path, params) end end end
21.4
95
0.61163
26cc4b6586aea0ee8a94079eceb41e70f2ad4bb7
10,062
=begin Wallee API: 1.0.0 The wallee API allows an easy interaction with the wallee web service. 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. =end require "uri" module Wallee class PaymentConnectorConfigurationService attr_accessor :api_client def initialize(api_client = ApiClient.default) @api_client = api_client end # Count # Counts the number of items in the database as restricted by the given filter. # @param space_id # @param [Hash] opts the optional parameters # @option opts [EntityQueryFilter] :filter The filter which restricts the entities which are used to calculate the count. # @return [Integer] def payment_connector_configuration_service_count(space_id, opts = {}) data, _status_code, _headers = payment_connector_configuration_service_count_with_http_info(space_id, opts) return data end # Count # Counts the number of items in the database as restricted by the given filter. # @param space_id # @param [Hash] opts the optional parameters # @option opts [EntityQueryFilter] :filter The filter which restricts the entities which are used to calculate the count. # @return [Array<(Integer, Fixnum, Hash)>] Integer data, response status code and response headers def payment_connector_configuration_service_count_with_http_info(space_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: PaymentConnectorConfigurationService.payment_connector_configuration_service_count ..." end # verify the required parameter 'space_id' is set fail ArgumentError, "Missing the required parameter 'space_id' when calling PaymentConnectorConfigurationService.payment_connector_configuration_service_count" if space_id.nil? # resource path local_var_path = "/payment-connector-configuration/count".sub('{format}','json') # query parameters query_params = {} query_params[:'spaceId'] = space_id # header parameters header_params = {} # HTTP header 'Accept' (if needed) local_header_accept = ['application/json;charset=utf-8'] local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' local_header_content_type = ['application/json;charset=utf-8'] header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(opts[:'filter']) auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'Integer') if @api_client.config.debugging @api_client.config.logger.debug "API called: PaymentConnectorConfigurationService#payment_connector_configuration_service_count\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Read # Reads the entity with the given 'id' and returns it. # @param space_id # @param id The id of the payment connector configuration which should be returned. # @param [Hash] opts the optional parameters # @return [PaymentConnectorConfiguration] def payment_connector_configuration_service_read(space_id, id, opts = {}) data, _status_code, _headers = payment_connector_configuration_service_read_with_http_info(space_id, id, opts) return data end # Read # Reads the entity with the given &#39;id&#39; and returns it. # @param space_id # @param id The id of the payment connector configuration which should be returned. # @param [Hash] opts the optional parameters # @return [Array<(PaymentConnectorConfiguration, Fixnum, Hash)>] PaymentConnectorConfiguration data, response status code and response headers def payment_connector_configuration_service_read_with_http_info(space_id, id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: PaymentConnectorConfigurationService.payment_connector_configuration_service_read ..." end # verify the required parameter 'space_id' is set fail ArgumentError, "Missing the required parameter 'space_id' when calling PaymentConnectorConfigurationService.payment_connector_configuration_service_read" if space_id.nil? # verify the required parameter 'id' is set fail ArgumentError, "Missing the required parameter 'id' when calling PaymentConnectorConfigurationService.payment_connector_configuration_service_read" if id.nil? # resource path local_var_path = "/payment-connector-configuration/read".sub('{format}','json') # query parameters query_params = {} query_params[:'spaceId'] = space_id query_params[:'id'] = id # header parameters header_params = {} # HTTP header 'Accept' (if needed) local_header_accept = ['*/*'] local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' local_header_content_type = ['application/json;charset=utf-8'] header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil auth_names = [] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'PaymentConnectorConfiguration') if @api_client.config.debugging @api_client.config.logger.debug "API called: PaymentConnectorConfigurationService#payment_connector_configuration_service_read\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Search # Searches for the entities as specified by the given query. # @param space_id # @param query The query restricts the payment connector configuration which are returned by the search. # @param [Hash] opts the optional parameters # @return [Array<PaymentConnectorConfiguration>] def payment_connector_configuration_service_search(space_id, query, opts = {}) data, _status_code, _headers = payment_connector_configuration_service_search_with_http_info(space_id, query, opts) return data end # Search # Searches for the entities as specified by the given query. # @param space_id # @param query The query restricts the payment connector configuration which are returned by the search. # @param [Hash] opts the optional parameters # @return [Array<(Array<PaymentConnectorConfiguration>, Fixnum, Hash)>] Array<PaymentConnectorConfiguration> data, response status code and response headers def payment_connector_configuration_service_search_with_http_info(space_id, query, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: PaymentConnectorConfigurationService.payment_connector_configuration_service_search ..." end # verify the required parameter 'space_id' is set fail ArgumentError, "Missing the required parameter 'space_id' when calling PaymentConnectorConfigurationService.payment_connector_configuration_service_search" if space_id.nil? # verify the required parameter 'query' is set fail ArgumentError, "Missing the required parameter 'query' when calling PaymentConnectorConfigurationService.payment_connector_configuration_service_search" if query.nil? # resource path local_var_path = "/payment-connector-configuration/search".sub('{format}','json') # query parameters query_params = {} query_params[:'spaceId'] = space_id # header parameters header_params = {} # HTTP header 'Accept' (if needed) local_header_accept = ['application/json;charset=utf-8'] local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' local_header_content_type = ['application/json;charset=utf-8'] header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(query) auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'Array<PaymentConnectorConfiguration>') if @api_client.config.debugging @api_client.config.logger.debug "API called: PaymentConnectorConfigurationService#payment_connector_configuration_service_search\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end end end
46.155963
210
0.731962
627680e28d77dd29d4a63573e772d20a5a941fce
20,888
require 'puppet/face' require 'puppet/pops' require 'puppet/parser/files' require 'puppet/file_system' Puppet::Face.define(:epp, '0.0.1') do copyright "Puppet Inc.", 2014 license _("Apache 2 license; see COPYING") summary _("Interact directly with the EPP template parser/renderer.") action(:validate) do summary _("Validate the syntax of one or more EPP templates.") arguments _("[<template>] [<template> ...]") returns _("Nothing, or encountered syntax errors.") description <<-'EOT' This action validates EPP syntax without producing any output. When validating, multiple issues per file are reported up to the settings of max_error, and max_warnings. The processing stops after having reported issues for the first encountered file with errors unless the option --continue_on_error is given. Files can be given using the `modulename/template.epp` style to lookup the template from a module, or be given as a reference to a file. If the reference to a file can be resolved against a template in a module, the module version wins - in this case use an absolute path to reference the template file if the module version is not wanted. Exits with 0 if there were no validation errors. EOT option("--[no-]continue_on_error") do summary _("Whether or not to continue after errors are reported for a template.") end examples <<-'EOT' Validate the template 'template.epp' in module 'mymodule': $ puppet epp validate mymodule/template.epp Validate two arbitrary template files: $ puppet epp validate mymodule/template1.epp yourmodule/something.epp Validate a template somewhere in the file system: $ puppet epp validate /tmp/testing/template1.epp Validate a template against a file relative to the current directory: $ puppet epp validate template1.epp $ puppet epp validate ./template1.epp Validate from STDIN: $ cat template.epp | puppet epp validate Continue on error to see errors for all templates: $ puppet epp validate mymodule/template1.epp mymodule/template2.epp --continue_on_error EOT when_invoked do |*args| options = args.pop # pass a dummy node, as facts are not needed for validation options[:node] = node = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {})) compiler = create_compiler(options) status = true # no validation error yet files = args if files.empty? if not STDIN.tty? tmp = validate_template_string(STDIN.read) status &&= tmp else # This is not an error since a validate of all files in an empty # directory should not be treated as a failed validation. Puppet.notice _("No template specified. No action taken") end end missing_files = [] files.each do |file| break if !status && !options[:continue_on_error] template_file = effective_template(file, compiler.environment) if template_file tmp = validate_template(template_file) status &&= tmp else missing_files << file end end if !missing_files.empty? raise Puppet::Error, _("One or more file(s) specified did not exist:\n") + missing_files.map { |f| " #{f}" }.join("\n") else # Exit with 1 if there were errors raise Puppet::Error, _("Errors while validating epp") unless status end end end action (:dump) do summary _("Outputs a dump of the internal template parse tree for debugging") arguments "-e <source> | [<templates> ...] " returns _("A dump of the resulting AST model unless there are syntax or validation errors.") description <<-'EOT' The dump action parses and validates the EPP syntax and dumps the resulting AST model in a human readable (but not necessarily an easy to understand) format. The output format of the dumped tree is intended for epp parser debugging purposes and is not API, and may thus change between versions without deprecation warnings. The command accepts one or more templates (.epp) files, or an -e followed by the template source text. The given templates can be paths to template files, or references to templates in modules when given on the form <modulename>/<template-name>.epp. If no arguments are given, the stdin is read (unless it is attached to a terminal) If multiple templates are given, they are separated with a header indicating the name of the template. This can be suppressed with the option --no-header. The option --[no-]header has no effect when a single template is dumped. When debugging the epp parser itself, it may be useful to suppress the validation step with the `--no-validate` option to observe what the parser produced from the given source. This command ignores the --render-as setting/option. EOT option("--e " + _("<source>")) do default_to { nil } summary _("Dump one epp source expression given on the command line.") end option("--[no-]validate") do summary _("Whether or not to validate the parsed result, if no-validate only syntax errors are reported.") end option("--[no-]header") do summary _("Whether or not to show a file name header between files.") end when_invoked do |*args| require 'puppet/pops' options = args.pop # pass a dummy node, as facts are not needed for dump options[:node] = node = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {})) options[:header] = options[:header].nil? ? true : options[:header] options[:validate] = options[:validate].nil? ? true : options[:validate] compiler = create_compiler(options) # Print to a buffer since the face needs to return the resulting string # and the face API is "all or nothing" # buffer = StringIO.new if options[:e] buffer.print dump_parse(options[:e], 'command-line-string', options, false) elsif args.empty? if ! STDIN.tty? buffer.print dump_parse(STDIN.read, 'stdin', options, false) else raise Puppet::Error, _("No input to parse given on command line or stdin") end else templates, missing_files = args.reduce([[],[]]) do |memo, file| template_file = effective_template(file, compiler.environment) if template_file.nil? memo[1] << file else memo[0] << template_file end memo end show_filename = templates.count > 1 dumps = templates.each do |file| buffer.print dump_parse(Puppet::FileSystem.read(file, :encoding => 'utf-8'), file, options, show_filename) end if !missing_files.empty? raise Puppet::Error, _("One or more file(s) specified did not exist:\n") + missing_files.collect { |f| " #{f}" }.join("\n") end end buffer.string end end action (:render) do summary _("Renders an epp template as text") arguments "-e <source> | [<templates> ...] " returns _("A rendered result of one or more given templates.") description <<-'EOT' This action renders one or more EPP templates. The command accepts one or more templates (.epp files), given the same way as templates are given to the puppet `epp` function (a full path, or a relative reference on the form '<modulename>/<template-name>.epp'), or as a relative path.args In case the given path matches both a modulename/template and a file, the template from the module is used. An inline_epp equivalent can also be performed by giving the template after an -e, or by piping the EPP source text to the command. Values to the template can be defined using the Puppet Language on the command line with `--values` or in a .pp or .yaml file referenced with `--values_file`. If specifying both the result is merged with --values having higher precedence. The --values option allows a Puppet Language sequence of expressions to be defined on the command line the same way as it may be given in a .pp file referenced with `--values_file`. It may set variable values (that become available in the template), and must produce either `undef` or a `Hash` of values (the hash may be empty). Producing `undef` simulates that the template is called without an arguments hash and thus only references variables in its outer scope. When a hash is given, a template is limited to seeing only the global scope. It is thus possible to simulate the different types of calls to the `epp` and `inline_epp` functions, with or without a given hash. Note that if variables are given, they are always available in this simulation - to test that the template only references variables given as arguments, produce a hash in --values or the --values_file, do not specify any variables that are not global, and turn on --strict_variables setting. If multiple templates are given, the same set of values are given to each template. If both --values and --value_file are used, the --values are merged on top of those given in the file. When multiple templates are rendered, a separating header is output between the templates showing the name of the template before the output. The header output can be turned off with `--no-header`. This also concatenates the template results without any added newline separators. Facts from the node where the command is being run are used by default.args Facts can be obtained for other nodes if they have called in, and reported their facts by using the `--node <nodename>` flag. Overriding node facts as well as additional facts can be given in a .yaml or .json file and referencing it with the --facts option. (Values can be obtained in yaml format directly from `facter`, or from puppet for a given node). Note that it is not possible to simulate the reserved variable name `$facts` in any other way. Note that it is not possible to set variables using the Puppet Language that have the same names as facts as this result in an error; "attempt to redefine a variable" since facts are set first. Exits with 0 if there were no validation errors. On errors, no rendered output is produced for that template file. When designing EPP templates, it is strongly recommended to define all template arguments in the template, and to give them in a hash when calling `epp` or `inline_epp` and to use as few global variables as possible, preferably only the $facts hash. This makes templates more free standing and are easier to reuse, and to test. EOT examples <<-'EOT' Render the template in module 'mymodule' called 'mytemplate.epp', and give it two arguments `a` and `b`: $ puppet epp render mymodule/mytemplate.epp --values '{a => 10, b => 20}' Render a template using an absolute path: $ puppet epp render /tmp/testing/mytemplate.epp --values '{a => 10, b => 20}' Render a template with data from a .pp file: $ puppet epp render /tmp/testing/mytemplate.epp --values_file mydata.pp Render a template with data from a .pp file and override one value on the command line: $ puppet epp render /tmp/testing/mytemplate.epp --values_file mydata.pp --values '{a=>10}' Render from STDIN: $ cat template.epp | puppet epp render --values '{a => 10, b => 20}' Set variables in a .pp file and render a template that uses variable references: # data.pp file $greeted = 'a global var' undef $ puppet epp render -e 'hello <%= $greeted %>' --values_file data.pp Render a template that outputs a fact: $ facter --yaml > data.yaml $ puppet epp render -e '<% $facts[osfamily] %>' --facts data.yaml EOT option("--node " + _("<node_name>")) do summary _("The name of the node for which facts are obtained. Defaults to facts for the local node.") end option("--e " + _("<source>")) do default_to { nil } summary _("Render one inline epp template given on the command line.") end option("--values " + _("<values_hash>")) do summary _("A Hash in Puppet DSL form given as arguments to the template being rendered.") end option("--values_file " + _("<pp_or_yaml_file>")) do summary _("A .pp or .yaml file that is processed to produce a hash of values for the template.") end option("--facts " + _("<facts_file>")) do summary _("A .yaml or .json file containing a hash of facts made available in $facts and $trusted") end option("--[no-]header") do summary _("Whether or not to show a file name header between rendered results.") end when_invoked do |*args| options = args.pop options[:header] = options[:header].nil? ? true : options[:header] compiler = create_compiler(options) compiler.with_context_overrides('For rendering epp') do # Print to a buffer since the face needs to return the resulting string # and the face API is "all or nothing" # buffer = StringIO.new status = true if options[:e] buffer.print render_inline(options[:e], compiler, options) elsif args.empty? if ! STDIN.tty? buffer.print render_inline(STDIN.read, compiler, options) else raise Puppet::Error, _("No input to process given on command line or stdin") end else show_filename = args.count > 1 file_nbr = 0 args.each do |file| begin buffer.print render_file(file, compiler, options, show_filename, file_nbr += 1) rescue Puppet::ParseError => detail Puppet.err(detail.message) status = false end end end raise Puppet::Error, _("error while rendering epp") unless status buffer.string end end end def dump_parse(source, filename, options, show_filename = true) output = "" dumper = Puppet::Pops::Model::ModelTreeDumper.new evaluating_parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new begin if options[:validate] parse_result = evaluating_parser.parse_string(source, filename) else # side step the assert_and_report step parse_result = evaluating_parser.parser.parse_string(source) end if show_filename && options[:header] output << "--- #{filename}\n" end output << dumper.dump(parse_result) << "\n" rescue Puppet::ParseError => detail if show_filename Puppet.err("--- #{filename}") end Puppet.err(detail.message) "" end end def get_values(compiler, options) template_values = nil if values_file = options[:values_file] begin if values_file =~ /\.yaml$/ template_values = YAML.load_file(values_file) elsif values_file =~ /\.pp$/ evaluating_parser = Puppet::Pops::Parser::EvaluatingParser.new template_values = evaluating_parser.evaluate_file(compiler.topscope, values_file) else Puppet.err(_("Only .yaml or .pp can be used as a --values_file")) end rescue => e Puppet.err(_("Could not load --values_file %{error}") % { error: e.message }) end if !(template_values.nil? || template_values.is_a?(Hash)) Puppet.err(_("--values_file option must evaluate to a Hash or undef/nil, got: '%{template_class}'") % { template_class: template_values.class }) end end if values = options[:values] evaluating_parser = Puppet::Pops::Parser::EvaluatingParser.new result = evaluating_parser.evaluate_string(compiler.topscope, values, 'values-hash') case result when nil template_values when Hash template_values.nil? ? result : template_values.merge(result) else Puppet.err(_("--values option must evaluate to a Hash or undef, got: '%{values_class}'") % { values_class: result.class }) end else template_values end end def render_inline(epp_source, compiler, options) template_args = get_values(compiler, options) Puppet::Pops::Evaluator::EppEvaluator.inline_epp(compiler.topscope, epp_source, template_args) end def render_file(epp_template_name, compiler, options, show_filename, file_nbr) template_args = get_values(compiler, options) output = "" begin if show_filename && options[:header] output << "\n" unless file_nbr == 1 output << "--- #{epp_template_name}\n" end # Change to an absolute file only if reference is to a an existing file. Note that an absolute file must be used # or the template must be found on the module path when calling the epp evaluator. template_file = Puppet::Parser::Files.find_template(epp_template_name, compiler.environment) if template_file.nil? && Puppet::FileSystem.exist?(epp_template_name) epp_template_name = File.expand_path(epp_template_name) end output << Puppet::Pops::Evaluator::EppEvaluator.epp(compiler.topscope, epp_template_name, compiler.environment, template_args) rescue Puppet::ParseError => detail Puppet.err("--- #{epp_template_name}") if show_filename raise detail end output end # @api private def validate_template(template) parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new() parser.parse_file(template) true rescue => detail Puppet.log_exception(detail) false end # @api private def validate_template_string(source) parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new() parser.parse_string(source, '<stdin>') true rescue => detail Puppet.log_exception(detail) false end # @api private def create_compiler(options) if options[:node] node = options[:node] else node = Puppet[:node_name_value] # If we want to lookup the node we are currently on # we must returning these settings to their default values Puppet.settings[:facts_terminus] = 'facter' Puppet.settings[:node_cache_terminus] = nil end unless node.is_a?(Puppet::Node) node = Puppet::Node.indirection.find(node) # Found node must be given the environment to use in some cases, use the one configured # or given on the command line node.environment = Puppet[:environment] end fact_file = options[:facts] if fact_file if fact_file.is_a?(Hash) # when used via the Face API given_facts = fact_file elsif fact_file.end_with?("json") given_facts = JSON.parse(Puppet::FileSystem.read(fact_file, :encoding => 'utf-8')) else given_facts = YAML.load(Puppet::FileSystem.read(fact_file, :encoding => 'utf-8')) end unless given_facts.instance_of?(Hash) raise _("Incorrect formatted data in %{fact_file} given via the --facts flag") % { fact_file: fact_file } end # It is difficult to add to or modify the set of facts once the node is created # as changes does not show up in parameters. Rather than manually patching up # a node and risking future regressions, a new node is created from scratch node = Puppet::Node.new(node.name, :facts => Puppet::Node::Facts.new("facts", node.facts.values.merge(given_facts))) node.environment = Puppet[:environment] node.merge(node.facts.values) end compiler = Puppet::Parser::Compiler.new(node) # configure compiler with facts and node related data # Set all global variables from facts compiler.send(:set_node_parameters) # pretend that the main class (named '') has been evaluated # since it is otherwise not possible to resolve top scope variables # using '::' when rendering. (There is no harm doing this for the other actions) # compiler.topscope.class_set('', compiler.topscope) compiler end # Produces the effective template file from a module/template or file reference # @api private def effective_template(file, env) template_file = Puppet::Parser::Files.find_template(file, env) if !template_file.nil? template_file elsif Puppet::FileSystem.exist?(file) file else nil end end end
39.560606
152
0.665933
5dce82adfd0f8c4739c5433949ac2345b9fff06b
28,282
# frozen_string_literal: true Prawn::Font::AFM.instance_variable_set :@hide_m17n_warning, true require 'prawn/icon' Prawn::Icon::Compatibility.send :prepend, (::Module.new { def warning *args; end }) module Asciidoctor module Prawn module Extensions include ::Asciidoctor::PDF::Measurements include ::Asciidoctor::PDF::Sanitizer FontAwesomeIconSets = %w(fab far fas) IconSets = %w(fab far fas fi pf).to_set InitialPageContent = %(q\n) # - :height is the height of a line # - :leading is spacing between adjacent lines # - :padding_top is half line spacing, plus any line_gap in the font # - :padding_bottom is half line spacing # - :final_gap determines whether a gap is added below the last line LineMetrics = ::Struct.new :height, :leading, :padding_top, :padding_bottom, :final_gap # Core # Retrieves the catalog reference data for the PDF. # def catalog state.store.root end # Measurements # Returns the width of the current page from edge-to-edge # def page_width page.dimensions[2] end # Returns the effective (writable) width of the page # # If inside a bounding box, returns width of box. # def effective_page_width reference_bounds.width end # Returns the height of the current page from edge-to-edge # def page_height page.dimensions[3] end # Returns the effective (writable) height of the page # # If inside a fixed-height bounding box, returns width of box. # def effective_page_height reference_bounds.height end # Set the margins for the current page. # def set_page_margin margin # FIXME is there a cleaner way to set margins? does it make sense to override create_new_page? apply_margin_options margin: margin generate_margin_box end # Returns the margins for the current page as a 4 element array (top, right, bottom, left) # def page_margin [page.margins[:top], page.margins[:right], page.margins[:bottom], page.margins[:left]] end # Returns the width of the left margin for the current page # def page_margin_left page.margins[:left] end # deprecated alias left_margin page_margin_left # Returns the width of the right margin for the current page # def page_margin_right page.margins[:right] end # deprecated alias right_margin page_margin_right # Returns the width of the top margin for the current page # def page_margin_top page.margins[:top] end # Returns the width of the bottom margin for the current page # def page_margin_bottom page.margins[:bottom] end # Returns the total left margin (to the page edge) for the current bounds. # def bounds_margin_left bounds.absolute_left end # Returns the total right margin (to the page edge) for the current bounds. # def bounds_margin_right page.dimensions[2] - bounds.absolute_right end # Returns the side the current page is facing, :recto or :verso. # def page_side pgnum = nil, invert = nil if invert (recto_page? pgnum) ? :verso : :recto else (recto_page? pgnum) ? :recto : :verso end end # Returns whether the page is a recto page. # def recto_page? pgnum = nil (pgnum || page_number).odd? end # Returns whether the page is a verso page. # def verso_page? pgnum = nil (pgnum || page_number).even? end # Returns whether the cursor is at the top of the page (i.e., margin box). # def at_page_top? @y == @margin_box.absolute_top end # Returns whether the current page is the last page in the document. # def last_page? page_number == page_count end # Destinations # Generates a destination object that resolves to the top of the page # specified by the page_num parameter or the current page if no page number # is provided. The destination preserves the user's zoom level unlike # the destinations generated by the outline builder. # def dest_top page_num = nil dest_xyz 0, page_height, nil, (page_num ? state.pages[page_num - 1] : page) end # Fonts # Registers a new custom font described in the data parameter # after converting the font name to a String. # # Example: # # register_font Roboto: { # normal: 'fonts/roboto-normal.ttf', # italic: 'fonts/roboto-italic.ttf', # bold: 'fonts/roboto-bold.ttf', # bold_italic: 'fonts/roboto-bold_italic.ttf' # } # def register_font data font_families.update data.reduce({}) {|accum, (key, val)| accum[key.to_s] = val; accum } end # Enhances the built-in font method to allow the font # size to be specified as the second option and to # lazily load font-based icons. # def font name = nil, options = {} if name options = { size: options } if ::Numeric === options if IconSets.include? name ::Prawn::Icon::FontData.load self, name options = options.reject {|k| k == :style } if options.key? :style end end super name, options end # Retrieves the current font name (i.e., family). # def font_family font.options[:family] end alias font_name font_family # Retrieves the current font info (family, style, size) as a Hash # def font_info { family: font.options[:family], style: (font.options[:style] || :normal), size: @font_size } end # Sets the font style for the scope of the block to which this method # yields. If the style is nil and no block is given, return the current # font style. # def font_style style = nil if block_given? font font.options[:family], style: style do yield end elsif style font font.options[:family], style: style else font.options[:style] || :normal end end # Applies points as a scale factor of the current font if the value provided # is less than or equal to 1 or it's a string (e.g., 1.1em), then delegates to the super # implementation to carry out the built-in functionality. # #-- # QUESTION should we round the result? def font_size points = nil return @font_size unless points if points == 1 super @font_size elsif String === points if points.end_with? 'rem' super(@root_font_size * points.to_f) elsif points.end_with? 'em' super(@font_size * points.to_f) elsif points.end_with? '%' super(@font_size * (points.to_f / 100.0)) else super points.to_f end # FIXME HACK assume em value elsif points < 1 super(@font_size * points) else super points end end def resolve_font_style styles if styles.include? :bold (styles.include? :italic) ? :bold_italic : :bold elsif styles.include? :italic :italic else :normal end end # Retreives the collection of font styles from the given font style key, # which defaults to the current font style. # def font_styles style = font_style if style style == :bold_italic ? [:bold, :italic].to_set : [style].to_set else ::Set.new end end # Apply the font settings (family, size, styles and character spacing) from # the fragment to the document, then yield to the block. # # The original font settings are restored before this method returns. # def fragment_font fragment f_info = font_info f_family = fragment[:font] || f_info[:family] f_size = fragment[:size] || f_info[:size] if (f_styles = fragment[:styles]) f_style = resolve_font_style f_styles else f_style = :normal end if (c_spacing = fragment[:character_spacing]) character_spacing c_spacing do font f_family, size: f_size, style: f_style do yield end end else font f_family, size: f_size, style: f_style do yield end end end def icon_font_data family ::Prawn::Icon::FontData.load self, family end def resolve_legacy_icon_name name ::Prawn::Icon::Compatibility::SHIMS[%(fa-#{name})] end def calc_line_metrics line_height = 1, font = self.font, font_size = self.font_size line_height_length = line_height * font_size leading = line_height_length - font_size half_leading = leading / 2 padding_top = half_leading + font.line_gap padding_bottom = half_leading LineMetrics.new line_height_length, leading, padding_top, padding_bottom, false end =begin # these line metrics attempted to figure out a correction based on the reported height and the font_size # however, it only works for some fonts, and breaks down for fonts like Noto Serif def calc_line_metrics line_height = 1, font = self.font, font_size = self.font_size line_height_length = font_size * line_height line_gap = line_height_length - font_size correction = font.height - font_size leading = line_gap - correction shift = (font.line_gap + correction + line_gap) / 2 final_gap = font.line_gap != 0 LineMetrics.new line_height_length, leading, shift, shift, final_gap end =end # Parse the text into an array of fragments using the text formatter. def parse_text string, options = {} return [] if string.nil? options = options.dup if (format_option = options.delete :inline_format) format_option = [] unless ::Array === format_option fragments = self.text_formatter.format string, *format_option else fragments = [{text: string}] end if (color = options.delete :color) fragments.map do |fragment| fragment[:color] ? fragment : fragment.merge(color: color) end else fragments end end # NOTE override built-in draw_indented_formatted_line to insert leading before second line def draw_indented_formatted_line string, opts result = super unless @no_text_printed || @all_text_printed # as of Prawn 1.2.1, we have to handle the line gap after the first line manually move_down opts[:leading] end result end # Performs the same work as Prawn::Text.text except that the first_line_opts are applied to the first line of text # renderered. It's necessary to use low-level APIs in this method so we only style the first line and not the # remaining lines (which is the default behavior in Prawn). def text_with_formatted_first_line string, first_line_opts, opts color = opts.delete :color fragments = parse_text string, opts # NOTE the low-level APIs we're using don't recognize the :styles option, so we must resolve if (styles = opts.delete :styles) opts[:style] = resolve_font_style styles end if (first_line_styles = first_line_opts.delete :styles) first_line_opts[:style] = resolve_font_style first_line_styles end first_line_color = (first_line_opts.delete :color) || color opts = opts.merge document: self # QUESTION should we merge more carefully here? (hand-select keys?) first_line_opts = opts.merge(first_line_opts).merge single_line: true box = ::Prawn::Text::Formatted::Box.new fragments, first_line_opts # NOTE get remaining_fragments before we add color to fragments on first line if (text_indent = opts.delete :indent_paragraphs) remaining_fragments = indent text_indent do box.render dry_run: true end else remaining_fragments = box.render dry_run: true end # NOTE color must be applied per-fragment if first_line_color fragments.each {|fragment| fragment[:color] ||= first_line_color} end if text_indent indent text_indent do fill_formatted_text_box fragments, first_line_opts end else fill_formatted_text_box fragments, first_line_opts end unless remaining_fragments.empty? # NOTE color must be applied per-fragment remaining_fragments.each {|fragment| fragment[:color] ||= color } if color # as of Prawn 1.2.1, we have to handle the line gap after the first line manually move_down opts[:leading] remaining_fragments = fill_formatted_text_box remaining_fragments, opts draw_remaining_formatted_text_on_new_pages remaining_fragments, opts end end # Apply the text transform to the specified text. # # Supported transform values are "uppercase", "lowercase", or "none" (passed # as either a String or a Symbol). When the uppercase transform is applied to # the text, it correctly uppercases visible text while leaving markup and # named character entities unchanged. The none transform returns the text # unmodified. # def transform_text text, transform case transform when :uppercase, 'uppercase' uppercase_pcdata text when :lowercase, 'lowercase' lowercase_mb text else text end end # Cursor # Short-circuits the call to the built-in move_up operation # when n is 0. # def move_up n super unless n == 0 end # Override built-in move_text_position method to prevent Prawn from advancing # to next page if image doesn't fit before rendering image. #-- # NOTE could use :at option when calling image/embed_image instead def move_text_position h end # Short-circuits the call to the built-in move_down operation # when n is 0. # def move_down n super unless n == 0 end # Bounds # Overrides the built-in pad operation to allow for asymmetric paddings. # # Example: # # pad 20, 10 do # text 'A paragraph with twice as much top padding as bottom padding.' # end # def pad top, bottom = nil move_down top yield move_down(bottom || top) end # Combines the built-in pad and indent operations into a single method. # # Padding may be specified as an array of four values, or as a single value. # The single value is used as the padding around all four sides of the box. # # If padding is nil, this method simply yields to the block and returns. # # Example: # # pad_box 20 do # text 'A paragraph inside a blox with even padding on all sides.' # end # # pad_box [10, 10, 10, 20] do # text 'An indented paragraph inside a box with equal padding on all sides.' # end # def pad_box padding if padding # TODO implement shorthand combinations like in CSS p_top, p_right, p_bottom, p_left = ::Array === padding ? padding : (::Array.new 4, padding) begin # logic is intentionally inlined move_down p_top bounds.add_left_padding p_left bounds.add_right_padding p_right yield # NOTE support negative bottom padding for use with quote block if p_bottom < 0 # QUESTION should we return to previous page if top of page is reached? p_bottom < cursor - reference_bounds.top ? (move_cursor_to reference_bounds.top) : (move_down p_bottom) else p_bottom < cursor ? (move_down p_bottom) : reference_bounds.move_past_bottom end ensure bounds.subtract_left_padding p_left bounds.subtract_right_padding p_right end else yield end # alternate, delegated logic #pad padding[0], padding[2] do # indent padding[1], padding[3] do # yield # end #end end # TODO memoize the result def inflate_padding padding padding = [*(padding || 0)].slice 0, 4 case padding.size when 1 [padding[0], padding[0], padding[0], padding[0]] when 2 [padding[0], padding[1], padding[0], padding[1]] when 3 [padding[0], padding[1], padding[2], padding[1]] else padding end end # Stretch the current bounds to the left and right edges of the current page # while yielding the specified block if the verdict argument is true. # Otherwise, simply yield the specified block. # def span_page_width_if verdict if verdict indent(-bounds_margin_left, -bounds_margin_right) do yield end else yield end end # A flowing version of the bounding_box. If the content runs to another page, the cursor starts # at the top of the page instead of the original cursor position. Similar to span, except # you can specify an absolute left position and pass additional options through to bounding_box. # def flow_bounding_box left = 0, opts = {} original_y = self.y # QUESTION should preserving original_x be an option? original_x = bounds.absolute_left - margin_box.absolute_left canvas do bounding_box [margin_box.absolute_left + original_x + left, margin_box.absolute_top], opts do self.y = original_y yield end end end # Graphics # Fills the current bounding box with the specified fill color. Before # returning from this method, the original fill color on the document is # restored. def fill_bounds f_color = fill_color if f_color && f_color != 'transparent' prev_fill_color = fill_color fill_color f_color fill_rectangle bounds.top_left, bounds.width, bounds.height fill_color prev_fill_color end end # Fills the absolute bounding box with the specified fill color. Before # returning from this method, the original fill color on the document is # restored. def fill_absolute_bounds f_color = fill_color canvas { fill_bounds f_color } end # Fills the current bounds using the specified fill color and strokes the # bounds using the specified stroke color. Sets the line with if specified # in the options. Before returning from this method, the original fill # color, stroke color and line width on the document are restored. # def fill_and_stroke_bounds f_color = fill_color, s_color = stroke_color, options = {} no_fill = !f_color || f_color == 'transparent' no_stroke = !s_color || s_color == 'transparent' || options[:line_width] == 0 return if no_fill && no_stroke save_graphics_state do radius = options[:radius] || 0 # fill unless no_fill fill_color f_color fill_rounded_rectangle bounds.top_left, bounds.width, bounds.height, radius end # stroke unless no_stroke stroke_color s_color line_width(options[:line_width] || 0.5) # FIXME think about best way to indicate dashed borders #if options.has_key? :dash_width # dash options[:dash_width], space: options[:dash_space] || 1 #end stroke_rounded_rectangle bounds.top_left, bounds.width, bounds.height, radius #undash if options.has_key? :dash_width end end end # Fills and, optionally, strokes the current bounds using the fill and # stroke color specified, then yields to the block. The only_if option can # be used to conditionally disable this behavior. # def shade_box color, line_color = nil, options = {} if (!options.has_key? :only_if) || options[:only_if] # FIXME could use save_graphics_state here previous_fill_color = current_fill_color fill_color color fill_rectangle [bounds.left, bounds.top], bounds.right, bounds.top - bounds.bottom fill_color previous_fill_color if line_color line_width 0.5 previous_stroke_color = current_stroke_color stroke_color line_color stroke_bounds stroke_color previous_stroke_color end end yield end # A compliment to the stroke_horizontal_rule method, strokes a # vertical line using the current bounds. The width of the line # can be specified using the line_width option. The horizontal (x) # position can be specified using the at option. # def stroke_vertical_rule rule_color = stroke_color, options = {} rule_x = options[:at] || 0 rule_y_from = bounds.top rule_y_to = bounds.bottom rule_style = options[:line_style] rule_width = options[:line_width] || 0.5 save_graphics_state do line_width rule_width stroke_color rule_color case rule_style when :dashed dash rule_width * 4 when :dotted dash rule_width when :double stroke_vertical_line rule_y_from, rule_y_to, at: (rule_x - rule_width) rule_x += rule_width end if rule_style stroke_vertical_line rule_y_from, rule_y_to, at: rule_x end end # Strokes a horizontal line using the current bounds. The width of the line # can be specified using the line_width option. # def stroke_horizontal_rule rule_color = stroke_color, options = {} rule_style = options[:line_style] rule_width = options[:line_width] || 0.5 rule_x_start = bounds.left rule_x_end = bounds.right rule_inked = false save_graphics_state do line_width rule_width stroke_color rule_color case rule_style when :dashed dash rule_width * 4 when :dotted dash rule_width when :double move_up rule_width stroke_horizontal_line rule_x_start, rule_x_end move_down rule_width * 2 stroke_horizontal_line rule_x_start, rule_x_end move_up rule_width rule_inked = true end if rule_style stroke_horizontal_line rule_x_start, rule_x_end unless rule_inked end end # Pages # Deletes the current page and move the cursor # to the previous page. def delete_page pg = page_number pdf_store = state.store pdf_objs = pdf_store.instance_variable_get :@objects pdf_ids = pdf_store.instance_variable_get :@identifiers page_id = pdf_store.object_id_for_page pg content_id = page.content.identifier [page_id, content_id].each do |key| pdf_objs.delete key pdf_ids.delete key end pdf_store.pages.data[:Kids].pop pdf_store.pages.data[:Count] -= 1 state.pages.pop if pg > 1 go_to_page pg - 1 else @page_number = 0 state.page = nil end end # Import the specified page into the current document. # # By default, advance to the next page afterwards, creating it if necessary. # This behavior can be disabled by passing the option `advance: false`. # However, due to how page creation works in Prawn, understand that advancing # to the next page is necessary to prevent the size & layout of the imported # page from affecting a newly created page. def import_page file, opts = {} prev_page_layout = page.layout prev_page_size = page.size state.compress = false if state.compress # can't use compression if using template prev_text_rendering_mode = (defined? @text_rendering_mode) ? @text_rendering_mode : nil delete_page if opts[:replace] # NOTE use functionality provided by prawn-templates start_new_page_discretely template: file, template_page: opts[:page] # prawn-templates sets text_rendering_mode to :unknown, which breaks running content; revert @text_rendering_mode = prev_text_rendering_mode if opts.fetch :advance, true # NOTE set page size & layout explicitly in case imported page differs # I'm not sure it's right to start a new page here, but unfortunately there's no other # way atm to prevent the size & layout of the imported page from affecting subsequent pages advance_page size: prev_page_size, layout: prev_page_layout end nil end # Create a new page for the specified image. If the canvas option is true, # the image is positioned relative to the boundaries of the page. def image_page file, options = {} start_new_page_discretely image_page_number = page_number if options.delete :canvas canvas { image file, ({ position: :center, vposition: :center }.merge options) } else image file, (options.merge position: :center, vposition: :center, fit: [bounds.width, bounds.height]) end # NOTE advance to newly created page just in case the image function threw off the cursor go_to_page image_page_number nil end # Perform an operation (such as creating a new page) without triggering the on_page_create callback # def perform_discretely if (saved_callback = state.on_page_create_callback) # equivalent to calling `on_page_create` state.on_page_create_callback = nil yield # equivalent to calling `on_page_create &saved_callback` state.on_page_create_callback = saved_callback else yield end end # This method is a smarter version of start_new_page. It calls start_new_page # if the current page is the last page of the document. Otherwise, it simply # advances to the next existing page. def advance_page opts = {} last_page? ? (start_new_page opts) : (go_to_page page_number + 1) end # Start a new page without triggering the on_page_create callback # def start_new_page_discretely options = {} perform_discretely { start_new_page options } end # Grouping # Conditional group operation # def group_if verdict if verdict state.optimize_objects = false # optimize objects breaks group group { yield } else yield end end def get_scratch_document # marshal if not using transaction feature #Marshal.load Marshal.dump @prototype # use cached instance, tests show it's faster #@prototype ||= ::Prawn::Document.new @scratch ||= if defined? @prototype scratch = Marshal.load Marshal.dump @prototype scratch.instance_variable_set(:@prototype, @prototype) # TODO set scratch number on scratch document scratch else logger.warn 'no scratch prototype available; instantiating fresh scratch document' ::Prawn::Document.new end end def scratch? (@_label ||= (state.store.info.data[:Scratch] ? :scratch : :primary)) == :scratch rescue false # NOTE this method may get called before the state is initialized end alias is_scratch? scratch? # TODO document me def dry_run &block scratch = get_scratch_document # QUESTION should we use scratch.advance_page instead? scratch.start_new_page start_page_number = scratch.page_number start_y = scratch.y if (left_padding = bounds.total_left_padding) > 0 scratch.bounds.add_left_padding left_padding end if (right_padding = bounds.total_right_padding) > 0 scratch.bounds.add_right_padding right_padding end scratch.font font_family, style: font_style, size: font_size do scratch.instance_exec(&block) end # NOTE don't count excess if cursor exceeds writable area (due to padding) full_page_height = scratch.effective_page_height partial_page_height = [full_page_height, start_y - scratch.y].min scratch.bounds.subtract_left_padding left_padding if left_padding > 0 scratch.bounds.subtract_right_padding right_padding if right_padding > 0 whole_pages = scratch.page_number - start_page_number [(whole_pages * full_page_height + partial_page_height), whole_pages, partial_page_height] end # Attempt to keep the objects generated in the block on the same page # # TODO short-circuit nested usage def keep_together &block available_space = cursor total_height, _, _ = dry_run(&block) # NOTE technically, if we're at the page top, we don't even need to do the # dry run, except several uses of this method rely on the calculated height if total_height > available_space && !at_page_top? && total_height <= effective_page_height advance_page started_new_page = true else started_new_page = false end # HACK yield doesn't work here on JRuby (at least not when called from AsciidoctorJ) #yield remainder, started_new_page instance_exec(total_height, started_new_page, &block) end # Attempt to keep the objects generated in the block on the same page # if the verdict parameter is true. # def keep_together_if verdict, &block if verdict keep_together(&block) else yield end end =begin def run_with_trial &block available_space = cursor total_height, whole_pages, remainder = dry_run(&block) if whole_pages > 0 || remainder > available_space started_new_page = true else started_new_page = false end # HACK yield doesn't work here on JRuby (at least not when called from AsciidoctorJ) #yield remainder, started_new_page instance_exec(remainder, started_new_page, &block) end =end end end end
31.459399
116
0.697511
e9b6824d84613d12ee34a3427137afeeade6c6be
23
module PoniesHelper end
11.5
19
0.913043
ab623b6ae69cedbe693c73febf3907652559e415
2,693
# # Cookbook Name:: ipfs # Recipe:: default # # The MIT License (MIT) # # Copyright:: 2018, Kosmos Developers # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. include_recipe 'ipfs::_user' version = node['ipfs']['version'] ark 'ipfs' do url "https://dist.ipfs.io/go-ipfs/v#{version}/go-ipfs_v#{version}_linux-amd64.tar.gz" checksum node['ipfs']['checksum'] has_binaries ['ipfs'] notifies :restart, 'service[ipfs]', :delayed end execute 'ipfs init --empty-repo' do environment 'IPFS_PATH' => '/home/ipfs/.ipfs' user 'ipfs' not_if { File.directory? '/home/ipfs/.ipfs' } end if platform?('ubuntu') && node['platform_version'].to_f < 15.04 || platform?('debian') && node['platform_version'].to_f < 8 template 'ipfs.initd.service.erb' do path '/etc/init.d/ipfs' source 'ipfs.initd.service.erb' owner 'root' group 'root' mode '0750' notifies :restart, 'service[ipfs]', :delayed end service 'ipfs' do provider Chef::Provider::Service::Init::Debian action [:enable] supports start: true, stop: true, restart: true, reload: false, status: true end else execute 'systemctl daemon-reload' do command 'systemctl daemon-reload' action :nothing end template 'ipfs.systemd.service.erb' do path '/lib/systemd/system/ipfs.service' source 'ipfs.systemd.service.erb' owner 'root' group 'root' mode '0644' notifies :run, 'execute[systemctl daemon-reload]', :delayed notifies :restart, 'service[ipfs]', :delayed end service 'ipfs' do provider Chef::Provider::Service::Systemd action [:enable] end end node['ipfs']['config'].each do |k, v| ipfs_config k do value v end end
30.602273
87
0.712217
bb951b05b59dc2fa3279faed2d71d992021c4ced
97
class IngredientsProduct < ApplicationRecord belongs_to :product belongs_to :ingredient end
16.166667
44
0.824742
b94ba0f6cff7de69ee07dcb46474e7c21779236c
285
class NOVAHawk::Providers::Google::CloudManager::MetricsCollectorWorker < NOVAHawk::Providers::BaseManager::MetricsCollectorWorker require_nested :Runner self.default_queue_name = "google" def friendly_name @friendly_name ||= "C&U Metrics Collector for Google" end end
25.909091
73
0.778947
f776a4278b6876be7ea3b3be833e3f370e036cbb
198
module XingApi class User class BusinessAddress < XingApi::Base def self.update(options = {}) request(:put, '/v1/users/me/business_address', options) end end end end
19.8
63
0.641414
1d6a4c8df9772b0c0bceaa8cbaf1944741adf8e6
1,621
class ListingRequestsController < ApplicationController skip_before_action :authenticate_user #, only: [:show, :create] def create @pet = Pet.find(request_params.dig(:pet, :pet_id)) render_unprocessable unless current_user && @pet if @pet @listing_requests = ListingRequest.new(request_params.except(:pet)) @listing_requests.pet = @pet @listing_requests.user = current_user if @listing_requests.save! render json: @listing_requests, status: :ok else render_unprocessable end end end def index render json: current_user.listing_requests, status: :ok end def show # debugger if requests_belongs_to_current_user @listing_request = current_user.listing_requests.find(request_params[:id]) render json: @listing_request, status: :ok else render_not_found end end def update end def destroy if requests_belongs_to_current_user @listing_request = current_user.listing_requests.find(request_params[:id]) @listing_request.destroy render json: {}, status: :ok else render_unprocessable end end private def request_params params.permit(:message, :id, pet: [:pet_id]) end def current_user_ids current_user.listing_requests.ids end def requests_belongs_to_current_user current_user_ids.include?(request_params[:id].to_i) end end
27.474576
86
0.61752
fff81f3247b073cfd60de25bf0419cfc08687308
9,951
# frozen_string_literal: true require 'spec_helper' require 'et_azure_insights/trace_parent' RSpec.describe EtAzureInsights::TraceParent do subject(:trace_parent) { described_class } describe '.parse' do it 'should return a TraceParent' do result = trace_parent.parse('00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01') expect(result).to be_a(described_class) end it 'should parse a valid traceparent into its component parts' do result = trace_parent.parse('00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01') expect(result).to have_attributes version: '00', trace_id: '4bf92f3577b34da6a3ce929d0e0e4736', span_id: '00f067aa0ba902b7', trace_flag: '01' end it 'sets trace_id and span_id to random values if more than 1 traceparent is present' do result = trace_parent.parse('00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01,00-5bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '4bf92f3577b34da6a3ce929d0e0e4736' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: satisfy { |v| v != '00f067aa0ba902b7' && v =~ /\A[0-9a-z]{16}\z/ }, trace_flag: '01' end it 'sets trace_id and span_id to random values if traceparent doesnt have enough values' do result = trace_parent.parse('00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '4bf92f3577b34da6a3ce929d0e0e4736' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: satisfy { |v| v != '00f067aa0ba902b7' && v =~ /\A[0-9a-z]{16}\z/ }, trace_flag: '01' end it 'sets trace_id to random value and version to 00 if version is not valid lower case hex' do result = trace_parent.parse('0F-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '4bf92f3577b34da6a3ce929d0e0e4736' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: '00f067aa0ba902b7', trace_flag: '01' end it 'sets trace_id and span_id to random values if version is 00 and the number of parts in the traceparent is not 4' do result = trace_parent.parse('00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-99') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '4bf92f3577b34da6a3ce929d0e0e4736' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: satisfy { |v| v != '00f067aa0ba902b7' && v =~ /\A[0-9a-z]{16}\z/ }, trace_flag: '01' end it 'sets version to 00, trace_id and span_id to random versions if the version is ff' do result = trace_parent.parse('ff-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '4bf92f3577b34da6a3ce929d0e0e4736' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: satisfy { |v| v != '00f067aa0ba902b7' && v =~ /\A[0-9a-z]{16}\z/ }, trace_flag: '01' end it 'sets version to 00 if the version does not match /^0[0-9a-f]$/' do result = trace_parent.parse('1f-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01') expect(result).to have_attributes version: '00', trace_id: '4bf92f3577b34da6a3ce929d0e0e4736', span_id: '00f067aa0ba902b7', trace_flag: '01' end it 'sets the trace_id to random value and the trace_flag to default if the trace_flag is not valid lowercase hex' do result = trace_parent.parse('00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-FE') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '4bf92f3577b34da6a3ce929d0e0e4736' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: '00f067aa0ba902b7', trace_flag: '01' end it 'sets the trace_id to new random value if trace_id is 32 zeros' do result = trace_parent.parse('00-00000000000000000000000000000000-00f067aa0ba902b7-01') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '00000000000000000000000000000000' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: '00f067aa0ba902b7', trace_flag: '01' end it 'sets the trace_id to new random value if trace_id is >32 hex chars' do result = trace_parent.parse('00-4bf92f3577b34da6a3ce929d0e0e4736a-00f067aa0ba902b7-01') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '4bf92f3577b34da6a3ce929d0e0e4736a' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: '00f067aa0ba902b7', trace_flag: '01' end it 'sets the trace_id to new random value if trace_id is <32 hex chars' do result = trace_parent.parse('00-4bf92f3577b34da6a3ce929d0e0e473-00f067aa0ba902b7-01') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '4bf92f3577b34da6a3ce929d0e0e473' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: '00f067aa0ba902b7', trace_flag: '01' end it 'sets the trace_id to new random value if trace_id is 32 chars but 1 not hex' do result = trace_parent.parse('00-gbf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != 'gbf92f3577b34da6a3ce929d0e0e4736' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: '00f067aa0ba902b7', trace_flag: '01' end it 'sets the span_id and trace_id to a random value if span_id is 16 zeros' do result = trace_parent.parse('00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000000-01') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '4bf92f3577b34da6a3ce929d0e0e4736' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: satisfy { |v| v != '0000000000000000' && v =~ /\A[0-9a-z]{16}\z/ }, trace_flag: '01' end it 'sets the span_id and trace_id to a random value if span_id is < 16 hex digits' do result = trace_parent.parse('00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b-01') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '4bf92f3577b34da6a3ce929d0e0e4736' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: satisfy { |v| v != '00f067aa0ba902b' && v =~ /\A[0-9a-z]{16}\z/ }, trace_flag: '01' end it 'sets the span_id and trace_id to a random value if span_id is > 16 hex digits' do result = trace_parent.parse('00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902bab-01') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '4bf92f3577b34da6a3ce929d0e0e4736' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: satisfy { |v| v != '00f067aa0ba902bab' && v =~ /\A[0-9a-z]{16}\z/ }, trace_flag: '01' end it 'sets the span_id and trace_id to a random value if span_id is 16 chars but 1 is not hex' do result = trace_parent.parse('00-4bf92f3577b34da6a3ce929d0e0e4736-g0f067aa0ba902ba-01') expect(result).to have_attributes version: '00', trace_id: satisfy { |v| v != '4bf92f3577b34da6a3ce929d0e0e4736' && v =~ /\A[0-9a-z]{32}\z/ }, span_id: satisfy { |v| v != 'g0f067aa0ba902ba' && v =~ /\A[0-9a-z]{16}\z/ }, trace_flag: '01' end end describe '.from_span' do let(:example_span) do parent = EtAzureInsights::Correlation::Span.new(id: '0123456789abcdef0123456789abcdef', name: 'Fake operation', parent: EtAzureInsights::Correlation::RootSpan.new) EtAzureInsights::Correlation::Span.new id: '0123456789abcdef', name: 'fake child span', parent: parent end it 'should return a TraceParent' do result = trace_parent.from_span(example_span) expect(result).to be_a(described_class) end it 'has the correct traceid' do result = trace_parent.from_span(example_span) expect(result.trace_id).to eq '0123456789abcdef0123456789abcdef' end it 'has the correct spanid' do result = trace_parent.from_span(example_span) expect(result.span_id).to eq '0123456789abcdef' end end describe '#to_s' do it 'outputs in the correct format' do result = trace_parent.parse('01-0123456789abcdef0123456789abcdef-0123456789abcdef-01').to_s expect(result).to eq '01-0123456789abcdef0123456789abcdef-0123456789abcdef-01' end end end
57.854651
169
0.569993
7983a7220396ff0427cc06c525e38966a40b7a14
1,327
require_relative "macho/structure" require_relative "macho/view" require_relative "macho/headers" require_relative "macho/load_commands" require_relative "macho/sections" require_relative "macho/macho_file" require_relative "macho/fat_file" require_relative "macho/exceptions" require_relative "macho/utils" require_relative "macho/tools" # The primary namespace for ruby-macho. module MachO # release version VERSION = "2.1.0".freeze # Opens the given filename as a MachOFile or FatFile, depending on its magic. # @param filename [String] the file being opened # @return [MachOFile] if the file is a Mach-O # @return [FatFile] if the file is a Fat file # @raise [ArgumentError] if the given file does not exist # @raise [TruncatedFileError] if the file is too small to have a valid header # @raise [MagicError] if the file's magic is not valid Mach-O magic def self.open(filename) raise ArgumentError, "#{filename}: no such file" unless File.file?(filename) raise TruncatedFileError unless File.stat(filename).size >= 4 magic = File.open(filename, "rb") { |f| f.read(4) }.unpack("N").first if Utils.fat_magic?(magic) file = FatFile.new(filename) elsif Utils.magic?(magic) file = MachOFile.new(filename) else raise MagicError, magic end file end end
32.365854
80
0.730972
0891fc42a01bdf43ff8a1f9fffa9f9c431621523
1,535
Winnipegrb::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 = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # 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 # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Raise exception on mass assignment protection for Active Record models config.active_record.mass_assignment_sanitizer = :strict # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) config.active_record.auto_explain_threshold_in_seconds = 0.5 # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true # To Mailer get the correct url config.action_mailer.default_url_options = { :host => 'localhost:3000' } config.assets.initialize_on_precompile = true end
36.547619
84
0.77785
1c111d533b8e51a25d01331db3166f64f536579c
2,780
require 'colored' require "cloudpad/version" require "cloudpad/task_utils" require "cloudpad/cloud" require "cloudpad/docker" require "cloudpad/kube" require "active_support/core_ext" module Cloudpad def self.gem_context_path File.expand_path("../../context", __FILE__) end def self.context=(ctx) @context = ctx end def self.context return @context end class Context def initialize(c) @context = c end def method_missing(name, *args, &block) @context.instance_eval {|obj| self.send name, *args, &block } end end module Puppet # install puppet def self.ensure_puppet_installed(c) # check if puppet already installed if !c.is_package_installed?("puppet") && !c.is_package_installed?("puppet-agent") c.info "Puppet not installed, installing..." c.execute "wget -O /tmp/puppetlabs.deb http://apt.puppetlabs.com/puppetlabs-release-pc1-`lsb_release -cs`.deb" c.execute "sudo dpkg -i /tmp/puppetlabs.deb" c.execute "sudo apt-get update" c.execute "sudo apt-get -y install puppet-agent" c.info "Puppet installation complete." else c.info "Puppet installed." end end def self.ensure_puppet_modules_installed(c) module_config = c.fetch(:puppet_modules) # get currently installed modules installed_modules = {} Dir.glob(File.join(c.puppet_path, "modules", "*", "metadata.json")).each {|fp| data = JSON.parse(File.read(fp)) installed_modules[data["name"]] = data } mod_dir = File.join c.puppet_path, "modules" module_config.each do |mod_name, ver| next if !installed_modules[mod_name].nil? cmd = "sudo puppet module install #{mod_name} --modulepath #{mod_dir} --version #{ver}" c.execute cmd end end def self.puppet_apply(c, opts={}) pbp = c.remote_file_exists?("/opt/puppetlabs/bin/puppet") ? "/opt/puppetlabs/bin/puppet" : "/usr/bin/puppet" mp = opts[:module_path] || "/etc/puppet/modules" mf = opts[:manifest] || "/etc/puppet/manifests/site.pp" cmd = "sudo #{pbp} apply --logdest syslog --modulepath #{mp} --verbose #{mf}" c.execute cmd end end end extend Cloudpad::TaskUtils load File.expand_path("../cloudpad/tasks/cloudpad.rake", __FILE__) load File.expand_path("../cloudpad/tasks/app.rake", __FILE__) load File.expand_path("../cloudpad/tasks/launcher.rake", __FILE__) load File.expand_path("../cloudpad/tasks/nodes.rake", __FILE__) load File.expand_path("../cloudpad/tasks/hosts.rake", __FILE__) load File.expand_path("../cloudpad/tasks/docker.rake", __FILE__) load File.expand_path("../cloudpad/tasks/kube.rake", __FILE__) Cloudpad.context = Cloudpad::Context.new(self)
30.888889
118
0.669784
ed1b1a459bfcae0ac10bc8c1cc42145b3de65013
129
RSpec.describe AdventOfCode2020 do it "has a version number" do expect(AdventOfCode2020::VERSION).not_to be nil end end
18.428571
51
0.75969
acdd11ec5c090a58932229898c6dc301e23064cb
1,733
#!/usr/bin/env ruby require 'net/http' require 'json' issuenumber = '' issuetitle = '' issuestatus = '' currentindex = 0 maxindex = 0 totalnumberofrecords = 0 repos_issues = Array.new numberofrecordstodisplay = 7 #plus 1 = 10 #Fetch data every 5 minutes SCHEDULER.every '5m', :first_in => 0 do |job| http = Net::HTTP.new("api.github.com", Net::HTTP.https_default_port()) http.use_ssl = true responseopen = http.request(Net::HTTP::Get.new("/repos/OpenSourceFieldlinguistics/FieldDB/issues?state=open")) responseclosed = http.request(Net::HTTP::Get.new("/repos/OpenSourceFieldlinguistics/FieldDB/issues?state=closed")) repos_issues = Array.new if responseopen.code != "200" puts "github api error (status-code: #{responseopen.code})\n#{responseopen.body}" else data = JSON.parse(responseopen.body) + JSON.parse(responseclosed.body) repos_issues = Array.new data.each do |repo| repos_issues.push({ number: repo['number'], titleofissue: repo['title'], status: repo['state'] }) end repos_issues = repos_issues.sort { |a,b| a[:number] <=> b[:number] } end totalnumberofrecords = repos_issues.length maxindex = totalnumberofrecords - numberofrecordstodisplay end # SCHEDULER #Cycle through data in DOM every 3s SCHEDULER.every '3s', :first_in => 0 do |job| if repos_issues[0] send_event('fielddb_issues', { items: repos_issues[currentindex..currentindex+numberofrecordstodisplay] }) else send_event('fielddb_issues', { items: [{ number: 'N/A', titleofissue: 'N/A', status: 'N/A' }] }) end #if if currentindex < maxindex currentindex += 1 else currentindex = 0 end #if end # SCHEDULER
29.87931
116
0.6809
01cf1965088b736b29f2263dfd84a8f29b28ca17
185
default_unless['sys']['updatedb']['prunebindmounts'] = String.new default_unless['sys']['updatedb']['prunepaths'] = String.new default_unless['sys']['updatedb']['prunefs'] = String.new
46.25
65
0.724324
ff4459dc696f6b0f3e5519fa1774c8b7ae4e7f2b
6,572
require 'minitest' def run_spec_test(test_case, options = {}) if test_case.todo? skip "Skipped todo" unless options[:run_todo] end assert_filename_length!(test_case.input_path, options) assert_filename_length!(test_case.expected_path, options) assert File.exists?(test_case.input_path), "Input #{test_case.input_path} file does not exist" output, clean_output, error, status = test_case.output if test_case.overwrite? if status != 0 File.open(test_case.status_path, "w+", :binmode => true) do |f| f.write(status) end elsif (File.file?(test_case.status_path)) File.unlink(test_case.status_path) end if error.length > 0 File.open(test_case.error_path, "w+", :binmode => true) do |f| f.write(error) end elsif (File.file?(test_case.error_path)) File.unlink(test_case.error_path) end File.open(test_case.expected_path, "w+", :binmode => true) do |f| f.write(output) end end assert File.exists?(test_case.expected_path), "Expected #{test_case.expected_path} file does not exist" begin if test_case.should_fail? # XXX Ruby returns 65 etc. SassC returns 1 refute_equal status, 0, "Test case should fail, but it did not" else assert_equal 0, status, "Command `#{options[:engine_adapter]}` did not complete:\n\n#{error}" end assert_equal test_case.expected, clean_output, "Expected did not match output" if test_case.verify_stderr? # Compare only first line of error output (we can't compare stacktraces etc.) begin skip = false error_lines = error.each_line while error_line = error_lines.next do if (error_line =~ /DEPRECATION WARNING/) skip = false end if (error_line =~ /Error:/) skip = false end # disable once we support this deprecation fully if (error_line =~ /interpolation near operators will be simplified/) skip = true next end # disable once we support this deprecation fully # if (error_line =~ /The subject selector operator \"!\" is deprecated and will be removed/) # skip = true # next # end # disable once we support this deprecation fully if (error_line =~ /Passing a percentage as the alpha/) skip = true next end # disable once we support this deprecation fully (partial now) # if (error_line =~ /, a non-string value, to unquote()/) # skip = true # next # end if (skip) next end error_msg = error_line.rstrip break end expected_error_lines = test_case.expected_error.each_line while expected_error_line = expected_error_lines.next do if (expected_error_line =~ /DEPRECATION WARNING/) skip = false end if (expected_error_line =~ /Error:/) skip = false end # disable once we support this deprecation fully if (expected_error_line =~ /interpolation near operators will be simplified/) skip = true next end # disable once we support this deprecation fully # if (expected_error_line =~ /The subject selector operator \"!\" is deprecated and will be removed/) # skip = true # next # end # disable once we support this deprecation fully if (expected_error_line =~ /Passing a percentage as the alpha/) skip = true next end # disable once we support this deprecation fully (partial now) # if (expected_error_line =~ /, a non-string value, to unquote()/) # skip = true # next # end if (skip) next end expected_error_msg = expected_error_line.rstrip break end error_msg = _clean_debug_path(error_msg, options[:spec_directory]) expected_error_msg = _clean_debug_path(expected_error_msg, options[:spec_directory]) assert_equal expected_error_msg, error_msg, "Expected did not match error" rescue StopIteration assert_equal expected_error_msg, nil, "No error message produced" end end rescue Minitest::Assertion if test_case.todo? && options[:unexpected_pass] pass else raise end else if test_case.todo? && options[:unexpected_pass] raise "#{test_case.input_path} passed a test we expected it to fail" else pass end end end GEMFILE_PREFIX_LENGTH = 68 # When running sass-spec as a gem from github very long filenames # can cause installation issues. This checks that the paths in use will work. def assert_filename_length!(filename, options) name = relative_name = filename.to_s.sub(File.expand_path(options[:spec_directory]), "") assert false, "Filename #{name} must no more than #{256 - GEMFILE_PREFIX_LENGTH} characters long" if name.size > (256 - GEMFILE_PREFIX_LENGTH) if name.size <= 100 then prefix = "" else parts = name.split(/\//) newname = parts.pop nxt = "" loop do nxt = parts.pop break if newname.size + 1 + nxt.size > 100 newname = nxt + "/" + newname end prefix = (parts + [nxt]).join "/" name = newname assert false, "base name (#{name}) of #{relative_name} must no more than 100 characters long" if name.size > 100 assert false, "prefix (#{prefix}) of #{relative_name} must no more than #{155 - GEMFILE_PREFIX_LENGTH} characters long" if prefix.size > (155 - GEMFILE_PREFIX_LENGTH) end return nil end def _clean_debug_path(error, spec_dir) spec_dir = File.expand_path(spec_dir) url = spec_dir.gsub(/\\/, '\/') error.gsub(/^.*?(input.scss:\d+ DEBUG:)/, '\1') .gsub(/\/+/, "/") .gsub(/^#{Regexp.quote(url)}\//, "/sass/sass-spec/") .gsub(/^#{Regexp.quote(spec_dir)}\//, "/sass/sass-spec/") .gsub(/(?:\/todo_|_todo\/)/, "/") .gsub(/\/libsass\-[a-z]+\-tests\//, "/") .gsub(/\/libsass\-[a-z]+\-issues/, "/libsass-issues") .strip end # Holder to put and run test cases class SassSpec::Test < Minitest::Test def self.create_tests(test_cases, options = {}) test_cases[0..options[:limit]].each do |test_case| define_method("test__#{test_case.name}") do run_spec_test(test_case, options) end end end end
33.876289
170
0.617012
79d66d040c4cc15327ebaf33116ee1ec20f3a351
177
FactoryBot.define do factory :confirmed_user, parent: :user do confirmed_at { Time.now } confirmation_sent_at { Time.now } confirmation_token { '12345' } end end
25.285714
43
0.711864
21f2c2d7d44cdc253f6b8f4bfe66af7644219392
177
RSpec.describe Heroes do it "has a version number" do expect(Heroes::VERSION).not_to be nil end it "does something useful" do expect(false).to eq(true) end end
17.7
41
0.694915
91a82c50c1c672bf80fece7248a90ebb13229053
1,140
cask 'microsoft-r-open' do version '3.4.3' sha256 '4998500839389821f995d3ebb89ee7e8e5a35a61a63ba0ac54d63adf53288947' # mran.blob.core.windows.net was verified as official when first introduced to the cask url "https://mran.blob.core.windows.net/install/mro/#{version}/microsoft-r-open-#{version}.pkg" name 'Microsoft R Open' name 'MRO' homepage 'https://mran.microsoft.com/' pkg "microsoft-r-open-#{version}.pkg" uninstall pkgutil: [ 'com.microsoft.pkg.mro-framework', 'com.microsoft.pkg.mro-gui', ], delete: [ '/usr/bin/R', '/usr/bin/Rscript', '/Library/Frameworks/R.Framework/Versions/Current', "/Library/Frameworks/R.Framework/Versions/#{version.major_minor}", ] zap trash: [ '~/.R', '~/.RData', '~/.Rapp.history', '~/.Rhistory', '~/.Rprofile', '~/Library/R', '~/Library/Caches/org.R-project.R', ] end
33.529412
97
0.513158
1138106b8066cecc523e2c6fcbc3cf15e490ab25
907
require 'test_helper' class Abilities::ImpersonateTest < ActiveSupport::TestCase def setup @provider = FactoryBot.create :provider_account end test "master admin cannot impersonate provider accounts without 3scale admin user" do user = Account.master.admins.first assert_cannot Ability.new(user), :impersonate, @provider end test "master admin can impersonate provider accounts" do @provider.admins.first.update_attribute :username, ThreeScale.config.impersonation_admin['username'] @provider.reload user = Account.master.admins.first assert_can Ability.new(user), :impersonate, @provider end test "provider admin users cannot impersonate" do @provider.admins.first.update_attribute :username, ThreeScale.config.impersonation_admin['username'] @provider.reload assert_cannot Ability.new(@provider.admins.first), :impersonate, @provider end end
31.275862
104
0.768467
1175b6cc16981e845b484805ec3f4feb4bd30db6
2,758
# encoding: UTF-8 # This file contains data derived from the IANA Time Zone Database # (http://www.iana.org/time-zones). module TZInfo module Data module Definitions module America module Cancun include TimezoneDefinition timezone 'America/Cancun' do |tz| tz.offset :o0, -20824, 0, :LMT tz.offset :o1, -21600, 0, :CST tz.offset :o2, -18000, 0, :EST tz.offset :o3, -18000, 3600, :EDT tz.offset :o4, -21600, 3600, :CDT tz.transition 1922, 1, :o1, -1514743200, 9692223, 4 tz.transition 1981, 12, :o2, 377935200 tz.transition 1996, 4, :o3, 828860400 tz.transition 1996, 10, :o2, 846396000 tz.transition 1997, 4, :o3, 860310000 tz.transition 1997, 10, :o2, 877845600 tz.transition 1998, 4, :o3, 891759600 tz.transition 1998, 8, :o4, 902037600 tz.transition 1998, 10, :o1, 909298800 tz.transition 1999, 4, :o4, 923212800 tz.transition 1999, 10, :o1, 941353200 tz.transition 2000, 4, :o4, 954662400 tz.transition 2000, 10, :o1, 972802800 tz.transition 2001, 5, :o4, 989136000 tz.transition 2001, 9, :o1, 1001833200 tz.transition 2002, 4, :o4, 1018166400 tz.transition 2002, 10, :o1, 1035702000 tz.transition 2003, 4, :o4, 1049616000 tz.transition 2003, 10, :o1, 1067151600 tz.transition 2004, 4, :o4, 1081065600 tz.transition 2004, 10, :o1, 1099206000 tz.transition 2005, 4, :o4, 1112515200 tz.transition 2005, 10, :o1, 1130655600 tz.transition 2006, 4, :o4, 1143964800 tz.transition 2006, 10, :o1, 1162105200 tz.transition 2007, 4, :o4, 1175414400 tz.transition 2007, 10, :o1, 1193554800 tz.transition 2008, 4, :o4, 1207468800 tz.transition 2008, 10, :o1, 1225004400 tz.transition 2009, 4, :o4, 1238918400 tz.transition 2009, 10, :o1, 1256454000 tz.transition 2010, 4, :o4, 1270368000 tz.transition 2010, 10, :o1, 1288508400 tz.transition 2011, 4, :o4, 1301817600 tz.transition 2011, 10, :o1, 1319958000 tz.transition 2012, 4, :o4, 1333267200 tz.transition 2012, 10, :o1, 1351407600 tz.transition 2013, 4, :o4, 1365321600 tz.transition 2013, 10, :o1, 1382857200 tz.transition 2014, 4, :o4, 1396771200 tz.transition 2014, 10, :o1, 1414306800 tz.transition 2015, 2, :o2, 1422777600 end end end end end end
40.558824
66
0.563452
6131c3b55db1c63f3dd5ee5e0ddf474234403da6
2,599
# # specifying flor # # Wed May 31 05:14:14 JST 2017 圓さんの家 # require 'spec_helper' describe 'Flor procedures' do before :each do @executor = Flor::TransientExecutor.new end describe 'length' do it 'returns the length of its argument' do r = @executor.launch( %q{ [ (length [ 'a' 'b' 'c' ]) (length a0) (length a1) (length h0) #(length h0.a) #(length h0.b) ({ a: 'A', b: 'B'}; length _) ] }, vars: { 'a0' => [], 'a1' => [ 1, 2 ], 'h0' => { 'a' => 0 } }) expect(r['point']).to eq('terminated') expect(r['payload']['ret']).to eq([ 3, 0, 2, 1, 2 ]) end it 'fails if there are no argument with a length' do r = @executor.launch( %q{ length _ }) expect(r['point']).to eq('failed') expect(r['error']['kla']).to eq('Flor::FlorError') expect(r['error']['msg']).to eq('found no argument that has a length') expect(r['error']['lin']).to eq(2) end it 'returns the length of the non-att argument' do r = @executor.launch( %q{ length [ 0 1 2 ] tag: 'x' }) expect(r['point']).to eq('terminated') expect(r['payload']['ret']).to eq(3) end it 'returns the length of f.ret by default' do r = @executor.launch( %q{ [ 0 1 2 ] length _ }) expect(r['point']).to eq('terminated') expect(r['payload']['ret']).to eq(3) end it 'returns the length of f.ret by default (tag has no effect)' do r = @executor.launch( %q{ [ 0 1 2 ] length tag: 'a' }) expect(r['point']).to eq('terminated') expect(r['payload']['ret']).to eq(3) end end describe 'size' do it 'is an alias to "size"' do r = @executor.launch( %q{ set f.customers [ 'alice' 'bob' 'charly' 'doug' ] [ (size [ 'a' 'b' 'c' ]) (size a0) (size a1) (size h0) #(size h0.a) #(size h0.b) ({ a: 'A', b: 'B'}; size _) (case (size f.customers) 0; 'zero' [ 1 3 ]; 'one to three' [ 4 6 ]; 'four to six' else; 'seven or more') ] }, vars: { 'a0' => [], 'a1' => [ 1, 2 ], 'h0' => { 'a' => 0 } }) expect(r['point']).to eq('terminated') expect(r['payload']['ret']).to eq([ 3, 0, 2, 1, 2, 'four to six' ]) end end end
21.658333
76
0.442093
8777c00b397f18f94618489d333911131f73e50c
4,389
class Msitools < Formula desc "Windows installer (.MSI) tool" homepage "https://wiki.gnome.org/msitools" url "https://download.gnome.org/sources/msitools/0.100/msitools-0.100.tar.xz" sha256 "bbf1a6e3a9c2323b860a3227ac176736a3eafc4a44a67346c6844591f10978ea" license "GPL-2.0" livecheck do url :stable end bottle do sha256 "0c1f853fe5b312dead4d5d805f17b9620b8c5a759167e8ea38fea102bcd7579f" => :big_sur sha256 "f9b65f68c973c323e96a0492df562bae32e3ede79d9e5a6f24b89f53ef085883" => :catalina sha256 "b7646423954ae62a8dcb8ee413f98e0f5e1c4b8a73876255fcd2f0371e547f92" => :mojave sha256 "fd8689ba0902ed4d784f85969d281a0e1c58bb76f0fe17a93d96ba2d3f845cdb" => :high_sierra end depends_on "intltool" => :build depends_on "pkg-config" => :build depends_on "e2fsprogs" depends_on "gcab" depends_on "gettext" depends_on "glib" depends_on "libgsf" depends_on "vala" # Workaround for https://gitlab.gnome.org/GNOME/msitools/issues/15 # Merged upstream in the following commits: # https://gitlab.gnome.org/GNOME/msitools/commit/248450a2f2a23df59428fa816865a26f7e2496e0 # https://gitlab.gnome.org/GNOME/msitools/commit/9bbcc6da06ccf6144258c26ddcaab3262538d3ce # Remove in next release. patch do url "https://gitlab.gnome.org/GNOME/msitools/commit/248450a2f2a23df59428fa816865a26f7e2496e0.patch" sha256 "32bf8c2995085c2751c3fe8cd67878ea28b2ee255f5d00ed3ea7c5fddea3d902" end patch do url "https://gitlab.gnome.org/GNOME/msitools/commit/9bbcc6da06ccf6144258c26ddcaab3262538d3ce.patch" sha256 "5178df1577a967e887a859fe1a6c791071712e3acfc6f898e1e83352b7336a9a" end def install system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end test do # wixl-heat: make an xml fragment assert_match /<Fragment>/, pipe_output("#{bin}/wixl-heat --prefix test") # wixl: build two installers 1.upto(2) do |i| (testpath/"test#{i}.txt").write "abc" (testpath/"installer#{i}.wxs").write <<~EOS <?xml version="1.0"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Product Id="*" UpgradeCode="DADAA9FC-54F7-4977-9EA1-8BDF6DC73C7#{i}" Name="Test" Version="1.0.0" Manufacturer="BigCo" Language="1033"> <Package InstallerVersion="200" Compressed="yes" Comments="Windows Installer Package"/> <Media Id="1" Cabinet="product.cab" EmbedCab="yes"/> <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="ProgramFilesFolder"> <Directory Id="INSTALLDIR" Name="test"> <Component Id="ApplicationFiles" Guid="52028951-5A2A-4FB6-B8B2-73EF49B320F#{i}"> <File Id="ApplicationFile1" Source="test#{i}.txt"/> </Component> </Directory> </Directory> </Directory> <Feature Id="DefaultFeature" Level="1"> <ComponentRef Id="ApplicationFiles"/> </Feature> </Product> </Wix> EOS system "#{bin}/wixl", "-o", "installer#{i}.msi", "installer#{i}.wxs" assert_predicate testpath/"installer#{i}.msi", :exist? end # msidiff: diff two installers lines = `#{bin}/msidiff --list installer1.msi installer2.msi 2>/dev/null`.split("\n") assert_equal 0, $CHILD_STATUS.exitstatus assert_equal "-Program Files/test/test1.txt", lines[-2] assert_equal "+Program Files/test/test2.txt", lines[-1] # msiinfo: show info for an installer out = `#{bin}/msiinfo suminfo installer1.msi` assert_equal 0, $CHILD_STATUS.exitstatus assert_match /Author: BigCo/, out # msiextract: extract files from an installer mkdir "files" system "#{bin}/msiextract", "--directory", "files", "installer1.msi" assert_equal (testpath/"test1.txt").read, (testpath/"files/Program Files/test/test1.txt").read # msidump: dump tables from an installer mkdir "idt" system "#{bin}/msidump", "--directory", "idt", "installer1.msi" assert_predicate testpath/"idt/File.idt", :exist? # msibuild: replace a table in an installer system "#{bin}/msibuild", "installer1.msi", "-i", "idt/File.idt" end end
39.540541
103
0.663021
bb24501912c988e83e7d26935868859f7adf1d67
318
# frozen_string_literal: true require_relative "./laughter_break/joke" require_relative "./laughter_break/api" require_relative "./laughter_break/cli" require_relative "./laughter_break/version" require "pry" require "httparty" module LaughterBreak class Error < StandardError; end # Your code goes here... end
21.2
43
0.789308
080a6199940478426e7ebeeaad05649191e9dae2
185
# frozen_string_literal: true control 'arvados workbench package' do title 'should be installed' describe package('arvados-workbench') do it { should be_installed } end end
18.5
42
0.745946
9109e2db2b27f67927d2d17db883d36958bd6ca9
697
class AddCreatorToPlans < ActiveRecord::Migration[6.0] class Plan < ActiveRecord::Base; end class Member < ActiveRecord::Base; end class User < ActiveRecord::Base; end def change change_table :plans do |t| t.bigint :creator_id, foreign_key: true end Plan.all.each do |plan| default_creator = User.where(email: "[email protected]").take default_member = Member.where(project_id: plan.project_id, user_id: default_creator.id).take default_member ||= Member.where(project_id: plan.project_id).first plan.update(creator_id: default_member.id) end change_column_null(:plans, :creator_id, false) add_index :plans, [:creator_id] end end
30.304348
98
0.711621
912361eab7af60c844c1ad21fc32029927bd0104
650
class AppDelegate def applicationDidFinishLaunching(notification) buildMenu buildWindow end def buildWindow @mainWindowController = MainWindowController.alloc.initWithWindowNibName('MainWindowController') @mainWindowController.window.makeKeyAndOrderFront(self) end end class MainWindowController < NSWindowController extend IB outlet :label, NSTextField outlet :button, NSButton def windowDidLoad @label.stringValue = 'oh hello there!' @button.bordered = false @button.cell.backgroundColor = NSColor.redColor end def button_pressed(sender) @label.stringValue = 'don’t touch that!' end end
20.967742
100
0.763077
381465cb089cb569a03992042ee5230c83f7a304
337
# return.rb def add_three(number) return number + 3 number + 4 end returned_value = add_three(4) #stores the result of the method (with 4 passed in as an argument) into the variable returned_value puts returned_value #prints the variable returned_value def just_assignment(number) foo = number + 3 end puts just_assignment(2)
22.466667
131
0.768546
91a55514a9a64d5d57e2425379ccf4895ac9d625
970
# Base class for deployment services # # These services integrate with a deployment solution like Kubernetes/OpenShift, # Mesosphere, etc, to provide additional features to environments. class DeploymentService < Service default_value_for :category, 'deployment' def self.supported_events %w() end def predefined_variables [] end # Environments may have a number of terminals. Should return an array of # hashes describing them, e.g.: # # [{ # :selectors => {"a" => "b", "foo" => "bar"}, # :url => "wss://external.example.com/exec", # :headers => {"Authorization" => "Token xxx"}, # :subprotocols => ["foo"], # :ca_pem => "----BEGIN CERTIFICATE...", # optional # :created_at => Time.now.utc # }] # # Selectors should be a set of values that uniquely identify a particular # terminal def terminals(environment) raise NotImplementedError end end
28.529412
80
0.626804
e99404153b6d67dd115023d1becbe9b94ff6c468
1,326
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'google/apis/vision_v1/service.rb' require 'google/apis/vision_v1/classes.rb' require 'google/apis/vision_v1/representations.rb' module Google module Apis # Cloud Vision API # # The Google Cloud Vision API allows developers to easily integrate Google # vision features, including image labeling, face, logo, and landmark detection, # optical character recognition (OCR), and detection of explicit content, into # applications. # # @see https://cloud.google.com/vision/ module VisionV1 VERSION = 'V1' REVISION = '20160308' # View and manage your data across Google Cloud Platform services AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform' end end end
34.894737
84
0.735294
e2da4e83973ce2faad119788bb101e6e814be7ab
439
require 'rails_helper' # Specs in this file have access to a helper object that includes # the SummaryHelper. For example: # # describe SummaryHelper do # describe "string concat" do # it "concats two strings with spaces" do # expect(helper.concat_strings("this","that")).to eq("this that") # end # end # end RSpec.describe SummaryHelper, :type => :helper do pending "add some examples to (or delete) #{__FILE__}" end
27.4375
71
0.703872
035e1cdcdd601fe76a301e9037c0c04b5c113336
194
# frozen_string_literal: true RSpec.describe(BetterGraphQL) do describe '.VERSION' do it 'returns version number' do expect(BetterGraphQL::VERSION).not_to(be(nil)) end end end
21.555556
52
0.721649
e95a962f392c1ffd15153036ce5a68ae00f8edec
245
module Departure class ConnectionBase < ActiveRecord::Base def self.establish_connection(config = nil) super.tap do ActiveRecord::Base.connection_specification_name = connection_specification_name end end end end
24.5
88
0.742857
ffe4c7376f43eb59286eebb7558ad1ca59887965
1,471
class DeviseCreateUsers < ActiveRecord::Migration def change create_table(:users) do |t| ## Database authenticatable t.string :email, :null => false, :default => "" t.string :encrypted_password, :null => false, :default => "" ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at ## Rememberable t.datetime :remember_created_at ## Trackable t.integer :sign_in_count, :default => 0 t.datetime :current_sign_in_at t.datetime :last_sign_in_at t.string :current_sign_in_ip t.string :last_sign_in_ip ## Confirmable t.string :confirmation_token t.datetime :confirmed_at t.datetime :confirmation_sent_at t.string :unconfirmed_email # Only if using reconfirmable ## Lockable # t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts # t.string :unlock_token # Only if unlock strategy is :email or :both # t.datetime :locked_at ## Token authenticatable # t.string :authentication_token t.timestamps end add_index :users, :email, :unique => true add_index :users, :reset_password_token, :unique => true add_index :users, :confirmation_token, :unique => true # add_index :users, :unlock_token, :unique => true # add_index :users, :authentication_token, :unique => true end end
31.978261
94
0.645139
87b697956adce76725c6752f679cf15a441f9add
816
require 'ebay/types/pagination' module Ebay # :nodoc: module Requests # :nodoc: # == Attributes # text_node :item_id, 'ItemID', :optional => true # text_node :best_offer_id, 'BestOfferID', :optional => true # text_node :best_offer_status, 'BestOfferStatus', :optional => true # object_node :pagination, 'Pagination', :class => Pagination, :optional => true class GetBestOffers < Abstract include XML::Mapping include Initializer root_element_name 'GetBestOffersRequest' text_node :item_id, 'ItemID', :optional => true text_node :best_offer_id, 'BestOfferID', :optional => true text_node :best_offer_status, 'BestOfferStatus', :optional => true object_node :pagination, 'Pagination', :class => Pagination, :optional => true end end end
35.478261
85
0.682598
ed4cdcc52abf74d4baa01f4b292d8cc6bb4d4452
1,416
require File.expand_path("../../helpers", __FILE__) class ScannerMeta < Test::Unit::TestCase tests = { 'abc??|def*+|ghi+' => { 0 => [:literal, :literal, 'abc', 0, 3], 1 => [:quantifier, :zero_or_one_reluctant, '??', 3, 5], 2 => [:meta, :alternation, '|', 5, 6], 3 => [:literal, :literal, 'def', 6, 9], 4 => [:quantifier, :zero_or_more_possessive, '*+', 9, 11], 5 => [:meta, :alternation, '|', 11, 12], }, '(a\|b)|(c|d)\|(e[|]f)' => { 2 => [:escape, :alternation, '\|', 2, 4], 5 => [:meta, :alternation, '|', 6, 7], 8 => [:meta, :alternation, '|', 9, 10], 11 => [:escape, :alternation, '\|', 12, 14], 15 => [:literal, :literal, '|', 17, 18], }, } tests.each_with_index do |(pattern, checks), count| define_method "test_scanner_meta_alternation_#{count}" do tokens = RS.scan(pattern) checks.each do |index, (type, token, text, ts, te)| result = tokens.at(index) assert_equal type, result[0] assert_equal token, result[1] assert_equal text, result[2] assert_equal ts, result[3] assert_equal te, result[4] end end end end
34.536585
70
0.440678