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
183a540476fcf055259a4475997f59dfca5dd780
2,268
# frozen_string_literal: true require 'spec_helper' describe AdventOfCode2020::Day14::Decoder::Version2 do let(:program) do described_class.new( [ 'mask = 000000000000000000000000000000X1001X', 'mem[42] = 100', 'mask = 00000000000000000000000000000000X0XX', 'mem[26] = 1' ] ) end describe '#run' do it 'runs the program' do program.run expect(program.memory[16]).to eq(1) expect(program.memory[17]).to eq(1) expect(program.memory[18]).to eq(1) expect(program.memory[19]).to eq(1) expect(program.memory[24]).to eq(1) expect(program.memory[25]).to eq(1) expect(program.memory[26]).to eq(1) expect(program.memory[27]).to eq(1) expect(program.memory[58]).to eq(100) expect(program.memory[59]).to eq(100) end end describe '#follow_instruction' do it 'updates the bitmask' do program.follow_instruction expect(program.instance_variable_get(:@bitmask)).to eq('000000000000000000000000000000X1001X') end it 'writes values to memory' do 2.times do program.follow_instruction end expect(program.memory[26]).to eq(100) expect(program.memory[27]).to eq(100) expect(program.memory[58]).to eq(100) expect(program.memory[59]).to eq(100) end it 'writes values to memory' do 3.times do program.follow_instruction end expect(program.memory[26]).to eq(100) expect(program.memory[27]).to eq(100) expect(program.memory[58]).to eq(100) expect(program.memory[59]).to eq(100) expect(program.instance_variable_get(:@bitmask)).to eq('00000000000000000000000000000000X0XX') end it 'writes values to memory' do 4.times do program.follow_instruction end expect(program.memory[16]).to eq(1) expect(program.memory[17]).to eq(1) expect(program.memory[18]).to eq(1) expect(program.memory[19]).to eq(1) expect(program.memory[24]).to eq(1) expect(program.memory[25]).to eq(1) expect(program.memory[26]).to eq(1) expect(program.memory[27]).to eq(1) expect(program.memory[58]).to eq(100) expect(program.memory[59]).to eq(100) end end end
28
100
0.638889
5dcbd7b099eb54bac570c3a96f85ff9f726c4f5a
186
class AddLocalFileToLogFile < ActiveRecord::Migration[4.2] def up add_column :log_files, :local_file, :string end def down remove_column :log_files, :local_file end end
18.6
58
0.736559
1c7676b831657037d6fa10dfa575944d4f70f69d
8,691
module FlatMap # == Mapper # # FlatMap mappers are designed to provide complex set of data, distributed over # associated AR models, in the simple form of a plain hash. They accept a plain # hash of the same format and distribute its values over deeply nested AR models. # # To achieve this goal, Mapper uses three major concepts: Mappings, Mountings and # Traits. # # === Mappings # # Mappings are defined view Mapper.map method. They represent a simple one-to-one # relation between target attribute and a mapper, extended by additional features # for convenience. The best way to show how they work is by example: # # class CustomerMapper < FlatMap::Mapper # # When there is no need to rename attributes, they can be passed as array: # map :first_name, :last_name # # # When hash is used, it will map field name to attribute name: # map :dob => :date_of_birth # # # Also, additional options can be used: # map :name_suffix, :format => :enum # map :password, :reader => false, :writer => :assign_password # # # Or you can combine all definitions together if they all are common: # map :first_name, :last_name, # :dob => :date_of_birth, # :suffix => :name_suffix, # :reader => :my_custom_reader # end # # When mappings are defined, one can read and write values using them: # # mapper = CustomerMapper.find(1) # mapper.read # => {:first_name => 'John', :last_name => 'Smith', :dob => '02/01/1970'} # mapper.write(params) # will assign same-looking hash of arguments # # Following options may be used when defining mappings: # [<tt>:format</tt>] Allows to additionally process output value on reading it. All formats are # defined within FlatMap::Mapping::Reader::Formatted::Formats and # specify the actual output of the mapping # [<tt>:reader</tt>] Allows you to manually control reader value of a mapping, or a group of # mappings listed on definition. When String or Symbol is used, will call # a method, defined by mapper class, and pass mapping object to it. When # lambda is used, mapper's target (the model) will be passed to it. # [<tt>:writer</tt>] Just like with the :reader option, allows to control how value is assigned # (written). Works the same way as :reader does, but additionally value is # sent to both mapper method and lambda. # [<tt>:multiparam</tt>] If used, multiparam attributes will be extracted from params, when # those are passed for writing. Class should be passed as a value for # this option. Object of this class will be initialized with the arguments # extracted from params hash. # # === Mountings # # Mappers may be mounted on top of each other. This ability allows host mapper to gain all the # mappings of the mounted mapper, thus providing more information for external usage (both reading # and writing). Usually, target for mounted mapper may be obtained from association of target of # the host mapper itself, but may be defined manually. # # class CustomerMapper < FlatMap::Mapper # map :first_name, :last_name # end # # class CustomerAccountMapper < FlatMap::Mapper # map :source, :brand, :format => :enum # # mount :customer # end # # mapper = CustomerAccountMapper.find(1) # mapper.read # => {:first_name => 'John', :last_name => 'Smith', :source => nil, :brand => 'FTW'} # mapper.write(params) # Will assign params for both CustomerAccount and Customer records # # The following options may be used when mounting a mapper: # [<tt>:mapper_class</tt>] Specifies mapper class if it cannot be determined from mounting itself # [<tt>:mapper_class_name</tt>] Alternate string form of class name instead of mapper_class. # [<tt>:target</tt>] Allows to manually specify target for the new mapper. May be an object or lambda # with arity of one that accepts host mapper target as argument. Comes in handy # when target cannot be obviously detected or requires additional setup: # <tt>mount :title, :target => lambda{ |customer| customer.title_customers.build.build_title }</tt> # [<tt>:traits</tt>] Specifies list of traits to be used by mounted mapper # [<tt>:suffix</tt>] Specifies the suffix that will be appended to all mappings and mountings of mapper, # as well as mapper name itself. # # === Traits # # Traits allow mappers to encapsulate named sets of additional definitions, and use them optionally # on mapper initialization. Everything that can be defined within the mapper may be defined within # the trait. In fact, from the implementation perspective traits are mappers themselves that are # mounted on the host mapper. # # class CustomerAccountMapper < FlatMap::Mapper # map :brand, :format => :enum # # trait :with_email do # map :source, :format => :enum # # mount :email_address # # trait :with_email_phones_residence do # mount :customer, :traits => [:with_phone_numbers, :with_residence] # end # end # end # # CustomerAccountMapper.find(1).read # => {:brand => 'TLP'} # CustomerAccountMapper.find(1, :with_email).read # => {:brand => 'TLP', :source => nil, :email_address => '[email protected]'} # CustomerAccountMapper.find(1, :with_email_phone_residence).read # => :brand, :source, :email_address, phone numbers, # #:residence attributes - all will be available for reading and writing in plain hash # # === Extensions # # When mounting a mapper, one can pass an optional block. This block is used as an extension for a mounted # mapper and acts as an anonymous trait. For example: # # class CustomerAccountMapper < FlatMap::Mapper # mount :customer do # map :dob => :date_of_birth, :format => :i18n_l # validates_presence_of :dob # # mount :unique_identifier # # validates_acceptance_of :mandatory_agreement, :message => "You must check this box to continue" # end # end # # === Validation # # <tt>FlatMap::Mapper</tt> includes <tt>ActiveModel::Validations</tt> module, allowing each model to # perform its own validation routines before trying to save its target (which is usually AR model). Mapper # validation is very handy when mappers are used with Rails forms, since there no need to lookup for a # deeply nested errors hash of the AR models to extract error messages. Mapper validations will attach # messages to mapping names. # # Mapper validations become even more useful when used within traits, providing way of very flexible validation sets. # # === Callbacks # # Since mappers include <tt>ActiveModel::Validation</tt>, they already support ActiveSupport's callbacks. # Additionally, <tt>:save</tt> callbacks have been defined (i.e. there have been define_callbacks <tt>:save</tt> # call for <tt>FlatMap::Mapper</tt>). This allows you to control flow of mapper saving: # # set_callback :save, :before, :set_model_validation # # def set_model_validation # target.use_validation :some_themis_validation # end # # === Skipping # # In some cases, it is required to omit mapper processing after it has been created within mounting chain. If # <tt>skip!</tt> method is called on mapper, it will return <tt>true</tt> for <tt>valid?</tt> and <tt>save</tt> # method calls without performing any other operations. For example: # # class CustomerMapper < FlatMap::Mapper # # some definitions # # trait :product_selection do # attr_reader :selected_product_id # # mount :product # # set_callback :validate, :before, :ignore_new_product # # def ignore_new_bank_account # mounting(:product).skip! if product_selected? # end # # # some more definitions # end # end # # === Attribute Methods # # All mappers have the ability to read and write values via method calls: # # mapper.read[:first_name] # => John # mapper.first_name # => 'John' # mapper.last_name = 'Smith' class ModelMapper < OpenMapper extend ActiveSupport::Autoload autoload :Persistence autoload :Skipping include Persistence include Skipping delegate :logger, :to => :target end end
44.341837
131
0.659763
33df4b20df51e6d09e7df7177e2e099b9eca5a34
585
cask "freeplane" do version "1.8.11" sha256 "5f558640e8811c0d4b515dfc67c4d9ef5d877dfb3b7c88a3578d97001f6b337a" url "https://downloads.sourceforge.net/freeplane/freeplane%20stable/Freeplane-#{version}.dmg", verified: "downloads.sourceforge.net/freeplane/" appcast "https://sourceforge.net/projects/freeplane/rss?path=/freeplane%20stable" name "Freeplane" desc "Mind mapping and knowledge management software" homepage "https://freeplane.sourceforge.io/" app "Freeplane.app" zap trash: "~/Library/Saved Application State/org.freeplane.launcher.savedState" end
36.5625
96
0.779487
7a9ec9c9ac9d92e6c54528fc9f4090e4f3f56e8a
1,355
module Fog module Compute class Cloudstack class Real def revoke_security_group_ingress(options={}) options.merge!( 'command' => 'revokeSecurityGroupIngress' ) request(options) end end # Real class Mock def revoke_security_group_ingress(options={}) unless security_group_rule_id = options['id'] raise Fog::Compute::Cloudstack::BadRequest.new('Unable to execute API command missing parameter id') end security_group = self.data[:security_groups].values.find do |group| (rule = (group['ingressrule'] || []).find{|r| r['ruleid'] == security_group_rule_id}) && group['ingressrule'].delete(rule) end job_id = Fog::Cloudstack.uuid job = { "cmd" => "com.cloud.api.commands.revokeSecurityGroupIngress", "created" => Time.now.iso8601, "jobid" => job_id, "jobstatus" => 1, "jobprocstatus" => 0, "jobresultcode" => 0, "jobresulttype" => "object", "jobresult" => { "securitygroup" => security_group } } self.data[:jobs][job_id]= job {"revokesecuritygroupingress" => { "jobid" => job_id }} end end end end end
30.795455
134
0.540221
18665885fcf1f6a428ffc4f2740bea0656e014ce
65,270
# coding: utf-8 # frozen_string_literal: true # external dependencies require 'rack' require 'tilt' require 'rack/protection' require 'mustermann' require 'mustermann/sinatra' require 'mustermann/regular' # stdlib dependencies require 'thread' require 'time' require 'uri' # other files we need require 'sinatra/indifferent_hash' require 'sinatra/show_exceptions' require 'sinatra/version' module Sinatra # The request object. See Rack::Request for more info: # http://rubydoc.info/github/rack/rack/master/Rack/Request class Request < Rack::Request HEADER_PARAM = /\s*[\w.]+=(?:[\w.]+|"(?:[^"\\]|\\.)*")?\s*/ HEADER_VALUE_WITH_PARAMS = /(?:(?:\w+|\*)\/(?:\w+(?:\.|\-|\+)?|\*)*)\s*(?:;#{HEADER_PARAM})*/ # Returns an array of acceptable media types for the response def accept @env['sinatra.accept'] ||= begin if @env.include? 'HTTP_ACCEPT' and @env['HTTP_ACCEPT'].to_s != '' @env['HTTP_ACCEPT'].to_s.scan(HEADER_VALUE_WITH_PARAMS). map! { |e| AcceptEntry.new(e) }.sort else [AcceptEntry.new('*/*')] end end end def accept?(type) preferred_type(type).to_s.include?(type) end def preferred_type(*types) return accept.first if types.empty? types.flatten! return types.first if accept.empty? accept.detect do |accept_header| type = types.detect { |t| MimeTypeEntry.new(t).accepts?(accept_header) } return type if type end end alias secure? ssl? def forwarded? @env.include? "HTTP_X_FORWARDED_HOST" end def safe? get? or head? or options? or trace? end def idempotent? safe? or put? or delete? or link? or unlink? end def link? request_method == "LINK" end def unlink? request_method == "UNLINK" end def params super rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e raise BadRequest, "Invalid query parameters: #{Rack::Utils.escape_html(e.message)}" end class AcceptEntry attr_accessor :params attr_reader :entry def initialize(entry) params = entry.scan(HEADER_PARAM).map! do |s| key, value = s.strip.split('=', 2) value = value[1..-2].gsub(/\\(.)/, '\1') if value.start_with?('"') [key, value] end @entry = entry @type = entry[/[^;]+/].delete(' ') @params = Hash[params] @q = @params.delete('q') { 1.0 }.to_f end def <=>(other) other.priority <=> self.priority end def priority # We sort in descending order; better matches should be higher. [ @q, [email protected]('*'), @params.size ] end def to_str @type end def to_s(full = false) full ? entry : to_str end def respond_to?(*args) super or to_str.respond_to?(*args) end def method_missing(*args, &block) to_str.send(*args, &block) end end class MimeTypeEntry attr_reader :params def initialize(entry) params = entry.scan(HEADER_PARAM).map! do |s| key, value = s.strip.split('=', 2) value = value[1..-2].gsub(/\\(.)/, '\1') if value.start_with?('"') [key, value] end @type = entry[/[^;]+/].delete(' ') @params = Hash[params] end def accepts?(entry) File.fnmatch(entry, self) && matches_params?(entry.params) end def to_str @type end def matches_params?(params) return true if @params.empty? params.all? { |k,v| [email protected]_key?(k) || @params[k] == v } end end end # The response object. See Rack::Response and Rack::Response::Helpers for # more info: # http://rubydoc.info/github/rack/rack/master/Rack/Response # http://rubydoc.info/github/rack/rack/master/Rack/Response/Helpers class Response < Rack::Response DROP_BODY_RESPONSES = [204, 304] def body=(value) value = value.body while Rack::Response === value @body = String === value ? [value.to_str] : value end def each block_given? ? super : enum_for(:each) end def finish result = body if drop_content_info? headers.delete "Content-Length" headers.delete "Content-Type" end if drop_body? close result = [] end if calculate_content_length? # if some other code has already set Content-Length, don't muck with it # currently, this would be the static file-handler headers["Content-Length"] = body.map(&:bytesize).reduce(0, :+).to_s end [status.to_i, headers, result] end private def calculate_content_length? headers["Content-Type"] and not headers["Content-Length"] and Array === body end def drop_content_info? status.to_i / 100 == 1 or drop_body? end def drop_body? DROP_BODY_RESPONSES.include?(status.to_i) end end # Some Rack handlers (Rainbows!) implement an extended body object protocol, however, # some middleware (namely Rack::Lint) will break it by not mirroring the methods in question. # This middleware will detect an extended body object and will make sure it reaches the # handler directly. We do this here, so our middleware and middleware set up by the app will # still be able to run. class ExtendedRack < Struct.new(:app) def call(env) result, callback = app.call(env), env['async.callback'] return result unless callback and async?(*result) after_response { callback.call result } setup_close(env, *result) throw :async end private def setup_close(env, status, headers, body) return unless body.respond_to? :close and env.include? 'async.close' env['async.close'].callback { body.close } env['async.close'].errback { body.close } end def after_response(&block) raise NotImplementedError, "only supports EventMachine at the moment" unless defined? EventMachine EventMachine.next_tick(&block) end def async?(status, headers, body) return true if status == -1 body.respond_to? :callback and body.respond_to? :errback end end # Behaves exactly like Rack::CommonLogger with the notable exception that it does nothing, # if another CommonLogger is already in the middleware chain. class CommonLogger < Rack::CommonLogger def call(env) env['sinatra.commonlogger'] ? @app.call(env) : super end superclass.class_eval do alias call_without_check call unless method_defined? :call_without_check def call(env) env['sinatra.commonlogger'] = true call_without_check(env) end end end class BadRequest < TypeError #:nodoc: def http_status; 400 end end class NotFound < NameError #:nodoc: def http_status; 404 end end # Methods available to routes, before/after filters, and views. module Helpers # Set or retrieve the response status code. def status(value = nil) response.status = Rack::Utils.status_code(value) if value response.status end # Set or retrieve the response body. When a block is given, # evaluation is deferred until the body is read with #each. def body(value = nil, &block) if block_given? def block.each; yield(call) end response.body = block elsif value # Rack 2.0 returns a Rack::File::Iterator here instead of # Rack::File as it was in the previous API. unless request.head? || value.is_a?(Rack::File::Iterator) || value.is_a?(Stream) headers.delete 'Content-Length' end response.body = value else response.body end end # Halt processing and redirect to the URI provided. def redirect(uri, *args) if env['HTTP_VERSION'] == 'HTTP/1.1' and env["REQUEST_METHOD"] != 'GET' status 303 else status 302 end # According to RFC 2616 section 14.30, "the field value consists of a # single absolute URI" response['Location'] = uri(uri.to_s, settings.absolute_redirects?, settings.prefixed_redirects?) halt(*args) end # Generates the absolute URI for a given path in the app. # Takes Rack routers and reverse proxies into account. def uri(addr = nil, absolute = true, add_script_name = true) return addr if addr =~ /\A[a-z][a-z0-9\+\.\-]*:/i uri = [host = String.new] if absolute host << "http#{'s' if request.secure?}://" if request.forwarded? or request.port != (request.secure? ? 443 : 80) host << request.host_with_port else host << request.host end end uri << request.script_name.to_s if add_script_name uri << (addr ? addr : request.path_info).to_s File.join uri end alias url uri alias to uri # Halt processing and return the error status provided. def error(code, body = nil) code, body = 500, code.to_str if code.respond_to? :to_str response.body = body unless body.nil? halt code end # Halt processing and return a 404 Not Found. def not_found(body = nil) error 404, body end # Set multiple response headers with Hash. def headers(hash = nil) response.headers.merge! hash if hash response.headers end # Access the underlying Rack session. def session request.session end # Access shared logger object. def logger request.logger end # Look up a media type by file extension in Rack's mime registry. def mime_type(type) Base.mime_type(type) end # Set the Content-Type of the response body given a media type or file # extension. def content_type(type = nil, params = {}) return response['Content-Type'] unless type default = params.delete :default mime_type = mime_type(type) || default fail "Unknown media type: %p" % type if mime_type.nil? mime_type = mime_type.dup unless params.include? :charset or settings.add_charset.all? { |p| not p === mime_type } params[:charset] = params.delete('charset') || settings.default_encoding end params.delete :charset if mime_type.include? 'charset' unless params.empty? mime_type << (mime_type.include?(';') ? ', ' : ';') mime_type << params.map do |key, val| val = val.inspect if val =~ /[";,]/ "#{key}=#{val}" end.join(', ') end response['Content-Type'] = mime_type end # Set the Content-Disposition to "attachment" with the specified filename, # instructing the user agents to prompt to save. def attachment(filename = nil, disposition = :attachment) response['Content-Disposition'] = disposition.to_s.dup if filename params = '; filename="%s"' % File.basename(filename) response['Content-Disposition'] << params ext = File.extname(filename) content_type(ext) unless response['Content-Type'] or ext.empty? end end # Use the contents of the file at +path+ as the response body. def send_file(path, opts = {}) if opts[:type] or not response['Content-Type'] content_type opts[:type] || File.extname(path), :default => 'application/octet-stream' end disposition = opts[:disposition] filename = opts[:filename] disposition = :attachment if disposition.nil? and filename filename = path if filename.nil? attachment(filename, disposition) if disposition last_modified opts[:last_modified] if opts[:last_modified] file = Rack::File.new(File.dirname(settings.app_file)) result = file.serving(request, path) result[1].each { |k,v| headers[k] ||= v } headers['Content-Length'] = result[1]['Content-Length'] opts[:status] &&= Integer(opts[:status]) halt (opts[:status] || result[0]), result[2] rescue Errno::ENOENT not_found end # Class of the response body in case you use #stream. # # Three things really matter: The front and back block (back being the # block generating content, front the one sending it to the client) and # the scheduler, integrating with whatever concurrency feature the Rack # handler is using. # # Scheduler has to respond to defer and schedule. class Stream def self.schedule(*) yield end def self.defer(*) yield end def initialize(scheduler = self.class, keep_open = false, &back) @back, @scheduler, @keep_open = back.to_proc, scheduler, keep_open @callbacks, @closed = [], false end def close return if closed? @closed = true @scheduler.schedule { @callbacks.each { |c| c.call } } end def each(&front) @front = front @scheduler.defer do begin @back.call(self) rescue Exception => e @scheduler.schedule { raise e } end close unless @keep_open end end def <<(data) @scheduler.schedule { @front.call(data.to_s) } self end def callback(&block) return yield if closed? @callbacks << block end alias errback callback def closed? @closed end end # Allows to start sending data to the client even though later parts of # the response body have not yet been generated. # # The close parameter specifies whether Stream#close should be called # after the block has been executed. This is only relevant for evented # servers like Rainbows. def stream(keep_open = false) scheduler = env['async.callback'] ? EventMachine : Stream current = @params.dup body Stream.new(scheduler, keep_open) { |out| with_params(current) { yield(out) } } end # Specify response freshness policy for HTTP caches (Cache-Control header). # Any number of non-value directives (:public, :private, :no_cache, # :no_store, :must_revalidate, :proxy_revalidate) may be passed along with # a Hash of value directives (:max_age, :s_maxage). # # cache_control :public, :must_revalidate, :max_age => 60 # => Cache-Control: public, must-revalidate, max-age=60 # # See RFC 2616 / 14.9 for more on standard cache control directives: # http://tools.ietf.org/html/rfc2616#section-14.9.1 def cache_control(*values) if values.last.kind_of?(Hash) hash = values.pop hash.reject! { |k, v| v == false } hash.reject! { |k, v| values << k if v == true } else hash = {} end values.map! { |value| value.to_s.tr('_','-') } hash.each do |key, value| key = key.to_s.tr('_', '-') value = value.to_i if ['max-age', 's-maxage'].include? key values << "#{key}=#{value}" end response['Cache-Control'] = values.join(', ') if values.any? end # Set the Expires header and Cache-Control/max-age directive. Amount # can be an integer number of seconds in the future or a Time object # indicating when the response should be considered "stale". The remaining # "values" arguments are passed to the #cache_control helper: # # expires 500, :public, :must_revalidate # => Cache-Control: public, must-revalidate, max-age=500 # => Expires: Mon, 08 Jun 2009 08:50:17 GMT # def expires(amount, *values) values << {} unless values.last.kind_of?(Hash) if amount.is_a? Integer time = Time.now + amount.to_i max_age = amount else time = time_for amount max_age = time - Time.now end values.last.merge!(:max_age => max_age) cache_control(*values) response['Expires'] = time.httpdate end # Set the last modified time of the resource (HTTP 'Last-Modified' header) # and halt if conditional GET matches. The +time+ argument is a Time, # DateTime, or other object that responds to +to_time+. # # When the current request includes an 'If-Modified-Since' header that is # equal or later than the time specified, execution is immediately halted # with a '304 Not Modified' response. def last_modified(time) return unless time time = time_for time response['Last-Modified'] = time.httpdate return if env['HTTP_IF_NONE_MATCH'] if status == 200 and env['HTTP_IF_MODIFIED_SINCE'] # compare based on seconds since epoch since = Time.httpdate(env['HTTP_IF_MODIFIED_SINCE']).to_i halt 304 if since >= time.to_i end if (success? or status == 412) and env['HTTP_IF_UNMODIFIED_SINCE'] # compare based on seconds since epoch since = Time.httpdate(env['HTTP_IF_UNMODIFIED_SINCE']).to_i halt 412 if since < time.to_i end rescue ArgumentError end ETAG_KINDS = [:strong, :weak] # Set the response entity tag (HTTP 'ETag' header) and halt if conditional # GET matches. The +value+ argument is an identifier that uniquely # identifies the current version of the resource. The +kind+ argument # indicates whether the etag should be used as a :strong (default) or :weak # cache validator. # # When the current request includes an 'If-None-Match' header with a # matching etag, execution is immediately halted. If the request method is # GET or HEAD, a '304 Not Modified' response is sent. def etag(value, options = {}) # Before touching this code, please double check RFC 2616 14.24 and 14.26. options = {:kind => options} unless Hash === options kind = options[:kind] || :strong new_resource = options.fetch(:new_resource) { request.post? } unless ETAG_KINDS.include?(kind) raise ArgumentError, ":strong or :weak expected" end value = '"%s"' % value value = "W/#{value}" if kind == :weak response['ETag'] = value if success? or status == 304 if etag_matches? env['HTTP_IF_NONE_MATCH'], new_resource halt(request.safe? ? 304 : 412) end if env['HTTP_IF_MATCH'] halt 412 unless etag_matches? env['HTTP_IF_MATCH'], new_resource end end end # Sugar for redirect (example: redirect back) def back request.referer end # whether or not the status is set to 1xx def informational? status.between? 100, 199 end # whether or not the status is set to 2xx def success? status.between? 200, 299 end # whether or not the status is set to 3xx def redirect? status.between? 300, 399 end # whether or not the status is set to 4xx def client_error? status.between? 400, 499 end # whether or not the status is set to 5xx def server_error? status.between? 500, 599 end # whether or not the status is set to 404 def not_found? status == 404 end # whether or not the status is set to 400 def bad_request? status == 400 end # Generates a Time object from the given value. # Used by #expires and #last_modified. def time_for(value) if value.is_a? Numeric Time.at value elsif value.respond_to? :to_s Time.parse value.to_s else value.to_time end rescue ArgumentError => boom raise boom rescue Exception raise ArgumentError, "unable to convert #{value.inspect} to a Time object" end private # Helper method checking if a ETag value list includes the current ETag. def etag_matches?(list, new_resource = request.post?) return !new_resource if list == '*' list.to_s.split(/\s*,\s*/).include? response['ETag'] end def with_params(temp_params) original, @params = @params, temp_params yield ensure @params = original if original end end # Template rendering methods. Each method takes the name of a template # to render as a Symbol and returns a String with the rendered output, # as well as an optional hash with additional options. # # `template` is either the name or path of the template as symbol # (Use `:'subdir/myview'` for views in subdirectories), or a string # that will be rendered. # # Possible options are: # :content_type The content type to use, same arguments as content_type. # :layout If set to something falsy, no layout is rendered, otherwise # the specified layout is used (Ignored for `sass` and `less`) # :layout_engine Engine to use for rendering the layout. # :locals A hash with local variables that should be available # in the template # :scope If set, template is evaluate with the binding of the given # object rather than the application instance. # :views Views directory to use. module Templates module ContentTyped attr_accessor :content_type end def initialize super @default_layout = :layout @preferred_extension = nil end def erb(template, options = {}, locals = {}, &block) render(:erb, template, options, locals, &block) end def erubis(template, options = {}, locals = {}) warn "Sinatra::Templates#erubis is deprecated and will be removed, use #erb instead.\n" \ "If you have Erubis installed, it will be used automatically." render :erubis, template, options, locals end def haml(template, options = {}, locals = {}, &block) render(:haml, template, options, locals, &block) end def sass(template, options = {}, locals = {}) options.merge! :layout => false, :default_content_type => :css render :sass, template, options, locals end def scss(template, options = {}, locals = {}) options.merge! :layout => false, :default_content_type => :css render :scss, template, options, locals end def less(template, options = {}, locals = {}) options.merge! :layout => false, :default_content_type => :css render :less, template, options, locals end def stylus(template, options = {}, locals = {}) options.merge! :layout => false, :default_content_type => :css render :styl, template, options, locals end def builder(template = nil, options = {}, locals = {}, &block) options[:default_content_type] = :xml render_ruby(:builder, template, options, locals, &block) end def liquid(template, options = {}, locals = {}, &block) render(:liquid, template, options, locals, &block) end def markdown(template, options = {}, locals = {}) options[:exclude_outvar] = true render :markdown, template, options, locals end def textile(template, options = {}, locals = {}) render :textile, template, options, locals end def rdoc(template, options = {}, locals = {}) render :rdoc, template, options, locals end def asciidoc(template, options = {}, locals = {}) render :asciidoc, template, options, locals end def radius(template, options = {}, locals = {}) render :radius, template, options, locals end def markaby(template = nil, options = {}, locals = {}, &block) render_ruby(:mab, template, options, locals, &block) end def coffee(template, options = {}, locals = {}) options.merge! :layout => false, :default_content_type => :js render :coffee, template, options, locals end def nokogiri(template = nil, options = {}, locals = {}, &block) options[:default_content_type] = :xml render_ruby(:nokogiri, template, options, locals, &block) end def slim(template, options = {}, locals = {}, &block) render(:slim, template, options, locals, &block) end def creole(template, options = {}, locals = {}) render :creole, template, options, locals end def mediawiki(template, options = {}, locals = {}) render :mediawiki, template, options, locals end def wlang(template, options = {}, locals = {}, &block) render(:wlang, template, options, locals, &block) end def yajl(template, options = {}, locals = {}) options[:default_content_type] = :json render :yajl, template, options, locals end def rabl(template, options = {}, locals = {}) Rabl.register! render :rabl, template, options, locals end # Calls the given block for every possible template file in views, # named name.ext, where ext is registered on engine. def find_template(views, name, engine) yield ::File.join(views, "#{name}.#{@preferred_extension}") Tilt.default_mapping.extensions_for(engine).each do |ext| yield ::File.join(views, "#{name}.#{ext}") unless ext == @preferred_extension end end private # logic shared between builder and nokogiri def render_ruby(engine, template, options = {}, locals = {}, &block) options, template = template, nil if template.is_a?(Hash) template = Proc.new { block } if template.nil? render engine, template, options, locals end def render(engine, data, options = {}, locals = {}, &block) # merge app-level options engine_options = settings.respond_to?(engine) ? settings.send(engine) : {} options.merge!(engine_options) { |key, v1, v2| v1 } # extract generic options locals = options.delete(:locals) || locals || {} views = options.delete(:views) || settings.views || "./views" layout = options[:layout] layout = false if layout.nil? && options.include?(:layout) eat_errors = layout.nil? layout = engine_options[:layout] if layout.nil? or (layout == true && engine_options[:layout] != false) layout = @default_layout if layout.nil? or layout == true layout_options = options.delete(:layout_options) || {} content_type = options.delete(:default_content_type) content_type = options.delete(:content_type) || content_type layout_engine = options.delete(:layout_engine) || engine scope = options.delete(:scope) || self exclude_outvar = options.delete(:exclude_outvar) options.delete(:layout) # set some defaults options[:outvar] ||= '@_out_buf' unless exclude_outvar options[:default_encoding] ||= settings.default_encoding # compile and render template begin layout_was = @default_layout @default_layout = false template = compile_template(engine, data, options, views) output = template.render(scope, locals, &block) ensure @default_layout = layout_was end # render layout if layout options = options.merge(:views => views, :layout => false, :eat_errors => eat_errors, :scope => scope). merge!(layout_options) catch(:layout_missing) { return render(layout_engine, layout, options, locals) { output } } end output.extend(ContentTyped).content_type = content_type if content_type output end def compile_template(engine, data, options, views) eat_errors = options.delete :eat_errors template_cache.fetch engine, data, options, views do template = Tilt[engine] raise "Template engine not found: #{engine}" if template.nil? case data when Symbol body, path, line = settings.templates[data] if body body = body.call if body.respond_to?(:call) template.new(path, line.to_i, options) { body } else found = false @preferred_extension = engine.to_s find_template(views, data, template) do |file| path ||= file # keep the initial path rather than the last one if found = File.exist?(file) path = file break end end throw :layout_missing if eat_errors and not found template.new(path, 1, options) end when Proc, String body = data.is_a?(String) ? Proc.new { data } : data caller = settings.caller_locations.first path = options[:path] || caller[0] line = options[:line] || caller[1] template.new(path, line.to_i, options, &body) else raise ArgumentError, "Sorry, don't know how to render #{data.inspect}." end end end end # Base class for all Sinatra applications and middleware. class Base include Rack::Utils include Helpers include Templates URI_INSTANCE = URI::Parser.new attr_accessor :app, :env, :request, :response, :params attr_reader :template_cache def initialize(app = nil) super() @app = app @template_cache = Tilt::Cache.new @pinned_response = nil # whether a before! filter pinned the content-type yield self if block_given? end # Rack call interface. def call(env) dup.call!(env) end def call!(env) # :nodoc: @env = env @params = IndifferentHash.new @request = Request.new(env) @response = Response.new template_cache.clear if settings.reload_templates invoke { dispatch! } invoke { error_block!(response.status) } unless @env['sinatra.error'] unless @response['Content-Type'] if Array === body && body[0].respond_to?(:content_type) content_type body[0].content_type elsif default = settings.default_content_type content_type default end end @response.finish end # Access settings defined with Base.set. def self.settings self end # Access settings defined with Base.set. def settings self.class.settings end def options warn "Sinatra::Base#options is deprecated and will be removed, " \ "use #settings instead." settings end # Exit the current block, halts any further processing # of the request, and returns the specified response. def halt(*response) response = response.first if response.length == 1 throw :halt, response end # Pass control to the next matching route. # If there are no more matching routes, Sinatra will # return a 404 response. def pass(&block) throw :pass, block end # Forward the request to the downstream app -- middleware only. def forward fail "downstream app not set" unless @app.respond_to? :call status, headers, body = @app.call env @response.status = status @response.body = body @response.headers.merge! headers nil end private # Run filters defined on the class and all superclasses. # Accepts an optional block to call after each filter is applied. def filter!(type, base = settings) filter! type, base.superclass if base.superclass.respond_to?(:filters) base.filters[type].each do |args| result = process_route(*args) yield result if block_given? end end # Run routes defined on the class and all superclasses. def route!(base = settings, pass_block = nil) if routes = base.routes[@request.request_method] routes.each do |pattern, conditions, block| @response.delete_header('Content-Type') unless @pinned_response returned_pass_block = process_route(pattern, conditions) do |*args| env['sinatra.route'] = "#{@request.request_method} #{pattern}" route_eval { block[*args] } end # don't wipe out pass_block in superclass pass_block = returned_pass_block if returned_pass_block end end # Run routes defined in superclass. if base.superclass.respond_to?(:routes) return route!(base.superclass, pass_block) end route_eval(&pass_block) if pass_block route_missing end # Run a route block and throw :halt with the result. def route_eval throw :halt, yield end # If the current request matches pattern and conditions, fill params # with keys and call the given block. # Revert params afterwards. # # Returns pass block. def process_route(pattern, conditions, block = nil, values = []) route = @request.path_info route = '/' if route.empty? and not settings.empty_path_info? route = route[0..-2] if !settings.strict_paths? && route != '/' && route.end_with?('/') return unless params = pattern.params(route) params.delete("ignore") # TODO: better params handling, maybe turn it into "smart" object or detect changes force_encoding(params) @params = @params.merge(params) if params.any? regexp_exists = pattern.is_a?(Mustermann::Regular) || (pattern.respond_to?(:patterns) && pattern.patterns.any? {|subpattern| subpattern.is_a?(Mustermann::Regular)} ) if regexp_exists captures = pattern.match(route).captures.map { |c| URI_INSTANCE.unescape(c) if c } values += captures @params[:captures] = force_encoding(captures) unless captures.nil? || captures.empty? else values += params.values.flatten end catch(:pass) do conditions.each { |c| throw :pass if c.bind(self).call == false } block ? block[self, values] : yield(self, values) end rescue @env['sinatra.error.params'] = @params raise ensure params ||= {} params.each { |k, _| @params.delete(k) } unless @env['sinatra.error.params'] end # No matching route was found or all routes passed. The default # implementation is to forward the request downstream when running # as middleware (@app is non-nil); when no downstream app is set, raise # a NotFound exception. Subclasses can override this method to perform # custom route miss logic. def route_missing if @app forward else raise NotFound, "#{request.request_method} #{request.path_info}" end end # Attempt to serve static files from public directory. Throws :halt when # a matching file is found, returns nil otherwise. def static!(options = {}) return if (public_dir = settings.public_folder).nil? path = "#{public_dir}#{URI_INSTANCE.unescape(request.path_info)}" return unless valid_path?(path) path = File.expand_path(path) return unless File.file?(path) env['sinatra.static_file'] = path cache_control(*settings.static_cache_control) if settings.static_cache_control? send_file path, options.merge(:disposition => nil) end # Run the block with 'throw :halt' support and apply result to the response. def invoke res = catch(:halt) { yield } res = [res] if Integer === res or String === res if Array === res and Integer === res.first res = res.dup status(res.shift) body(res.pop) headers(*res) elsif res.respond_to? :each body res end nil # avoid double setting the same response tuple twice end # Dispatch a request with error handling. def dispatch! # Avoid passing frozen string in force_encoding @params.merge!(@request.params).each do |key, val| next unless val.respond_to?(:force_encoding) val = val.dup if val.frozen? @params[key] = force_encoding(val) end invoke do static! if settings.static? && (request.get? || request.head?) filter! :before do @pinned_response = !@response['Content-Type'].nil? end route! end rescue ::Exception => boom invoke { handle_exception!(boom) } ensure begin filter! :after unless env['sinatra.static_file'] rescue ::Exception => boom invoke { handle_exception!(boom) } unless @env['sinatra.error'] end end # Error handling during requests. def handle_exception!(boom) if error_params = @env['sinatra.error.params'] @params = @params.merge(error_params) end @env['sinatra.error'] = boom if boom.respond_to? :http_status status(boom.http_status) elsif settings.use_code? and boom.respond_to? :code and boom.code.between? 400, 599 status(boom.code) else status(500) end status(500) unless status.between? 400, 599 if server_error? dump_errors! boom if settings.dump_errors? raise boom if settings.show_exceptions? and settings.show_exceptions != :after_handler elsif not_found? headers['X-Cascade'] = 'pass' if settings.x_cascade? end if res = error_block!(boom.class, boom) || error_block!(status, boom) return res end if not_found? || bad_request? if boom.message && boom.message != boom.class.name body boom.message else content_type 'text/html' body '<h1>' + (not_found? ? 'Not Found' : 'Bad Request') + '</h1>' end end return unless server_error? raise boom if settings.raise_errors? or settings.show_exceptions? error_block! Exception, boom end # Find an custom error block for the key(s) specified. def error_block!(key, *block_params) base = settings while base.respond_to?(:errors) next base = base.superclass unless args_array = base.errors[key] args_array.reverse_each do |args| first = args == args_array.first args += [block_params] resp = process_route(*args) return resp unless resp.nil? && !first end end return false unless key.respond_to? :superclass and key.superclass < Exception error_block!(key.superclass, *block_params) end def dump_errors!(boom) msg = ["#{Time.now.strftime("%Y-%m-%d %H:%M:%S")} - #{boom.class} - #{boom.message}:", *boom.backtrace].join("\n\t") @env['rack.errors'].puts(msg) end class << self CALLERS_TO_IGNORE = [ # :nodoc: /\/sinatra(\/(base|main|show_exceptions))?\.rb$/, # all sinatra code /lib\/tilt.*\.rb$/, # all tilt code /^\(.*\)$/, # generated code /rubygems\/(custom|core_ext\/kernel)_require\.rb$/, # rubygems require hacks /active_support/, # active_support require hacks /bundler(\/(?:runtime|inline))?\.rb/, # bundler require hacks /<internal:/, # internal in ruby >= 1.9.2 /src\/kernel\/bootstrap\/[A-Z]/ # maglev kernel files ] # contrary to what the comment said previously, rubinius never supported this if defined?(RUBY_IGNORE_CALLERS) warn "RUBY_IGNORE_CALLERS is deprecated and will no longer be supported by Sinatra 2.0" CALLERS_TO_IGNORE.concat(RUBY_IGNORE_CALLERS) end attr_reader :routes, :filters, :templates, :errors # Removes all routes, filters, middleware and extension hooks from the # current class (not routes/filters/... defined by its superclass). def reset! @conditions = [] @routes = {} @filters = {:before => [], :after => []} @errors = {} @middleware = [] @prototype = nil @extensions = [] if superclass.respond_to?(:templates) @templates = Hash.new { |hash, key| superclass.templates[key] } else @templates = {} end end # Extension modules registered on this class and all superclasses. def extensions if superclass.respond_to?(:extensions) (@extensions + superclass.extensions).uniq else @extensions end end # Middleware used in this class and all superclasses. def middleware if superclass.respond_to?(:middleware) superclass.middleware + @middleware else @middleware end end # Sets an option to the given value. If the value is a proc, # the proc will be called every time the option is accessed. def set(option, value = (not_set = true), ignore_setter = false, &block) raise ArgumentError if block and !not_set value, not_set = block, false if block if not_set raise ArgumentError unless option.respond_to?(:each) option.each { |k,v| set(k, v) } return self end if respond_to?("#{option}=") and not ignore_setter return __send__("#{option}=", value) end setter = proc { |val| set option, val, true } getter = proc { value } case value when Proc getter = value when Symbol, Integer, FalseClass, TrueClass, NilClass getter = value.inspect when Hash setter = proc do |val| val = value.merge val if Hash === val set option, val, true end end define_singleton("#{option}=", setter) define_singleton(option, getter) define_singleton("#{option}?", "!!#{option}") unless method_defined? "#{option}?" self end # Same as calling `set :option, true` for each of the given options. def enable(*opts) opts.each { |key| set(key, true) } end # Same as calling `set :option, false` for each of the given options. def disable(*opts) opts.each { |key| set(key, false) } end # Define a custom error handler. Optionally takes either an Exception # class, or an HTTP status code to specify which errors should be # handled. def error(*codes, &block) args = compile! "ERROR", /.*/, block codes = codes.flat_map(&method(:Array)) codes << Exception if codes.empty? codes << Sinatra::NotFound if codes.include?(404) codes.each { |c| (@errors[c] ||= []) << args } end # Sugar for `error(404) { ... }` def not_found(&block) error(404, &block) end # Define a named template. The block must return the template source. def template(name, &block) filename, line = caller_locations.first templates[name] = [block, filename, line.to_i] end # Define the layout template. The block must return the template source. def layout(name = :layout, &block) template name, &block end # Load embedded templates from the file; uses the caller's __FILE__ # when no file is specified. def inline_templates=(file = nil) file = (file.nil? || file == true) ? (caller_files.first || File.expand_path($0)) : file begin io = ::IO.respond_to?(:binread) ? ::IO.binread(file) : ::IO.read(file) app, data = io.gsub("\r\n", "\n").split(/^__END__$/, 2) rescue Errno::ENOENT app, data = nil end if data if app and app =~ /([^\n]*\n)?#[^\n]*coding: *(\S+)/m encoding = $2 else encoding = settings.default_encoding end lines = app.count("\n") + 1 template = nil force_encoding data, encoding data.each_line do |line| lines += 1 if line =~ /^@@\s*(.*\S)\s*$/ template = force_encoding(String.new, encoding) templates[$1.to_sym] = [template, file, lines] elsif template template << line end end end end # Lookup or register a mime type in Rack's mime registry. def mime_type(type, value = nil) return type if type.nil? return type.to_s if type.to_s.include?('/') type = ".#{type}" unless type.to_s[0] == ?. return Rack::Mime.mime_type(type, nil) unless value Rack::Mime::MIME_TYPES[type] = value end # provides all mime types matching type, including deprecated types: # mime_types :html # => ['text/html'] # mime_types :js # => ['application/javascript', 'text/javascript'] def mime_types(type) type = mime_type type type =~ /^application\/(xml|javascript)$/ ? [type, "text/#$1"] : [type] end # Define a before filter; runs before all requests within the same # context as route handlers and may access/modify the request and # response. def before(path = /.*/, **options, &block) add_filter(:before, path, **options, &block) end # Define an after filter; runs after all requests within the same # context as route handlers and may access/modify the request and # response. def after(path = /.*/, **options, &block) add_filter(:after, path, **options, &block) end # add a filter def add_filter(type, path = /.*/, **options, &block) filters[type] << compile!(type, path, block, **options) end # Add a route condition. The route is considered non-matching when the # block returns false. def condition(name = "#{caller.first[/`.*'/]} condition", &block) @conditions << generate_method(name, &block) end def public=(value) warn ":public is no longer used to avoid overloading Module#public, use :public_folder or :public_dir instead" set(:public_folder, value) end def public_dir=(value) self.public_folder = value end def public_dir public_folder end # Defining a `GET` handler also automatically defines # a `HEAD` handler. def get(path, opts = {}, &block) conditions = @conditions.dup route('GET', path, opts, &block) @conditions = conditions route('HEAD', path, opts, &block) end def put(path, opts = {}, &bk) route 'PUT', path, opts, &bk end def post(path, opts = {}, &bk) route 'POST', path, opts, &bk end def delete(path, opts = {}, &bk) route 'DELETE', path, opts, &bk end def head(path, opts = {}, &bk) route 'HEAD', path, opts, &bk end def options(path, opts = {}, &bk) route 'OPTIONS', path, opts, &bk end def patch(path, opts = {}, &bk) route 'PATCH', path, opts, &bk end def link(path, opts = {}, &bk) route 'LINK', path, opts, &bk end def unlink(path, opts = {}, &bk) route 'UNLINK', path, opts, &bk end # Makes the methods defined in the block and in the Modules given # in `extensions` available to the handlers and templates def helpers(*extensions, &block) class_eval(&block) if block_given? prepend(*extensions) if extensions.any? end # Register an extension. Alternatively take a block from which an # extension will be created and registered on the fly. def register(*extensions, &block) extensions << Module.new(&block) if block_given? @extensions += extensions extensions.each do |extension| extend extension extension.registered(self) if extension.respond_to?(:registered) end end def development?; environment == :development end def production?; environment == :production end def test?; environment == :test end # Set configuration options for Sinatra and/or the app. # Allows scoping of settings for certain environments. def configure(*envs) yield self if envs.empty? || envs.include?(environment.to_sym) end # Use the specified Rack middleware def use(middleware, *args, &block) @prototype = nil @middleware << [middleware, args, block] end # Stop the self-hosted server if running. def quit! return unless running? running_server.stop $stderr.puts "== Sinatra has ended his set (crowd applauds)" unless suppress_messages? set :running_server, nil set :handler_name, nil end alias_method :stop!, :quit! # Run the Sinatra app as a self-hosted server using # Puma, Mongrel, or WEBrick (in that order). If given a block, will call # with the constructed handler once we have taken the stage. def run!(options = {}, &block) return if running? set options handler = detect_rack_handler handler_name = handler.name.gsub(/.*::/, '') server_settings = settings.respond_to?(:server_settings) ? settings.server_settings : {} server_settings.merge!(:Port => port, :Host => bind) begin start_server(handler, server_settings, handler_name, &block) rescue Errno::EADDRINUSE $stderr.puts "== Someone is already performing on port #{port}!" raise ensure quit! end end alias_method :start!, :run! # Check whether the self-hosted server is running or not. def running? running_server? end # The prototype instance used to process requests. def prototype @prototype ||= new end # Create a new instance without middleware in front of it. alias new! new unless method_defined? :new! # Create a new instance of the class fronted by its middleware # pipeline. The object is guaranteed to respond to #call but may not be # an instance of the class new was called on. def new(*args, &bk) instance = new!(*args, &bk) Wrapper.new(build(instance).to_app, instance) end # Creates a Rack::Builder instance with all the middleware set up and # the given +app+ as end point. def build(app) builder = Rack::Builder.new setup_default_middleware builder setup_middleware builder builder.run app builder end def call(env) synchronize { prototype.call(env) } end # Like Kernel#caller but excluding certain magic entries and without # line / method information; the resulting array contains filenames only. def caller_files cleaned_caller(1).flatten end # Like caller_files, but containing Arrays rather than strings with the # first element being the file, and the second being the line. def caller_locations cleaned_caller 2 end private # Starts the server by running the Rack Handler. def start_server(handler, server_settings, handler_name) # Ensure we initialize middleware before startup, to match standard Rack # behavior, by ensuring an instance exists: prototype # Run the instance we created: handler.run(self, **server_settings) do |server| unless suppress_messages? $stderr.puts "== Sinatra (v#{Sinatra::VERSION}) has taken the stage on #{port} for #{environment} with backup from #{handler_name}" end setup_traps set :running_server, server set :handler_name, handler_name server.threaded = settings.threaded if server.respond_to? :threaded= yield server if block_given? end end def suppress_messages? handler_name =~ /cgi/i || quiet end def setup_traps if traps? at_exit { quit! } [:INT, :TERM].each do |signal| old_handler = trap(signal) do quit! old_handler.call if old_handler.respond_to?(:call) end end set :traps, false end end # Dynamically defines a method on settings. def define_singleton(name, content = Proc.new) singleton_class.class_eval do undef_method(name) if method_defined? name String === content ? class_eval("def #{name}() #{content}; end") : define_method(name, &content) end end # Condition for matching host name. Parameter might be String or Regexp. def host_name(pattern) condition { pattern === request.host } end # Condition for matching user agent. Parameter should be Regexp. # Will set params[:agent]. def user_agent(pattern) condition do if request.user_agent.to_s =~ pattern @params[:agent] = $~[1..-1] true else false end end end alias_method :agent, :user_agent # Condition for matching mimetypes. Accepts file extensions. def provides(*types) types.map! { |t| mime_types(t) } types.flatten! condition do if type = response['Content-Type'] types.include? type or types.include? type[/^[^;]+/] elsif type = request.preferred_type(types) params = (type.respond_to?(:params) ? type.params : {}) content_type(type, params) true else false end end end def route(verb, path, options = {}, &block) enable :empty_path_info if path == "" and empty_path_info.nil? signature = compile!(verb, path, block, **options) (@routes[verb] ||= []) << signature invoke_hook(:route_added, verb, path, block) signature end def invoke_hook(name, *args) extensions.each { |e| e.send(name, *args) if e.respond_to?(name) } end def generate_method(method_name, &block) define_method(method_name, &block) method = instance_method method_name remove_method method_name method end def compile!(verb, path, block, **options) # Because of self.options.host host_name(options.delete(:host)) if options.key?(:host) # Pass Mustermann opts to compile() route_mustermann_opts = options.key?(:mustermann_opts) ? options.delete(:mustermann_opts) : {}.freeze options.each_pair { |option, args| send(option, *args) } pattern = compile(path, route_mustermann_opts) method_name = "#{verb} #{path}" unbound_method = generate_method(method_name, &block) conditions, @conditions = @conditions, [] wrapper = block.arity != 0 ? proc { |a, p| unbound_method.bind(a).call(*p) } : proc { |a, p| unbound_method.bind(a).call } [ pattern, conditions, wrapper ] end def compile(path, route_mustermann_opts = {}) Mustermann.new(path, **mustermann_opts.merge(route_mustermann_opts)) end def setup_default_middleware(builder) builder.use ExtendedRack builder.use ShowExceptions if show_exceptions? builder.use Rack::MethodOverride if method_override? builder.use Rack::Head setup_logging builder setup_sessions builder setup_protection builder end def setup_middleware(builder) middleware.each { |c,a,b| builder.use(c, *a, &b) } end def setup_logging(builder) if logging? setup_common_logger(builder) setup_custom_logger(builder) elsif logging == false setup_null_logger(builder) end end def setup_null_logger(builder) builder.use Rack::NullLogger end def setup_common_logger(builder) builder.use Sinatra::CommonLogger end def setup_custom_logger(builder) if logging.respond_to? :to_int builder.use Rack::Logger, logging else builder.use Rack::Logger end end def setup_protection(builder) return unless protection? options = Hash === protection ? protection.dup : {} options = { img_src: "'self' data:", font_src: "'self'" }.merge options protect_session = options.fetch(:session) { sessions? } options[:without_session] = !protect_session options[:reaction] ||= :drop_session builder.use Rack::Protection, options end def setup_sessions(builder) return unless sessions? options = {} options[:secret] = session_secret if session_secret? options.merge! sessions.to_hash if sessions.respond_to? :to_hash builder.use session_store, options end def detect_rack_handler servers = Array(server) servers.each do |server_name| begin return Rack::Handler.get(server_name.to_s) rescue LoadError, NameError end end fail "Server handler (#{servers.join(',')}) not found." end def inherited(subclass) subclass.reset! subclass.set :app_file, caller_files.first unless subclass.app_file? super end @@mutex = Mutex.new def synchronize(&block) if lock? @@mutex.synchronize(&block) else yield end end # used for deprecation warnings def warn(message) super message + "\n\tfrom #{cleaned_caller.first.join(':')}" end # Like Kernel#caller but excluding certain magic entries def cleaned_caller(keep = 3) caller(1). map! { |line| line.split(/:(?=\d|in )/, 3)[0,keep] }. reject { |file, *_| CALLERS_TO_IGNORE.any? { |pattern| file =~ pattern } } end end # Force data to specified encoding. It defaults to settings.default_encoding # which is UTF-8 by default def self.force_encoding(data, encoding = default_encoding) return if data == settings || data.is_a?(Tempfile) if data.respond_to? :force_encoding data.force_encoding(encoding).encode! elsif data.respond_to? :each_value data.each_value { |v| force_encoding(v, encoding) } elsif data.respond_to? :each data.each { |v| force_encoding(v, encoding) } end data end def force_encoding(*args) settings.force_encoding(*args) end reset! set :environment, (ENV['APP_ENV'] || ENV['RACK_ENV'] || :development).to_sym set :raise_errors, Proc.new { test? } set :dump_errors, Proc.new { !test? } set :show_exceptions, Proc.new { development? } set :sessions, false set :session_store, Rack::Session::Cookie set :logging, false set :protection, true set :method_override, false set :use_code, false set :default_encoding, "utf-8" set :x_cascade, true set :add_charset, %w[javascript xml xhtml+xml].map { |t| "application/#{t}" } settings.add_charset << /^text\// set :mustermann_opts, {} set :default_content_type, 'text/html' # explicitly generating a session secret eagerly to play nice with preforking begin require 'securerandom' set :session_secret, SecureRandom.hex(64) rescue LoadError, NotImplementedError # SecureRandom raises a NotImplementedError if no random device is available set :session_secret, "%064x" % Kernel.rand(2**256-1) end class << self alias_method :methodoverride?, :method_override? alias_method :methodoverride=, :method_override= end set :run, false # start server via at-exit hook? set :running_server, nil set :handler_name, nil set :traps, true set :server, %w[HTTP webrick] set :bind, Proc.new { development? ? 'localhost' : '0.0.0.0' } set :port, Integer(ENV['PORT'] && !ENV['PORT'].empty? ? ENV['PORT'] : 4567) set :quiet, false ruby_engine = defined?(RUBY_ENGINE) && RUBY_ENGINE if ruby_engine == 'macruby' server.unshift 'control_tower' else server.unshift 'reel' server.unshift 'puma' server.unshift 'mongrel' if ruby_engine.nil? server.unshift 'trinidad' if ruby_engine == 'jruby' end set :absolute_redirects, true set :prefixed_redirects, false set :empty_path_info, nil set :strict_paths, true set :app_file, nil set :root, Proc.new { app_file && File.expand_path(File.dirname(app_file)) } set :views, Proc.new { root && File.join(root, 'views') } set :reload_templates, Proc.new { development? } set :lock, false set :threaded, true set :public_folder, Proc.new { root && File.join(root, 'public') } set :static, Proc.new { public_folder && File.exist?(public_folder) } set :static_cache_control, false error ::Exception do response.status = 500 content_type 'text/html' '<h1>Internal Server Error</h1>' end configure :development do get '/__sinatra__/:image.png' do filename = __dir__ + "/images/#{params[:image].to_i}.png" content_type :png send_file filename end error NotFound do content_type 'text/html' if self.class == Sinatra::Application code = <<-RUBY.gsub(/^ {12}/, '') #{request.request_method.downcase} '#{request.path_info}' do "Hello World" end RUBY else code = <<-RUBY.gsub(/^ {12}/, '') class #{self.class} #{request.request_method.downcase} '#{request.path_info}' do "Hello World" end end RUBY file = settings.app_file.to_s.sub(settings.root.to_s, '').sub(/^\//, '') code = "# in #{file}\n#{code}" unless file.empty? end (<<-HTML).gsub(/^ {10}/, '') <!DOCTYPE html> <html> <head> <style type="text/css"> body { text-align:center;font-family:helvetica,arial;font-size:22px; color:#888;margin:20px} #c {margin:0 auto;width:500px;text-align:left} </style> </head> <body> <h2>Sinatra doesn’t know this ditty.</h2> <img src='#{uri "/__sinatra__/404.png"}'> <div id="c"> Try this: <pre>#{Rack::Utils.escape_html(code)}</pre> </div> </body> </html> HTML end end end # Execution context for classic style (top-level) applications. All # DSL methods executed on main are delegated to this class. # # The Application class should not be subclassed, unless you want to # inherit all settings, routes, handlers, and error pages from the # top-level. Subclassing Sinatra::Base is highly recommended for # modular applications. class Application < Base set :logging, Proc.new { !test? } set :method_override, true set :run, Proc.new { !test? } set :app_file, nil def self.register(*extensions, &block) #:nodoc: added_methods = extensions.flat_map(&:public_instance_methods) Delegator.delegate(*added_methods) super(*extensions, &block) end end # Sinatra delegation mixin. Mixing this module into an object causes all # methods to be delegated to the Sinatra::Application class. Used primarily # at the top-level. module Delegator #:nodoc: def self.delegate(*methods) methods.each do |method_name| define_method(method_name) do |*args, &block| return super(*args, &block) if respond_to? method_name Delegator.target.send(method_name, *args, &block) end private method_name end end delegate :get, :patch, :put, :post, :delete, :head, :options, :link, :unlink, :template, :layout, :before, :after, :error, :not_found, :configure, :set, :mime_type, :enable, :disable, :use, :development?, :test?, :production?, :helpers, :settings, :register class << self attr_accessor :target end self.target = Application end class Wrapper def initialize(stack, instance) @stack, @instance = stack, instance end def settings @instance.settings end def helpers @instance end def call(env) @stack.call(env) end def inspect "#<#{@instance.class} app_file=#{settings.app_file.inspect}>" end end # Create a new Sinatra application; the block is evaluated in the class scope. def self.new(base = Base, &block) base = Class.new(base) base.class_eval(&block) if block_given? base end # Extend the top-level DSL with the modules provided. def self.register(*extensions, &block) Delegator.target.register(*extensions, &block) end # Include the helper modules provided in Sinatra's request context. def self.helpers(*extensions, &block) Delegator.target.helpers(*extensions, &block) end # Use the middleware for classic applications. def self.use(*args, &block) Delegator.target.use(*args, &block) end end
32.327885
171
0.611491
622749434972f0630d9f7c63285d8c7788b4caa3
468
require "rails_helper" RSpec.describe Integrated::ReviewTaxRelationshipsController do describe "#skip?" do context "when applicant is not filing taxes next year" do it "returns true" do application = create(:common_application, members: [create(:household_member, filing_taxes_next_year: "no")]) skip_step = Integrated::ReviewTaxRelationshipsController.skip?(application) expect(skip_step).to eq(true) end end end end
31.2
117
0.726496
1af9833d46f5543b1133b34e8ae6dbfe9d7be105
15,433
# frozen_string_literal: true require "active_support/inflections" module ActiveSupport # The Inflector transforms words from singular to plural, class names to table # names, modularized class names to ones without, and class names to foreign # keys. The default inflections for pluralization, singularization, and # uncountable words are kept in inflections.rb. # # The Rails core team has stated patches for the inflections library will not # be accepted in order to avoid breaking legacy applications which may be # relying on errant inflections. If you discover an incorrect inflection and # require it for your application or wish to define rules for languages other # than English, please correct or add them yourself (explained below). module Inflector extend self # Returns the plural form of the word in the string. # # If passed an optional +locale+ parameter, the word will be # pluralized using rules defined for that language. By default, # this parameter is set to <tt>:en</tt>. # # pluralize('post') # => "posts" # pluralize('octopus') # => "octopi" # pluralize('sheep') # => "sheep" # pluralize('words') # => "words" # pluralize('CamelOctopus') # => "CamelOctopi" # pluralize('ley', :es) # => "leyes" def pluralize(word, locale = :en) apply_inflections(word, inflections(locale).plurals, locale) end # The reverse of #pluralize, returns the singular form of a word in a # string. # # If passed an optional +locale+ parameter, the word will be # singularized using rules defined for that language. By default, # this parameter is set to <tt>:en</tt>. # # singularize('posts') # => "post" # singularize('octopi') # => "octopus" # singularize('sheep') # => "sheep" # singularize('word') # => "word" # singularize('CamelOctopi') # => "CamelOctopus" # singularize('leyes', :es) # => "ley" def singularize(word, locale = :en) apply_inflections(word, inflections(locale).singulars, locale) end # Converts strings to UpperCamelCase. # If the +uppercase_first_letter+ parameter is set to false, then produces # lowerCamelCase. # # Also converts '/' to '::' which is useful for converting # paths to namespaces. # # camelize('active_model') # => "ActiveModel" # camelize('active_model', false) # => "activeModel" # camelize('active_model/errors') # => "ActiveModel::Errors" # camelize('active_model/errors', false) # => "activeModel::Errors" # # As a rule of thumb you can think of +camelize+ as the inverse of # #underscore, though there are cases where that does not hold: # # camelize(underscore('SSLError')) # => "SslError" def camelize(term, uppercase_first_letter = true) string = term.to_s if uppercase_first_letter string = string.sub(/^[a-z\d]*/) { |match| inflections.acronyms[match] || match.capitalize } else string = string.sub(inflections.acronyms_camelize_regex) { |match| match.downcase } end string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" } string.gsub!("/", "::") string end # Makes an underscored, lowercase form from the expression in the string. # # Changes '::' to '/' to convert namespaces to paths. # # underscore('ActiveModel') # => "active_model" # underscore('ActiveModel::Errors') # => "active_model/errors" # # As a rule of thumb you can think of +underscore+ as the inverse of # #camelize, though there are cases where that does not hold: # # camelize(underscore('SSLError')) # => "SslError" def underscore(camel_cased_word) return camel_cased_word unless /[A-Z-]|::/.match?(camel_cased_word) word = camel_cased_word.to_s.gsub("::", "/") word.gsub!(inflections.acronyms_underscore_regex) { "#{$1 && '_' }#{$2.downcase}" } word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2') word.gsub!(/([a-z\d])([A-Z])/, '\1_\2') word.tr!("-", "_") word.downcase! word end # Tweaks an attribute name for display to end users. # # Specifically, performs these transformations: # # * Applies human inflection rules to the argument. # * Deletes leading underscores, if any. # * Removes a "_id" suffix if present. # * Replaces underscores with spaces, if any. # * Downcases all words except acronyms. # * Capitalizes the first word. # The capitalization of the first word can be turned off by setting the # +:capitalize+ option to false (default is true). # # The trailing '_id' can be kept and capitalized by setting the # optional parameter +keep_id_suffix+ to true (default is false). # # humanize('employee_salary') # => "Employee salary" # humanize('author_id') # => "Author" # humanize('author_id', capitalize: false) # => "author" # humanize('_id') # => "Id" # humanize('author_id', keep_id_suffix: true) # => "Author Id" # # If "SSL" was defined to be an acronym: # # humanize('ssl_error') # => "SSL error" # def humanize(lower_case_and_underscored_word, capitalize: true, keep_id_suffix: false) result = lower_case_and_underscored_word.to_s.dup inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) } result.sub!(/\A_+/, "") unless keep_id_suffix result.sub!(/_id\z/, "") end result.tr!("_", " ") result.gsub!(/([a-z\d]*)/i) do |match| "#{inflections.acronyms[match.downcase] || match.downcase}" end if capitalize result.sub!(/\A\w/) { |match| match.upcase } end result end # Converts just the first character to uppercase. # # upcase_first('what a Lovely Day') # => "What a Lovely Day" # upcase_first('w') # => "W" # upcase_first('') # => "" def upcase_first(string) string.length > 0 ? string[0].upcase.concat(string[1..-1]) : "" end # Capitalizes all the words and replaces some characters in the string to # create a nicer looking title. +titleize+ is meant for creating pretty # output. It is not used in the Rails internals. # # The trailing '_id','Id'.. can be kept and capitalized by setting the # optional parameter +keep_id_suffix+ to true. # By default, this parameter is false. # # +titleize+ is also aliased as +titlecase+. # # titleize('man from the boondocks') # => "Man From The Boondocks" # titleize('x-men: the last stand') # => "X Men: The Last Stand" # titleize('TheManWithoutAPast') # => "The Man Without A Past" # titleize('raiders_of_the_lost_ark') # => "Raiders Of The Lost Ark" # titleize('string_ending_with_id', keep_id_suffix: true) # => "String Ending With Id" def titleize(word, keep_id_suffix: false) humanize(underscore(word), keep_id_suffix: keep_id_suffix).gsub(/\b(?<!\w['’`])[a-z]/) do |match| match.capitalize end end # Creates the name of a table like Rails does for models to table names. # This method uses the #pluralize method on the last word in the string. # # tableize('RawScaledScorer') # => "raw_scaled_scorers" # tableize('ham_and_egg') # => "ham_and_eggs" # tableize('fancyCategory') # => "fancy_categories" def tableize(class_name) pluralize(underscore(class_name)) end # Creates a class name from a plural table name like Rails does for table # names to models. Note that this returns a string and not a Class (To # convert to an actual class follow +classify+ with #constantize). # # classify('ham_and_eggs') # => "HamAndEgg" # classify('posts') # => "Post" # # Singular names are not handled correctly: # # classify('calculus') # => "Calculus" def classify(table_name) # strip out any leading schema name camelize(singularize(table_name.to_s.sub(/.*\./, ""))) end # Replaces underscores with dashes in the string. # # dasherize('puni_puni') # => "puni-puni" def dasherize(underscored_word) underscored_word.tr("_", "-") end # Removes the module part from the expression in the string. # # demodulize('ActiveSupport::Inflector::Inflections') # => "Inflections" # demodulize('Inflections') # => "Inflections" # demodulize('::Inflections') # => "Inflections" # demodulize('') # => "" # # See also #deconstantize. def demodulize(path) path = path.to_s if i = path.rindex("::") path[(i + 2)..-1] else path end end # Removes the rightmost segment from the constant expression in the string. # # deconstantize('Net::HTTP') # => "Net" # deconstantize('::Net::HTTP') # => "::Net" # deconstantize('String') # => "" # deconstantize('::String') # => "" # deconstantize('') # => "" # # See also #demodulize. def deconstantize(path) path.to_s[0, path.rindex("::") || 0] # implementation based on the one in facets' Module#spacename end # Creates a foreign key name from a class name. # +separate_class_name_and_id_with_underscore+ sets whether # the method should put '_' between the name and 'id'. # # foreign_key('Message') # => "message_id" # foreign_key('Message', false) # => "messageid" # foreign_key('Admin::Post') # => "post_id" def foreign_key(class_name, separate_class_name_and_id_with_underscore = true) underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id") end # Tries to find a constant with the name specified in the argument string. # # constantize('Module') # => Module # constantize('Foo::Bar') # => Foo::Bar # # The name is assumed to be the one of a top-level constant, no matter # whether it starts with "::" or not. No lexical context is taken into # account: # # C = 'outside' # module M # C = 'inside' # C # => 'inside' # constantize('C') # => 'outside', same as ::C # end # # NameError is raised when the name is not in CamelCase or the constant is # unknown. def constantize(camel_cased_word) names = camel_cased_word.split("::") # Trigger a built-in NameError exception including the ill-formed constant in the message. Object.const_get(camel_cased_word) if names.empty? # Remove the first blank element in case of '::ClassName' notation. names.shift if names.size > 1 && names.first.empty? names.inject(Object) do |constant, name| if constant == Object constant.const_get(name) else candidate = constant.const_get(name) next candidate if constant.const_defined?(name, false) next candidate unless Object.const_defined?(name) # Go down the ancestors to check if it is owned directly. The check # stops when we reach Object or the end of ancestors tree. constant = constant.ancestors.inject(constant) do |const, ancestor| break const if ancestor == Object break ancestor if ancestor.const_defined?(name, false) const end # owner is in Object, so raise constant.const_get(name, false) end end end # Tries to find a constant with the name specified in the argument string. # # safe_constantize('Module') # => Module # safe_constantize('Foo::Bar') # => Foo::Bar # # The name is assumed to be the one of a top-level constant, no matter # whether it starts with "::" or not. No lexical context is taken into # account: # # C = 'outside' # module M # C = 'inside' # C # => 'inside' # safe_constantize('C') # => 'outside', same as ::C # end # # +nil+ is returned when the name is not in CamelCase or the constant (or # part of it) is unknown. # # safe_constantize('blargle') # => nil # safe_constantize('UnknownModule') # => nil # safe_constantize('UnknownModule::Foo::Bar') # => nil def safe_constantize(camel_cased_word) constantize(camel_cased_word) rescue NameError => e raise if e.name && !(camel_cased_word.to_s.split("::").include?(e.name.to_s) || e.name.to_s == camel_cased_word.to_s) rescue ArgumentError => e raise unless /not missing constant #{const_regexp(camel_cased_word)}!$/.match?(e.message) end # Returns the suffix that should be added to a number to denote the position # in an ordered sequence such as 1st, 2nd, 3rd, 4th. # # ordinal(1) # => "st" # ordinal(2) # => "nd" # ordinal(1002) # => "nd" # ordinal(1003) # => "rd" # ordinal(-11) # => "th" # ordinal(-1021) # => "st" def ordinal(number) I18n.translate("number.nth.ordinals", number: number) end # Turns a number into an ordinal string used to denote the position in an # ordered sequence such as 1st, 2nd, 3rd, 4th. # # ordinalize(1) # => "1st" # ordinalize(2) # => "2nd" # ordinalize(1002) # => "1002nd" # ordinalize(1003) # => "1003rd" # ordinalize(-11) # => "-11th" # ordinalize(-1021) # => "-1021st" def ordinalize(number) I18n.translate("number.nth.ordinalized", number: number) end private # Mounts a regular expression, returned as a string to ease interpolation, # that will match part by part the given constant. # # const_regexp("Foo::Bar::Baz") # => "Foo(::Bar(::Baz)?)?" # const_regexp("::") # => "::" def const_regexp(camel_cased_word) parts = camel_cased_word.split("::") return Regexp.escape(camel_cased_word) if parts.blank? last = parts.pop parts.reverse.inject(last) do |acc, part| part.empty? ? acc : "#{part}(::#{acc})?" end end # Applies inflection rules for +singularize+ and +pluralize+. # # If passed an optional +locale+ parameter, the uncountables will be # found for that locale. # # apply_inflections('post', inflections.plurals, :en) # => "posts" # apply_inflections('posts', inflections.singulars, :en) # => "post" def apply_inflections(word, rules, locale = :en) result = word.to_s.dup if word.empty? || inflections(locale).uncountables.uncountable?(result) result else rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) } result end end end end
38.874055
104
0.593987
1a7cfad3944d17b3a3d642dd6d7c9bccedcbf8b9
327
class Keka < Cask version '1.0.4' sha256 '0075741ed52e2c86d7749dfe2baf54c8b6dad75a780b4b51ca5fb14337124701' url 'http://www.kekaosx.com/release/Keka-1.0.4-intel.dmg' appcast 'http://update.kekaosx.com' homepage 'http://kekaosx.com/' app 'Keka.app' zap :delete => '~/Library/Preferences/com.aone.keka.plist' end
27.25
75
0.733945
79b3c3d91926d75a16df141aa71334fbe6260345
56
module SequelSchemaDotGenerator VERSION = '0.0.4' end
14
31
0.767857
acb9ba55c462de2284284e9609110cc36e874270
7,238
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. require 'date' require_relative 'detect_anomalies_details' # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # The request body when the user selects to provide byte data in detect call which is Base64 encoded. # The default type of the data is CSV and can be JSON by setting the 'contentType'. # class AiAnomalyDetection::Models::EmbeddedDetectAnomaliesRequest < AiAnomalyDetection::Models::DetectAnomaliesDetails CONTENT_TYPE_ENUM = [ CONTENT_TYPE_CSV = 'CSV'.freeze, CONTENT_TYPE_JSON = 'JSON'.freeze ].freeze # @return [String] attr_reader :content_type # This attribute is required. # @return [String] attr_accessor :content # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { # rubocop:disable Style/SymbolLiteral 'model_id': :'modelId', 'request_type': :'requestType', 'content_type': :'contentType', 'content': :'content' # rubocop:enable Style/SymbolLiteral } end # Attribute type mapping. def self.swagger_types { # rubocop:disable Style/SymbolLiteral 'model_id': :'String', 'request_type': :'String', 'content_type': :'String', 'content': :'String' # rubocop:enable Style/SymbolLiteral } end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # Initializes the object # @param [Hash] attributes Model attributes in the form of hash # @option attributes [String] :model_id The value to assign to the {OCI::AiAnomalyDetection::Models::DetectAnomaliesDetails#model_id #model_id} proprety # @option attributes [String] :content_type The value to assign to the {#content_type} property # @option attributes [String] :content The value to assign to the {#content} property def initialize(attributes = {}) return unless attributes.is_a?(Hash) attributes['requestType'] = 'BASE64_ENCODED' super(attributes) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } self.content_type = attributes[:'contentType'] if attributes[:'contentType'] self.content_type = "CSV" if content_type.nil? && !attributes.key?(:'contentType') # rubocop:disable Style/StringLiterals raise 'You cannot provide both :contentType and :content_type' if attributes.key?(:'contentType') && attributes.key?(:'content_type') self.content_type = attributes[:'content_type'] if attributes[:'content_type'] self.content_type = "CSV" if content_type.nil? && !attributes.key?(:'contentType') && !attributes.key?(:'content_type') # rubocop:disable Style/StringLiterals self.content = attributes[:'content'] if attributes[:'content'] end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # Custom attribute writer method checking allowed values (enum). # @param [Object] content_type Object to be assigned def content_type=(content_type) raise "Invalid value for 'content_type': this must be one of the values in CONTENT_TYPE_ENUM." if content_type && !CONTENT_TYPE_ENUM.include?(content_type) @content_type = content_type end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # Checks equality by comparing each attribute. # @param [Object] other the other object to be compared def ==(other) return true if equal?(other) self.class == other.class && model_id == other.model_id && request_type == other.request_type && content_type == other.content_type && content == other.content end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # @see the `==` method # @param [Object] other the other object to be compared def eql?(other) self == other end # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [model_id, request_type, content_type, content].hash end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) public_method("#{key}=").call( attributes[self.class.attribute_map[key]] .map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? public_method("#{key}=").call( OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]]) ) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = public_method(attr).call next if value.nil? && !instance_variable_defined?("@#{attr}") hash[param] = _to_hash(value) end hash end private # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end # rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
37.502591
245
0.679608
d58f2d3d0a376bea2236ce1a9ebd136470f00a42
1,844
# frozen_string_literal: true module Spree module OrderDecorator def self.prepended(base) base.has_many :bookkeeping_documents, as: :printable, dependent: :destroy base.has_one :invoice, -> { where(template: 'invoice') }, class_name: 'Spree::BookkeepingDocument', as: :printable base.has_one :packaging_slip, -> { where(template: 'packaging_slip') }, class_name: 'Spree::BookkeepingDocument', as: :printable base.delegate :number, :date, :order_date, to: :invoice, prefix: true # Create a new invoice before transitioning to complete # base.state_machine.before_transition to: :complete, do: :invoice_for_order end # Backwards compatibility stuff. Please don't use these methods, rather use the # ones on Spree::BookkeepingDocument # def pdf_file ActiveSupport::Deprecation.warn('This API has changed: Please use order.invoice.pdf instead') invoice.pdf end def pdf_filename ActiveSupport::Deprecation.warn('This API has changed: Please use order.invoice.file_name instead') invoice.file_name end def pdf_file_path ActiveSupport::Deprecation.warn('This API has changed: Please use order.invoice.pdf_file_path instead') invoice.pdf_file_path end def pdf_storage_path(template) ActiveSupport::Deprecation.warn('This API has changed: Please use order.{packaging_slip, invoice}.pdf_file_path instead') bookkeeping_documents.find_by!(template: template).file_path end def invoice_for_order bookkeeping_documents.create(template: 'invoice') bookkeeping_documents.create(template: 'packaging_slip') end def order_date completed_at end end end ::Spree::Order.prepend Spree::OrderDecorator
34.148148
127
0.694685
bb6bbd639fb56942b2782e4af3019e705f14e12d
2,105
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Appconfiguration::Mgmt::V2019_02_01_preview module Models # # The result of a request to check the availability of a resource name. # class NameAvailabilityStatus include MsRestAzure # @return [Boolean] The value indicating whether the resource name is # available. attr_accessor :name_available # @return [String] If any, the error message that provides more detail # for the reason that the name is not available. attr_accessor :message # @return [String] If any, the reason that the name is not available. attr_accessor :reason # # Mapper for NameAvailabilityStatus class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'NameAvailabilityStatus', type: { name: 'Composite', class_name: 'NameAvailabilityStatus', model_properties: { name_available: { client_side_validation: true, required: false, read_only: true, serialized_name: 'nameAvailable', type: { name: 'Boolean' } }, message: { client_side_validation: true, required: false, read_only: true, serialized_name: 'message', type: { name: 'String' } }, reason: { client_side_validation: true, required: false, read_only: true, serialized_name: 'reason', type: { name: 'String' } } } } } end end end end
28.445946
76
0.529216
6183fe0d3bece5a9e94acc116e3a53d69adaf91e
1,368
cask 'font-source-serif-pro' do version '2.007R-ro,1.007R-it' sha256 '46d9b5114e3e86b24769729e2fe09288b6a94c2d4f28a7e39ef572fbe2bec2da' # github.com/adobe-fonts/source-serif-pro was verified as official when first introduced to the cask url "https://github.com/adobe-fonts/source-serif-pro/archive/#{version.before_comma}/#{version.after_comma}.zip" appcast 'https://github.com/adobe-fonts/source-serif-pro/releases.atom' name 'Source Serif Pro' homepage 'https://adobe-fonts.github.io/source-serif-pro/' font 'source-serif-pro-2.007R-ro-1.007R-it/OTF/SourceSerifPro-Black.otf' font 'source-serif-pro-2.007R-ro-1.007R-it/OTF/SourceSerifPro-BlackIt.otf' font 'source-serif-pro-2.007R-ro-1.007R-it/OTF/SourceSerifPro-Bold.otf' font 'source-serif-pro-2.007R-ro-1.007R-it/OTF/SourceSerifPro-BoldIt.otf' font 'source-serif-pro-2.007R-ro-1.007R-it/OTF/SourceSerifPro-ExtraLight.otf' font 'source-serif-pro-2.007R-ro-1.007R-it/OTF/SourceSerifPro-ExtraLightIt.otf' font 'source-serif-pro-2.007R-ro-1.007R-it/OTF/SourceSerifPro-It.otf' font 'source-serif-pro-2.007R-ro-1.007R-it/OTF/SourceSerifPro-Light.otf' font 'source-serif-pro-2.007R-ro-1.007R-it/OTF/SourceSerifPro-LightIt.otf' font 'source-serif-pro-2.007R-ro-1.007R-it/OTF/SourceSerifPro-Regular.otf' font 'source-serif-pro-2.007R-ro-1.007R-it/OTF/SourceSerifPro-Semibold.otf' end
59.478261
114
0.769737
abb988896754cf694442c5cc9d5e457e9e672f16
192
require 'erb' module Booty class ERBTemplate def initialize(content) @content = content end def expand(binding) ERB.new(@content).result(binding) end end end
13.714286
39
0.651042
61bc6527819426ad6f9873f42bf6fa5083c63e07
1,521
class PasswordResetsController < ApplicationController before_action :get_user, only: [:edit, :update] before_action :valid_user, only: [:edit, :update] before_action :check_expiration, only: [:edit, :update] def new end def create @user = User.find_by(email: params[:password_reset][:email].downcase) if @user @user.create_reset_digest @user.send_password_reset_email flash[:info] = "Email sent with password reset instructions" redirect_to root_url else flash.now[:danger] = "Email address not found" render 'new' end end def edit end def update if params[:user][:password].empty? @user.errors.add(:password, "can't be empty") render 'edit' elsif @user.update_attributes(user_params) log_in @user @user.update_attribute(:reset_digest, nil) flash[:success] = "Password has been reset." redirect_to @user else render 'edit' end end private def user_params params.require(:user).permit(:password, :password_confirmation) end def get_user @user = User.find_by(email: params[:email]) end def valid_user unless (@user && @user.activated? && @user.authenticated?(:reset, params[:id])) redirect_to root_url end end def check_expiration if @user.password_reset_expired? flash[:danger] = "Password reset has expired." redirect_to new_password_reset_url end end end
23.765625
73
0.646285
5d5b2137c4a266277c4ea9f74508c8fa976cdf5e
892
module Validations class StatisticInfo include ActiveModel::Validations validate :query_key_format_must_be_correct def initialize(params = {}) @query_key = params[:id] end def error_object api_errors = [] if invalid? api_errors << Api::V1::Exceptions::StatisticInfoNameInvalidError.new if :query_key.in?(errors.keys) { status: api_errors.first.status, errors: RequestErrorSerializer.new(api_errors, message: api_errors.first.title) } end end private attr_accessor :query_key def query_key_format_must_be_correct if query_key.blank? || !valid_statistic_info_names.include?(query_key.to_sym) errors.add(:query_key, "statistic info name is invalid") end end def valid_statistic_info_names ::StatisticInfo.instance_methods(false) end end end
23.473684
107
0.681614
215798d33f3c408e604881f3a9c6c0b71c9ec095
1,282
require 'trundle' require 'digest' require 'active_support' require 'active_support/core_ext/string/inflections' module TextbundleTo class TextbundleExtend attr_accessor :title attr_accessor :tags attr_accessor :body attr_accessor :assets BEAR_CREATOR_IDENTIFIER = 'net.shinyfrog.bear' def initialize(textbundle_path:) @textbundle = Trundle.open(textbundle_path) @assets = @textbundle.assets.send(:assets).map { |a| OpenStruct.new(path: "assets/#{a[0]}", pathname: a[1], url: nil) } set_datas end def replace_assets_url @assets.each do |asset| @body.gsub!("(#{asset.path})", "(#{asset.url})") end end def permlink slug = @title.parameterize slug.empty? ? Digest::SHA256.hexdigest(Time.now.to_i.to_s)[0..6] : slug end private def set_datas lines = @textbundle.text.lines @title = lines.first[2..-1].rstrip if @textbundle.creator_identifier == BEAR_CREATOR_IDENTIFIER && tag_line?(lines[1]) @tags = lines[1].scan(/(?:\s|^)(?:#)([^\s]+)(?=\s|$)/i).map { |e| e[0] } @body = lines[2..-1].join else @body = lines[1..-1].join end end def tag_line?(line) line.start_with? '#' end end end
25.64
125
0.613105
0146af79fdf9aa041fbff542dc319ad37c558691
4,246
#-- encoding: UTF-8 #-- copyright # OpenProject is a project management system. # Copyright (C) 2012-2015 the OpenProject Foundation (OPF) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2013 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See doc/COPYRIGHT.rdoc for more details. #++ class RepairInvalidDefaultWorkPackageCustomValues < ActiveRecord::Migration def up unless custom_field_default_values.empty? create_missing_work_package_custom_values create_missing_work_package_customizable_journals end end def down end private def create_missing_work_package_custom_values missing_custom_values.each do |c| # Use execute instead of insert as Rails' Postgres adapter's insert fails when inserting # into tables ending in 'values'. # See https://community.openproject.org/work_packages/5033 execute <<-SQL INSERT INTO custom_values (customized_type, customized_id, custom_field_id, value) VALUES ('WorkPackage', '#{c['work_package_id']}', '#{c['custom_field_id']}', '#{custom_field_default_values[c['custom_field_id']]}') SQL end end def create_missing_work_package_customizable_journals affected_journals.each do |c| insert <<-SQL INSERT INTO customizable_journals (journal_id, custom_field_id, value) VALUES ('#{c['journal_id']}', '#{c['custom_field_id']}', '#{custom_field_default_values[c['custom_field_id']]}') SQL end end def create_missing_custom_value(_table, _customized_id, _custom_field_id) end def missing_custom_values @missing_custom_values ||= select_all <<-SQL SELECT cf.id AS custom_field_id, w.id AS work_package_id FROM custom_fields AS cf JOIN custom_fields_projects AS cfp ON (cf.id = cfp.custom_field_id) JOIN custom_fields_types AS cft ON (cf.id = cft.custom_field_id) JOIN work_packages AS w ON (w.project_id = cfp.project_id AND w.type_id = cft.type_id) LEFT JOIN custom_values AS cv ON (cv.customized_id = w.id AND cv.customized_type = 'WorkPackage' AND cv.custom_field_id = cf.id) WHERE cf.id IN (#{custom_field_default_values.keys.join(', ')}) AND cv.id IS NULL SQL end def custom_field_default_values @custom_field_default_values ||= CustomField.select { |c| !(c.default_value.blank?) } .each_with_object({}) { |c, h| h[c.id] = c.default_value unless h[c.id] } end def affected_journals @affected_journals ||= select_all <<-SQL SELECT j.id AS journal_id, cv.custom_field_id AS custom_field_id FROM journals AS j JOIN custom_values AS cv ON (j.journable_id = cv.customized_id AND j.journable_type = cv.customized_type) LEFT JOIN customizable_journals AS cj ON (j.id = cj.journal_id AND cv.custom_field_id = cj.custom_field_id) WHERE cv.custom_field_id IN (#{custom_field_default_values.keys.join(', ')}) AND cv.customized_type = 'WorkPackage' AND cj.id IS NULL SQL end end
39.682243
110
0.674753
1cd6e20e8b09f784ffa074555cfadcd6958d6d7b
3,321
require_relative '../../spec_helper' module Aws module Plugins describe EndpointPattern do let(:metadata) {{ 'apiVersion' => '2018-11-07', 'protocol' => 'rest-xml', 'endpointPrefix' => 'svc', 'signatureVersion' => 'v4' }} let(:operations) {{ 'Foo' => { 'name' => 'Foo', 'http' => { 'method' => 'POST', 'requestUri' => '/' }, 'input' => { 'shape' => 'FooInput'}, 'endpoint' => { 'hostPrefix' => 'fancy123-' } }, 'Bar' => { 'name' => 'Bar', 'http' => { 'method' => 'POST', 'requestUri' => '/' }, 'input' => { 'shape' => 'BarInput'}, 'endpoint' => { 'hostPrefix' => '{MemberA}-{MemberB}.' } } }} let(:shapes) {{ 'FooInput' => { 'type' => 'structure', 'members' => {} }, 'BarInput' => { 'required' => [ 'MemberA', 'MemberB' ], 'type' => 'structure', 'members' => { 'MemberA' => { 'shape' => 'String', 'hostLabel' => true }, 'MemberB' => { 'shape' => 'String', 'hostLabel' => true } } }, 'String' => { 'type' => 'string' } }} let(:api) { Aws::Api::Builder.build( 'metadata' => metadata, 'operations' => operations, 'shapes' => shapes ) } let(:svc) { Aws.add_service(:Svc, api: api)::Client } let(:creds) { Aws::Credentials.new('akid', 'secert') } before do Aws.send(:remove_const, :Svc) if Aws.const_defined?(:Svc) svc.add_plugin(EndpointPattern) end it 'does nothing when custom endpoint is provided' do c = svc.new(credentials: creds, endpoint: 'https://abc.com', region: 'us-west-2', stub_responses: true) resp = c.foo expect(resp.context.http_request.endpoint.host).to eq('abc.com') end it 'does nothing when :disable_host_prefix_injection is true' do c = svc.new(credentials: creds, region: 'us-west-2', stub_responses: true, disable_host_prefix_injection: true) resp = c.foo expect(resp.context.http_request.endpoint.host).to eq('svc.us-west-2.amazonaws.com') end it 'updates endpoint host according to host prefix' do c = svc.new(credentials: creds, region: 'us-west-2', stub_responses: true) resp = c.foo expect(resp.context.http_request.endpoint.host).to eq('fancy123-svc.us-west-2.amazonaws.com') end it 'raise an error if label value is not provided' do c = svc.new(credentials: creds, region: 'us-west-2', stub_responses: true, validate_params: false) expect { c.bar }.to raise_error(Aws::Errors::MissingEndpointHostLabelValue) end it 'updates endpoint host with label values' do c = svc.new(credentials: creds, region: 'us-west-2', stub_responses: true) resp = c.bar(member_a: 'hello', member_b: 'world') expect(resp.context.http_request.endpoint.host).to eq('hello-world.svc.us-west-2.amazonaws.com') end end end end
30.190909
119
0.509485
266bb32c26a0eb8ea2f4ee334649a7c2d84c3bc6
4,805
# frozen_string_literal: true # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! module Google module Cloud module AIPlatform module V1 # Instance of a general artifact. # @!attribute [r] name # @return [::String] # Output only. The resource name of the Artifact. # @!attribute [rw] display_name # @return [::String] # User provided display name of the Artifact. # May be up to 128 Unicode characters. # @!attribute [rw] uri # @return [::String] # The uniform resource identifier of the artifact file. # May be empty if there is no actual artifact file. # @!attribute [rw] etag # @return [::String] # An eTag used to perform consistent read-modify-write updates. If not set, a # blind "overwrite" update happens. # @!attribute [rw] labels # @return [::Google::Protobuf::Map{::String => ::String}] # The labels with user-defined metadata to organize your Artifacts. # # Label keys and values can be no longer than 64 characters # (Unicode codepoints), can only contain lowercase letters, numeric # characters, underscores and dashes. International characters are allowed. # No more than 64 user labels can be associated with one Artifact (System # labels are excluded). # @!attribute [r] create_time # @return [::Google::Protobuf::Timestamp] # Output only. Timestamp when this Artifact was created. # @!attribute [r] update_time # @return [::Google::Protobuf::Timestamp] # Output only. Timestamp when this Artifact was last updated. # @!attribute [rw] state # @return [::Google::Cloud::AIPlatform::V1::Artifact::State] # The state of this Artifact. This is a property of the Artifact, and does # not imply or capture any ongoing process. This property is managed by # clients (such as Vertex AI Pipelines), and the system does not prescribe # or check the validity of state transitions. # @!attribute [rw] schema_title # @return [::String] # The title of the schema describing the metadata. # # Schema title and version is expected to be registered in earlier Create # Schema calls. And both are used together as unique identifiers to identify # schemas within the local metadata store. # @!attribute [rw] schema_version # @return [::String] # The version of the schema in schema_name to use. # # Schema title and version is expected to be registered in earlier Create # Schema calls. And both are used together as unique identifiers to identify # schemas within the local metadata store. # @!attribute [rw] metadata # @return [::Google::Protobuf::Struct] # Properties of the Artifact. # The size of this field should not exceed 200KB. # @!attribute [rw] description # @return [::String] # Description of the Artifact class Artifact include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # @!attribute [rw] key # @return [::String] # @!attribute [rw] value # @return [::String] class LabelsEntry include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Describes the state of the Artifact. module State # Unspecified state for the Artifact. STATE_UNSPECIFIED = 0 # A state used by systems like Vertex AI Pipelines to indicate that the # underlying data item represented by this Artifact is being created. PENDING = 1 # A state indicating that the Artifact should exist, unless something # external to the system deletes it. LIVE = 2 end end end end end end
42.522124
89
0.614984
4afba39f4143c79dea0c646ca2ca795810e81696
5,289
require 'request_helper' RSpec.describe '/test_runs' do let(:router) { Inferno::Web::Router } let(:response_fields) { ['id', 'inputs', 'results', 'status', 'test_group_id'] } let(:test_suite) { BasicTestSuite::Suite } let(:test_group_id) { test_suite.groups.first.id } let(:test_session) { test_run.test_session } let(:test_run) { repo_create(:test_run, runnable: { test_group_id: test_group_id }) } describe 'create' do let(:create_path) { router.path(:api_test_runs) } let(:test_run_definition) do { test_session_id: test_session.id, test_group_id: test_group_id } end context 'with valid input' do let(:inputs) do [ { name: 'input1', value: 'value1', type: 'text' }, { name: 'input2', value: 'value2', type: 'textarea' } ] end it 'renders the test_run json' do Inferno::Repositories::TestRuns.new.mark_as_done(test_run.id) post_json create_path, test_run_definition.merge(inputs: inputs) expect(last_response.status).to eq(200) expect(parsed_body).to include(*response_fields) expect(parsed_body['id']).to be_present expect(parsed_body['test_session_id']).to eq(test_session.id) end it 'persists inputs to the session data table' do Inferno::Repositories::TestRuns.new.mark_as_done(test_run.id) session_data_repo = Inferno::Repositories::SessionData.new test_run_params = test_run_definition.merge(inputs: inputs) post_json create_path, test_run_params expect(session_data_repo.db.count).to eq(2) inputs.each do |input| value = session_data_repo.load(test_session_id: test_session.id, name: input[:name]) expect(value).to eq(input[:value]) end end end context 'with a test_run currently in progress' do it 'returns a 409 error' do post_json create_path, test_run_definition expect(last_response.status).to eq(409) end end context 'with the wait_group in progress' do let(:runner) { Inferno::TestRunner.new(test_session: wait_test_session, test_run: wait_test_run) } let(:wait_test_session) { repo_create(:test_session, test_suite_id: 'demo') } let(:wait_test_run) do repo_create(:test_run, runnable: { test_group_id: wait_group.id }, test_session_id: wait_test_session.id) end let(:wait_group) do Inferno::Repositories::TestSuites.new.find('demo').groups.find do |group| group.id == 'demo-wait_group' end end it 'returns a 409 error' do runner.run(wait_group) post_json create_path, test_run_definition expect(last_response.status).to eq(409) end end context 'with a runnable that is marked as not user runnable' do let(:run_as_group_group_test_run_definition) do { test_session_id: run_as_group_test_session.id, test_group_id: run_as_group_group.id } end let(:run_as_group_test_test_run_definition) do { test_session_id: run_as_group_test_session.id, test_id: run_as_group_test.id } end let(:run_as_group_test_session) { repo_create(:test_session, test_suite_id: 'demo') } let(:run_as_group_test) { run_as_group_group.tests.first } let(:run_as_group_group) do Inferno::Repositories::TestGroups.new.find('demo-run_as_group_examples').groups.first.groups.first end it 'returns a 422 error for an unrunnable group' do post_json create_path, run_as_group_group_test_run_definition expect(last_response.status).to eq(422) end it 'returns a 422 error for an unrunnable test' do post_json create_path, run_as_group_test_test_run_definition expect(last_response.status).to eq(422) end end context 'with missing required inputs' do let(:inputs) do [ { name: 'input1', value: 'value1', type: 'text' } ] end it 'returns a 422 error when inputs are missing' do Inferno::Repositories::TestRuns.new.mark_as_done(test_run.id) post_json create_path, test_run_definition.merge(inputs: inputs) expect(last_response.status).to eq(422) end end end describe 'show' do it 'renders the test_run json' do get router.path(:api_test_run, id: test_run.id) expect(last_response.status).to eq(200) expect(parsed_body).to include(*response_fields) expect(parsed_body['id']).to eq(test_run.id) end end describe 'destroy' do it 'returns 204 when deleted' do delete router.path(:api_test_run, id: test_run.id) expect(last_response.status).to eq(204) end end describe '/:id/results' do let(:result) { repo_create(:result, message_count: 2) } let(:messages) { result.messages } it 'renders the results json' do get router.path(:api_test_run_results, test_run_id: result.test_run_id) expect(last_response.status).to eq(200) expect(parsed_body).to all(include('id', 'result', 'test_run_id', 'test_session_id', 'messages')) expect(parsed_body.first['messages'].length).to eq(messages.length) end end end
32.447853
113
0.665721
f8786b2c6024471b7653eec46be96dd5f173f5e8
1,362
# frozen_string_literal: true module Facter class ExternalFactLoader def custom_facts @custom_facts = load_custom_facts end def external_facts @external_facts ||= load_external_facts end def all_facts @all_facts ||= Utils.deep_copy(custom_facts + external_facts) end private # The search paths must be set before creating the fact collection. # If we set them after, they will not be visible. def load_search_paths LegacyFacter.search(*Options.custom_dir) if Options.custom_dir? LegacyFacter.search_external(Options.external_dir) if Options.external_dir? end def load_custom_facts custom_facts = [] load_search_paths custom_facts_to_load = LegacyFacter.collection.custom_facts custom_facts_to_load&.each do |custom_fact_name| loaded_fact = LoadedFact.new(custom_fact_name.to_s, nil, :custom) custom_facts << loaded_fact end custom_facts end def load_external_facts external_facts = [] load_search_paths external_facts_to_load = LegacyFacter.collection.external_facts external_facts_to_load&.each do |external_fact_name| loaded_fact = LoadedFact.new(external_fact_name.to_s, nil, :external) external_facts << loaded_fact end external_facts end end end
24.763636
81
0.711454
08c8c41706a234bdd29b2769f1c5dfb7c5c553ab
1,201
require 'rack' module ApiHammer # Rack middleware which adds a trailing newline to any responses which do not include one. # # one effect of this is to make curl more readable, as without this, the prompt that follows the # request will be on the same line. # # does not add a newline to blank responses. class TrailingNewline def initialize(app) @app=app end class TNLBodyProxy < Rack::BodyProxy def each last_has_newline = false blank = true @body.each do |e| last_has_newline = e =~ /\n\z/m blank = false if e != '' yield e end yield "\n" unless blank || last_has_newline end include Enumerable end def call(env) status, headers, body = *@app.call(env) _, content_type = headers.detect { |(k,_)| k =~ /\Acontent.type\z/i } if env['REQUEST_METHOD'].downcase != 'head' && ApiHammer::ContentTypeAttrs.new(content_type).text? body = TNLBodyProxy.new(body){} if headers["Content-Length"] headers["Content-Length"] = body.map(&:bytesize).inject(0, &:+).to_s end end [status, headers, body] end end end
30.025
104
0.610325
03c305e35a0e92820a3370f0a902e0fc6a0d0b64
965
require 'pp' # bundler require 'rubygems' require 'bundler/setup' # json # make sure you have an entry like:w # # gem 'yajl-ruby', :require => 'yajl' # # or # gem 'json', :require => 'yajl' # # in your Gemfile require 'rufus-json/automatic' # ruote-kit $:.unshift 'lib' require 'ruote-kit' # ruote require 'ruote/storage/fs_storage' RuoteKit.engine = Ruote::Engine.new( Ruote::Worker.new( Ruote::FsStorage.new( "ruote_work_#{RuoteKit.env}"))) RuoteKit.engine.register do catchall end # redirecting / to /_ruote (to avoid issue reports from new users) class ToRuote def initialize(app) @app = app end def call(env) if env['PATH_INFO'] == '/' [ 303, { 'Location' => '/_ruote', 'Content-Type' => 'text/plain' }, [] ] else @app.call(env) end end end # rack middlewares, business as usual... use ToRuote use Rack::CommonLogger use Rack::Lint use Rack::ShowExceptions run RuoteKit::Application
13.985507
78
0.650777
91230c1e3f8f3eece4e21d2fa76e1a735671000b
18,261
# -*- encoding: utf-8 -*- require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes.rb', __FILE__) # TODO: Add missing String#[]= specs: # String#[re, idx] = obj ruby_version_is ""..."1.9" do describe "String#[]= with Fixnum index" do it "sets the code of the character at idx to char modulo 256" do a = "hello" a[0] = ?b a.should == "bello" a[-1] = ?a a.should == "bella" a[-1] = 0 a.should == "bell\x00" a[-5] = 0 a.should == "\x00ell\x00" a = "x" a[0] = ?y a.should == "y" a[-1] = ?z a.should == "z" a[0] = 255 a[0].should == 255 a[0] = 256 a[0].should == 0 a[0] = 256 * 3 + 42 a[0].should == 42 a[0] = -214 a[0].should == 42 end it "sets the code to char % 256" do str = "Hello" str[0] = ?a + 256 * 3 str[0].should == ?a str[0] = -200 str[0].should == 56 end it "raises an IndexError without changing self if idx is outside of self" do a = "hello" lambda { a[20] = ?a }.should raise_error(IndexError) a.should == "hello" lambda { a[-20] = ?a }.should raise_error(IndexError) a.should == "hello" lambda { ""[0] = ?a }.should raise_error(IndexError) lambda { ""[-1] = ?a }.should raise_error(IndexError) end it "calls to_int on index" do str = "hello" str[0.5] = ?c str.should == "cello" obj = mock('-1') obj.should_receive(:to_int).and_return(-1) str[obj] = ?y str.should == "celly" end it "doesn't call to_int on char" do obj = mock('x') obj.should_not_receive(:to_int) lambda { "hi"[0] = obj }.should raise_error(TypeError) end it "raises a TypeError when self is frozen" do a = "hello" a.freeze lambda { a[0] = ?b }.should raise_error(TypeError) end end end describe "String#[]= with Fixnum index" do it "replaces the char at idx with other_str" do a = "hello" a[0] = "bam" a.should == "bamello" a[-2] = "" a.should == "bamelo" end it "taints self if other_str is tainted" do a = "hello" a[0] = "".taint a.tainted?.should == true a = "hello" a[0] = "x".taint a.tainted?.should == true end it "raises an IndexError without changing self if idx is outside of self" do str = "hello" lambda { str[20] = "bam" }.should raise_error(IndexError) str.should == "hello" lambda { str[-20] = "bam" }.should raise_error(IndexError) str.should == "hello" lambda { ""[-1] = "bam" }.should raise_error(IndexError) end ruby_version_is ""..."1.9" do it "raises an IndexError when setting the zero'th element of an empty String" do lambda { ""[0] = "bam" }.should raise_error(IndexError) end end # Behaviour verfieid correct by matz in # http://redmine.ruby-lang.org/issues/show/1750 ruby_version_is "1.9" do it "allows assignment to the zero'th element of an empty String" do str = "" str[0] = "bam" str.should == "bam" end end it "raises IndexError if the string index doesn't match a position in the string" do str = "hello" lambda { str['y'] = "bam" }.should raise_error(IndexError) str.should == "hello" end ruby_version_is ""..."1.9" do it "raises a TypeError when self is frozen" do a = "hello" a.freeze lambda { a[0] = "bam" }.should raise_error(TypeError) end end ruby_version_is "1.9" do it "raises a RuntimeError when self is frozen" do a = "hello" a.freeze lambda { a[0] = "bam" }.should raise_error(RuntimeError) end end it "calls to_int on index" do str = "hello" str[0.5] = "hi " str.should == "hi ello" obj = mock('-1') obj.should_receive(:to_int).and_return(-1) str[obj] = "!" str.should == "hi ell!" end it "calls #to_str to convert other to a String" do other_str = mock('-test-') other_str.should_receive(:to_str).and_return("-test-") a = "abc" a[1] = other_str a.should == "a-test-c" end it "raises a TypeError if other_str can't be converted to a String" do lambda { "test"[1] = [] }.should raise_error(TypeError) lambda { "test"[1] = mock('x') }.should raise_error(TypeError) lambda { "test"[1] = nil }.should raise_error(TypeError) end with_feature :encoding do it "raises a TypeError if passed a Fixnum replacement" do lambda { "abc"[1] = 65 }.should raise_error(TypeError) end it "raises an IndexError if the index is greater than character size" do lambda { "あれ"[4] = "a" }.should raise_error(IndexError) end it "calls #to_int to convert the index" do index = mock("string element set") index.should_receive(:to_int).and_return(1) str = "あれ" str[index] = "a" str.should == "あa" end it "raises a TypeError if #to_int does not return an Fixnum" do index = mock("string element set") index.should_receive(:to_int).and_return('1') lambda { "abc"[index] = "d" }.should raise_error(TypeError) end it "raises an IndexError if #to_int returns a value out of range" do index = mock("string element set") index.should_receive(:to_int).and_return(4) lambda { "ab"[index] = "c" }.should raise_error(IndexError) end it "replaces a character with a multibyte character" do str = "ありがとu" str[4] = "う" str.should == "ありがとう" end it "replaces a multibyte character with a character" do str = "ありがとう" str[4] = "u" str.should == "ありがとu" end it "replaces a multibyte character with a multibyte character" do str = "ありがとお" str[4] = "う" str.should == "ありがとう" end it "encodes the String in an encoding compatible with the replacement" do str = " ".force_encoding Encoding::US_ASCII rep = "\xA0".force_encoding Encoding::ASCII_8BIT str[0] = rep str.encoding.should equal(Encoding::ASCII_8BIT) end it "raises an Encoding::CompatibilityError if the replacement encoding is incompatible" do str = "あれ" rep = "が".encode Encoding::EUC_JP lambda { str[0] = rep }.should raise_error(Encoding::CompatibilityError) end end end describe "String#[]= with String index" do it "replaces fewer characters with more characters" do str = "abcde" str["cd"] = "ghi" str.should == "abghie" end it "replaces more characters with fewer characters" do str = "abcde" str["bcd"] = "f" str.should == "afe" end it "replaces characters with no characters" do str = "abcde" str["cd"] = "" str.should == "abe" end it "raises an IndexError if the search String is not found" do str = "abcde" lambda { str["g"] = "h" }.should raise_error(IndexError) end with_feature :encoding do it "replaces characters with a multibyte character" do str = "ありgaとう" str["ga"] = "が" str.should == "ありがとう" end it "replaces multibyte characters with characters" do str = "ありがとう" str["が"] = "ga" str.should == "ありgaとう" end it "replaces multibyte characters with multibyte characters" do str = "ありがとう" str["が"] = "か" str.should == "ありかとう" end it "encodes the String in an encoding compatible with the replacement" do str = " ".force_encoding Encoding::US_ASCII rep = "\xA0".force_encoding Encoding::ASCII_8BIT str[" "] = rep str.encoding.should equal(Encoding::ASCII_8BIT) end it "raises an Encoding::CompatibilityError if the replacement encoding is incompatible" do str = "あれ" rep = "が".encode Encoding::EUC_JP lambda { str["れ"] = rep }.should raise_error(Encoding::CompatibilityError) end end end describe "String#[]= with a Regexp index" do it "replaces the matched text with the rhs" do str = "hello" str[/lo/] = "x" str.should == "helx" end it "raises IndexError if the regexp index doesn't match a position in the string" do str = "hello" lambda { str[/y/] = "bam" }.should raise_error(IndexError) str.should == "hello" end describe "with 3 arguments" do it "calls #to_int to convert the second object" do ref = mock("string element set regexp ref") ref.should_receive(:to_int).and_return(1) str = "abc" str[/a(b)/, ref] = "x" str.should == "axc" end it "raises a TypeError if #to_int does not return a Fixnum" do ref = mock("string element set regexp ref") ref.should_receive(:to_int).and_return(nil) lambda { "abc"[/a(b)/, ref] = "x" }.should raise_error(TypeError) end it "uses the 2nd of 3 arguments as which capture should be replaced" do str = "aaa bbb ccc" str[/a (bbb) c/, 1] = "ddd" str.should == "aaa ddd ccc" end it "allows the specified capture to be negative and count from the end" do str = "abcd" str[/(a)(b)(c)(d)/, -2] = "e" str.should == "abed" end it "raises IndexError if the specified capture isn't available" do str = "aaa bbb ccc" lambda { str[/a (bbb) c/, 2] = "ddd" }.should raise_error(IndexError) lambda { str[/a (bbb) c/, -2] = "ddd" }.should raise_error(IndexError) end end with_feature :encoding do it "replaces characters with a multibyte character" do str = "ありgaとう" str[/ga/] = "が" str.should == "ありがとう" end it "replaces multibyte characters with characters" do str = "ありがとう" str[/が/] = "ga" str.should == "ありgaとう" end it "replaces multibyte characters with multibyte characters" do str = "ありがとう" str[/が/] = "か" str.should == "ありかとう" end it "encodes the String in an encoding compatible with the replacement" do str = " ".force_encoding Encoding::US_ASCII rep = "\xA0".force_encoding Encoding::ASCII_8BIT str[/ /] = rep str.encoding.should equal(Encoding::ASCII_8BIT) end it "raises an Encoding::CompatibilityError if the replacement encoding is incompatible" do str = "あれ" rep = "が".encode Encoding::EUC_JP lambda { str[/れ/] = rep }.should raise_error(Encoding::CompatibilityError) end end end describe "String#[]= with a Range index" do describe "with an empty replacement" do it "does not replace a character with a zero-index, zero exclude-end range" do str = "abc" str[0...0] = "" str.should == "abc" end it "does not replace a character with a zero exclude-end range" do str = "abc" str[1...1] = "" str.should == "abc" end it "replaces a character with zero-index, zero non-exclude-end range" do str = "abc" str[0..0] = "" str.should == "bc" end it "replaces a character with a zero non-exclude-end range" do str = "abc" str[1..1] = "" str.should == "ac" end end it "replaces the contents with a shorter String" do str = "abcde" str[0..-1] = "hg" str.should == "hg" end it "replaces the contents with a longer String" do str = "abc" str[0...4] = "uvwxyz" str.should == "uvwxyz" end it "replaces a partial string" do str = "abcde" str[1..3] = "B" str.should == "aBe" end it "raises a RangeError if negative Range begin is out of range" do lambda { "abc"[-4..-2] = "x" }.should raise_error(RangeError) end it "raises a RangeError if positive Range begin is greater than String size" do lambda { "abc"[4..2] = "x" }.should raise_error(RangeError) end it "uses the Range end as an index rather than a count" do str = "abcdefg" str[-5..3] = "xyz" str.should == "abxyzefg" end it "treats a negative out-of-range Range end with a positive Range begin as a zero count" do str = "abc" str[1..-4] = "x" str.should == "axbc" end it "treats a negative out-of-range Range end with a negative Range begin as a zero count" do str = "abcd" str[-1..-4] = "x" str.should == "abcxd" end with_feature :encoding do it "replaces characters with a multibyte character" do str = "ありgaとう" str[2..3] = "が" str.should == "ありがとう" end it "replaces multibyte characters with characters" do str = "ありがとう" str[2...3] = "ga" str.should == "ありgaとう" end it "replaces multibyte characters by negative indexes" do str = "ありがとう" str[-3...-2] = "ga" str.should == "ありgaとう" end it "replaces multibyte characters with multibyte characters" do str = "ありがとう" str[2..2] = "か" str.should == "ありかとう" end it "deletes a multibyte character" do str = "ありとう" str[2..3] = "" str.should == "あり" end it "inserts a multibyte character" do str = "ありとう" str[2...2] = "が" str.should == "ありがとう" end it "encodes the String in an encoding compatible with the replacement" do str = " ".force_encoding Encoding::US_ASCII rep = "\xA0".force_encoding Encoding::ASCII_8BIT str[0..1] = rep str.encoding.should equal(Encoding::ASCII_8BIT) end it "raises an Encoding::CompatibilityError if the replacement encoding is incompatible" do str = "あれ" rep = "が".encode Encoding::EUC_JP lambda { str[0..1] = rep }.should raise_error(Encoding::CompatibilityError) end end end describe "String#[]= with Fixnum index, count" do it "starts at idx and overwrites count characters before inserting the rest of other_str" do a = "hello" a[0, 2] = "xx" a.should == "xxllo" a = "hello" a[0, 2] = "jello" a.should == "jellollo" end it "counts negative idx values from end of the string" do a = "hello" a[-1, 0] = "bob" a.should == "hellbobo" a = "hello" a[-5, 0] = "bob" a.should == "bobhello" end it "overwrites and deletes characters if count is more than the length of other_str" do a = "hello" a[0, 4] = "x" a.should == "xo" a = "hello" a[0, 5] = "x" a.should == "x" end it "deletes characters if other_str is an empty string" do a = "hello" a[0, 2] = "" a.should == "llo" end it "deletes characters up to the maximum length of the existing string" do a = "hello" a[0, 6] = "x" a.should == "x" a = "hello" a[0, 100] = "" a.should == "" end it "appends other_str to the end of the string if idx == the length of the string" do a = "hello" a[5, 0] = "bob" a.should == "hellobob" end it "taints self if other_str is tainted" do a = "hello" a[0, 0] = "".taint a.tainted?.should == true a = "hello" a[1, 4] = "x".taint a.tainted?.should == true end it "calls #to_int to convert the index and count objects" do index = mock("string element set index") index.should_receive(:to_int).and_return(-4) count = mock("string element set count") count.should_receive(:to_int).and_return(2) str = "abcde" str[index, count] = "xyz" str.should == "axyzde" end it "raises a TypeError if #to_int for index does not return an Integer" do index = mock("string element set index") index.should_receive(:to_int).and_return("1") lambda { "abc"[index, 2] = "xyz" }.should raise_error(TypeError) end it "raises a TypeError if #to_int for count does not return an Integer" do count = mock("string element set count") count.should_receive(:to_int).and_return("1") lambda { "abc"[1, count] = "xyz" }.should raise_error(TypeError) end it "calls #to_str to convert the replacement object" do r = mock("string element set replacement") r.should_receive(:to_str).and_return("xyz") str = "abcde" str[2, 2] = r str.should == "abxyze" end it "raises a TypeError of #to_str does not return a String" do r = mock("string element set replacement") r.should_receive(:to_str).and_return(nil) lambda { "abc"[1, 1] = r }.should raise_error(TypeError) end it "raises an IndexError if |idx| is greater than the length of the string" do lambda { "hello"[6, 0] = "bob" }.should raise_error(IndexError) lambda { "hello"[-6, 0] = "bob" }.should raise_error(IndexError) end it "raises an IndexError if count < 0" do lambda { "hello"[0, -1] = "bob" }.should raise_error(IndexError) lambda { "hello"[1, -1] = "bob" }.should raise_error(IndexError) end it "raises a TypeError if other_str is a type other than String" do lambda { "hello"[0, 2] = nil }.should raise_error(TypeError) lambda { "hello"[0, 2] = [] }.should raise_error(TypeError) lambda { "hello"[0, 2] = 33 }.should raise_error(TypeError) end with_feature :encoding do it "replaces characters with a multibyte character" do str = "ありgaとう" str[2, 2] = "が" str.should == "ありがとう" end it "replaces multibyte characters with characters" do str = "ありがとう" str[2, 1] = "ga" str.should == "ありgaとう" end it "replaces multibyte characters with multibyte characters" do str = "ありがとう" str[2, 1] = "か" str.should == "ありかとう" end it "deletes a multibyte character" do str = "ありとう" str[2, 2] = "" str.should == "あり" end it "inserts a multibyte character" do str = "ありとう" str[2, 0] = "が" str.should == "ありがとう" end it "raises an IndexError if the character index is out of range of a multibyte String" do lambda { "あれ"[3, 0] = "り" }.should raise_error(IndexError) end it "encodes the String in an encoding compatible with the replacement" do str = " ".force_encoding Encoding::US_ASCII rep = "\xA0".force_encoding Encoding::ASCII_8BIT str[0, 1] = rep str.encoding.should equal(Encoding::ASCII_8BIT) end it "raises an Encoding::CompatibilityError if the replacement encoding is incompatible" do str = "あれ" rep = "が".encode Encoding::EUC_JP lambda { str[0, 1] = rep }.should raise_error(Encoding::CompatibilityError) end end end
26.933628
94
0.602596
bf26ec538aad74c50c5ae25e1b74d65cf89633e8
5,996
# frozen_string_literal: true def whyrun_supported? true end use_inline_resources # ~FC113 action :create do Chef::Application.fatal!("CategoryGroup specified '#{@current_resource.category_group}' doesn't exist!") unless @current_resource.catgroup_exists if @current_resource.changed Chef::Log.info "#{@new_resource} already exists but has changed - updating." converge_by("Update #{@new_resource}") do update_avail_category end elsif @current_resource.exists Chef::Log.info "#{@new_resource} already exists - nothing to do." else converge_by("Create #{@new_resource}") do create_avail_category end end end def load_current_resource @current_resource = Chef::Resource.resource_for_node(:opennms_avail_category, node).new(@new_resource.label) # @current_resource.name(@new_resource.name) @current_resource.category_group(@new_resource.category_group) @current_resource.comment(@new_resource.comment) @current_resource.normal(@new_resource.normal) @current_resource.warning(@new_resource.warning) @current_resource.rule(@new_resource.rule) @current_resource.services(@new_resource.services) if category_group_exists?(@current_resource.category_group) @current_resource.catgroup_exists = true if category_exists?(@current_resource.category_group, @current_resource.label) @current_resource.exists = true @current_resource.changed = true if category_changed?(@current_resource) end end end def category_group_exists?(group) file = ::File.new("#{node['opennms']['conf']['home']}/etc/categories.xml", 'r') doc = REXML::Document.new file file.close Chef::Log.debug "group is #{group}" name_el = doc.elements["/catinfo/categorygroup/name[text()[contains(.,'#{group}')]]"] Chef::Log.debug name_el.to_s !name_el.nil? end def category_exists?(group, label) Chef::Log.debug "label: #{label}" file = ::File.new("#{node['opennms']['conf']['home']}/etc/categories.xml", 'r') doc = REXML::Document.new file file.close !doc.elements["/catinfo/categorygroup[name[text()[contains(.,'#{group}')]]]/categories/category/label[text()[contains(.,'#{label}')]]"].nil? end def category_changed?(current_resource) file = ::File.new("#{node['opennms']['conf']['home']}/etc/categories.xml", 'r') doc = REXML::Document.new file file.close cat_el = doc.elements["/catinfo/categorygroup[name[text()[contains(.,'#{current_resource.category_group}')]]]/categories/category[label[text()[contains(.,'#{current_resource.label}')]]]"] label_el = cat_el.elements['label'] comment_el = cat_el.elements['comment'] normal_el = cat_el.elements['normal'] warn_el = cat_el.elements['warning'] rule_el = cat_el.elements['rule'] return true if label_el.text.to_s != current_resource.label.to_s Chef::Log.debug("#{label_el.text} == #{current_resource.label}") return true if comment_el.text.to_s != current_resource.comment.to_s Chef::Log.debug("#{comment_el.text} == #{current_resource.comment}") return true if normal_el.text.to_s != current_resource.normal.to_s Chef::Log.debug("#{normal_el.text} == #{current_resource.normal}") return true if warn_el.text.to_s != current_resource.warning.to_s Chef::Log.debug("#{warn_el.text} == #{current_resource.warning}") curr_services = [] cat_el.elements.each 'service' do |s| curr_services.push s.text.to_s end curr_services.sort! current_resource.services.sort! return true if curr_services != current_resource.services Chef::Log.debug("#{curr_services} == #{current_resource.services}") # return true if "#{service_els.text}" != "#{rule}" return true if rule_el.text.to_s != current_resource.rule.to_s Chef::Log.debug("#{rule_el.text} == #{current_resource.rule}") false end def update_avail_category file = ::File.new("#{node['opennms']['conf']['home']}/etc/categories.xml", 'r') doc = REXML::Document.new file file.close cat_el = doc.elements["/catinfo/categorygroup[name[text()[contains(.,'#{new_resource.category_group}')]]]/categories/category[label[text()[contains(.,'#{new_resource.label}')]]]"] comment_el = cat_el.elements['comment'] # clear out existing text comment_el.text = nil while comment_el.has_text? comment_el.add_text new_resource.comment normal_el = cat_el.elements['normal'] normal_el.text = nil while normal_el.has_text? normal_el.add_text new_resource.normal.to_s warning_el = cat_el.elements['warning'] warning_el.text = nil while warning_el.has_text? warning_el.add_text new_resource.warning.to_s cat_el.elements.delete_all 'service' new_resource.services.each do |s| s_el = cat_el.add_element 'service' s_el.add_text s end rule_el = cat_el.elements['rule'] rule_el.text = nil while rule_el.has_text? rule_el.add_text(REXML::CData.new(new_resource.rule)) Opennms::Helpers.write_xml_file(doc, "#{node['opennms']['conf']['home']}/etc/categories.xml") end # order doesn't matter here - these just exist to be referenced by viewdisplay.xml def create_avail_category file = ::File.new("#{node['opennms']['conf']['home']}/etc/categories.xml", 'r') doc = REXML::Document.new file file.close cg_el = doc.elements["/catinfo/categorygroup[name[text()[contains(.,'#{new_resource.category_group}')]]]/categories"] cat_el = cg_el.add_element 'category' label_el = cat_el.add_element 'label' label_el.add_text(REXML::CData.new(new_resource.label)) comment_el = cat_el.add_element 'comment' comment_el.add_text new_resource.comment normal_el = cat_el.add_element 'normal' normal_el.add_text new_resource.normal.to_s # really ruby? really? warning_el = cat_el.add_element 'warning' warning_el.add_text new_resource.warning.to_s new_resource.services.each do |s| s_el = cat_el.add_element 'service' s_el.add_text s end rule_el = cat_el.add_element 'rule' rule_el.add_text(REXML::CData.new(new_resource.rule)) Opennms::Helpers.write_xml_file(doc, "#{node['opennms']['conf']['home']}/etc/categories.xml") end
42.225352
189
0.735324
d525e1775bdc800fd01cc66c0916eb50d82fc33f
3,006
class SysWatchdog DEFAULT_CONF_FILE = '/etc/sys_watchdog.yml' DEFAULT_LOG_FILE = '/var/log/sys_watchdog.log' WORKING_DIR = '/var/local/sys_watchdog' CRONJOB_PATH = '/etc/cron.d/sys_watchdog' INSTALL_TYPE_PATH = "#{WORKING_DIR}/install_type" def initialize conf_file: nil, log_file: nil log_file ||= DEFAULT_LOG_FILE conf_file ||= DEFAULT_CONF_FILE @logger = WdLogger.new log_file parse_conf conf_file setup end def run once: false loop do @tests.each{|test| run_test test} return if once sleep 60 end end private def setup if @conf.slack_token Slack.configure do |config| config.token = @conf.slack_token end end if @conf.smtp_server conf_ = @conf Mail.defaults do delivery_method :smtp, address: conf_.smtp_server, port: 587, :domain => conf_.smtp_domain, :enable_starttls_auto => true, :openssl_verify_mode => 'none' end end end def parse_conf conf_file check_conf_file conf_file conf = YAML.load_file conf_file conf.deep_symbolize_keys! @conf = OpenStruct.new conf[:config] @tests = conf[:tests].keys.map { |name| WdTest.new(name, conf[:tests][name], @logger) } end def check_conf_file conf_file unless File.readable? conf_file raise "Conf file #{conf_file} not found or unreadable. Aborting." end conf_stat = File.stat conf_file unless conf_stat.mode.to_s(8) =~ /0600$/ raise "Conf file #{conf_file} must have mode 0600. Aborting." end unless match_root_or_current_user(conf_stat) raise "Conf file #{conf_file} must have uid/gid set to root or to current running uid/gid. Aborting." end end def run_test test, after_restore: false new_status, _exitstatus, output = test.run notify_output_change test, output return if new_status == test.status test.status = new_status if new_status notify "#{test.name} ok#{' (restored)' if after_restore}" else if test.restore_cmd and not after_restore test.restore run_test test, after_restore: true else fail test, output end end rescue => e @logger.error e.desc end def notify_output_change test, output if test.notify_on_output_change and test.previous_output != output notify "#{test.name} changed", "old: #{test.previous_output}\nnew: #{output}" test.previous_output = output end end def fail test, output body = "" body += "output: #{output}" if output and not output.empty? notify "#{test.name} fail", body end end
28.093458
114
0.585163
f82921b6f54acf3f90f6dec2d4f6dae354604ece
97
module ApplicationHelper def display_error @errors = @item.errors.full_messages end end
13.857143
40
0.762887
1af9a27050f913ef570632339306bebad3a64ad5
5,256
require "cloudfront-signer" require "cloud_controller/blobstore/blobstore" module VCAP::CloudController class StagingsController < RestController::Base include VCAP::Errors STAGING_PATH = "/staging" DROPLET_PATH = "#{STAGING_PATH}/droplets" BUILDPACK_CACHE_PATH = "#{STAGING_PATH}/buildpack_cache" # Endpoint does its own basic auth allow_unauthenticated_access authenticate_basic_auth("#{STAGING_PATH}/*") do [VCAP::CloudController::Config.config[:staging][:auth][:user], VCAP::CloudController::Config.config[:staging][:auth][:password]] end attr_reader :config, :blobstore, :buildpack_cache_blobstore, :package_blobstore get "/staging/apps/:guid", :download_app def download_app(guid) raise InvalidRequest unless package_blobstore.local? app = App.find(:guid => guid) raise AppNotFound.new(guid) if app.nil? file = package_blobstore.file(guid) package_path = file.send(:path) if file logger.debug "guid: #{guid} package_path: #{package_path}" unless package_path logger.error "could not find package for #{guid}" raise AppPackageNotFound.new(guid) end if config[:nginx][:use_nginx] url = package_blobstore.download_uri(guid) logger.debug "nginx redirect #{url}" [200, {"X-Accel-Redirect" => url}, ""] else logger.debug "send_file #{package_path}" send_file package_path end end post "#{DROPLET_PATH}/:guid/upload", :upload_droplet def upload_droplet(guid) app = App.find(:guid => guid) raise AppNotFound.new(guid) if app.nil? raise StagingError.new("malformed droplet upload request for #{app.guid}") unless upload_path logger.info "droplet.begin-upload", :app_guid => app.guid droplet_upload_job = Jobs::Runtime::DropletUpload.new(upload_path, app.id) if async? job = Delayed::Job.enqueue(droplet_upload_job, queue: LocalQueue.new(config)) external_domain = Array(config[:external_domain]).first [HTTP::OK, JobPresenter.new(job, "http://#{external_domain}").to_json] else droplet_upload_job.perform HTTP::OK end end get "#{DROPLET_PATH}/:guid/download", :download_droplet def download_droplet(guid) app = App.find(:guid => guid) raise AppNotFound.new(guid) if app.nil? droplet = app.current_droplet blob_name = "droplet" log_and_raise_missing_blob(app.guid, blob_name) unless droplet download(app, droplet.local_path, droplet.download_url, blob_name) end post "#{BUILDPACK_CACHE_PATH}/:guid/upload", :upload_buildpack_cache def upload_buildpack_cache(guid) app = App.find(:guid => guid) raise AppNotFound.new(guid) if app.nil? raise StagingError.new("malformed buildpack cache upload request for #{app.guid}") unless upload_path blobstore_upload = Jobs::Runtime::BlobstoreUpload.new(upload_path, app.guid, :buildpack_cache_blobstore) Delayed::Job.enqueue(blobstore_upload, queue: LocalQueue.new(config)) HTTP::OK end get "#{BUILDPACK_CACHE_PATH}/:guid/download", :download_buildpack_cache def download_buildpack_cache(guid) app = App.find(:guid => guid) raise AppNotFound.new(guid) if app.nil? file = buildpack_cache_blobstore.file(app.guid) buildpack_cache_path = file.send(:path) if file blob_name = "buildpack cache" log_and_raise_missing_blob(app.guid, blob_name) unless buildpack_cache_path buildpack_cache_url = buildpack_cache_blobstore.download_uri(app.guid) download(app, buildpack_cache_path, buildpack_cache_url, blob_name) end private def inject_dependencies(dependencies) super @blobstore = dependencies.fetch(:droplet_blobstore) @buildpack_cache_blobstore = dependencies.fetch(:buildpack_cache_blobstore) @package_blobstore = dependencies.fetch(:package_blobstore) @config = dependencies.fetch(:config) end def log_and_raise_missing_blob(app_guid, name) Loggregator.emit_error(app_guid, "Did not find #{name} for app with guid: #{app_guid}") logger.error "could not find #{name} for #{app_guid}" raise StagingError.new("#{name} not found for #{app_guid}") end def download(app, blob_path, url, name) raise InvalidRequest unless blobstore.local? logger.debug "guid: #{app.guid} #{name} #{blob_path} #{url}" if config[:nginx][:use_nginx] logger.debug "nginx redirect #{url}" [200, {"X-Accel-Redirect" => url}, ""] else logger.debug "send_file #{blob_path}" send_file blob_path end end def upload_path @upload_path ||= if get_from_hash_tree(config, :nginx, :use_nginx) params["droplet_path"] elsif (tempfile = get_from_hash_tree(params, "upload", "droplet", :tempfile)) tempfile.path end end def get_from_hash_tree(hash, *path) path.reduce(hash) do |here, seg| return unless here && here.is_a?(Hash) here[seg] end end def tmpdir (config[:directories] && config[:directories][:tmpdir]) || Dir.tmpdir end end end
33.477707
110
0.676941
1a90f09a35c600a33b860be211b004a687aca6e1
1,411
require 'active_record' require 'mongoid' module ModelSupport def self.included(base) base.extend ClassMethods end module ClassMethods def fake_active_record(name, &block) let(name) { Class.new(ActiveRecord::Base) do self.table_name = 'dummies' instance_eval &block end } end def fake_mongoid_model(name, &block) let(name) { Class.new do include Mongoid::Document include SimpleEnum::Mongoid store_in collection: 'dummies' instance_eval &block end } end def fake_multiple_model(name, *fields, &block) fields << :favorite_cds let(name) { Struct.new(*fields) do extend ActiveModel::Translation extend SimpleEnum::Attribute instance_eval &block if block_given? def self.model_name @model_name ||= ActiveModel::Name.new(self, nil, "FakeModel") end end } end def fake_model(name, *fields, &block) fields << :gender_cd let(name) { Struct.new(*fields) do extend ActiveModel::Translation extend SimpleEnum::Attribute instance_eval &block if block_given? def self.model_name @model_name ||= ActiveModel::Name.new(self, nil, "FakeModel") end end } end end end
22.396825
73
0.583983
0317ca045b4c648c1ef744d1f8480d81397ceba0
2,090
# Some tests require the more flexible driver methods for 'get', 'post' # etc. than available in RSpec controller tests. # # See also spec/controllers/scimitar/application_controller_spec.rb. # require 'spec_helper' RSpec.describe Scimitar::ApplicationController do before :each do allow_any_instance_of(Scimitar::ApplicationController).to receive(:authenticated?).and_return(true) end context 'format handling' do it 'renders "not acceptable" if the request does not use SCIM type' do get '/CustomRequestVerifiers', params: { format: :html } expect(response).to have_http_status(:not_acceptable) expect(JSON.parse(response.body)['detail']).to eql('Only application/scim+json type is accepted.') end it 'renders 400 if given bad JSON' do post '/CustomRequestVerifiers', params: 'not-json-12345', headers: { 'CONTENT_TYPE' => 'application/scim+json' } expect(response).to have_http_status(:bad_request) expect(JSON.parse(response.body)['detail']).to start_with('Invalid JSON - ') expect(JSON.parse(response.body)['detail']).to include("'not-json-12345'") end it 'translates Content-Type to Rails request format' do get '/CustomRequestVerifiers', headers: { 'CONTENT_TYPE' => 'application/scim+json' } expect(response).to have_http_status(:ok) parsed_body = JSON.parse(response.body) expect(parsed_body['request']['is_scim' ]).to eql(true) expect(parsed_body['request']['format' ]).to eql('application/scim+json') expect(parsed_body['request']['content_type']).to eql('application/scim+json') end it 'translates Rails request format to header' do get '/CustomRequestVerifiers', params: { format: :scim } expect(response).to have_http_status(:ok) parsed_body = JSON.parse(response.body) expect(parsed_body['request']['is_scim' ]).to eql(true) expect(parsed_body['request']['format' ]).to eql('application/scim+json') expect(parsed_body['request']['content_type']).to eql('application/scim+json') end end end
41.8
118
0.7
edf216cf2d7ce103f09f36ad3e83f0d80d8c6ce0
5,205
# 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_relative 'static' module BrocadeAPIClient # Brocade Exception Classes class BrocadeException < StandardError attr_reader :message, :code, :ref, :http_status def initialize(code: nil, message: nil, ref: nil, http_status: nil) @code = code @message = message @ref = ref @http_status = http_status formatted_string = 'Error: ' formatted_string += format(' (HTTP %s)', @http_status) if @http_status formatted_string += format(' API code: %s', @code) if @code formatted_string += format(' - %s', @message) if @message formatted_string += format(' - %s', @ref) if @ref super(formatted_string) end end exceptions_map = [{ name: 'UnsupportedOption', message: 'Unsupported Zoning Option, supported ALL is without zonename' }, { name: 'UnsupportedAction', message: 'Unsupported Action, only ADD/Remove allowed' }, { name: 'UnsupportedVersion', message: "Unsupported Brocade Network Advisor version, min supported version is, #{BrocadeAPIClient::BNASupport::BNA_MIN_SUPPORTED}" }, { name: 'UnsupportedSeverityOption' }, { name: 'InvalidPeerzoneOptions', message: 'Use principal and members as hash keys' }, { name: 'InvalidVersion', message: 'Invalid API Version Detected' }, { name: 'RequestException' }, { name: 'ConnectionError', message: 'Connection Error to Brocade Network Advisor version' }, { name: 'HTTPError' }, { name: 'URLRequired' }, { name: 'TooManyRedirects' }, { name: 'Timeout' }, { name: 'SSLCertFailed' }, { name: 'HTTPBadRequest', http_status: 400, message: 'Bad request' }, { name: 'HTTPUnauthorized', http_status: 401, message: 'Unauthorized' }, { name: 'HTTPForbidden', http_status: 403, message: 'Forbidden' }, { name: 'HTTPNotFound', http_status: 404, message: 'Not found' }, { name: 'HTTPMethodNotAllowed', http_status: 405, message: 'Method Not Allowed' }, { name: 'HTTPNotAcceptable', http_status: 406, message: 'Method Not Acceptable' }, { name: 'HTTPProxyAuthRequired', http_status: 407, message: 'Proxy Authentication Required' }, { name: 'HTTPRequestTimeout', http_status: 408, message: 'Request Timeout' }, { name: 'HTTPConflict', http_status: 409, message: 'Conflict' }, { name: 'HTTPGone', http_status: 410, message: 'Gone' }, { name: 'HTTPLengthRequired', http_status: 411, message: 'Length Required' }, { name: 'HTTPPreconditionFailed', http_status: 412, message: 'Over limit' }, { name: 'HTTPRequestEntityTooLarge', http_status: 413, message: 'Request Entity Too Large' }, { name: 'HTTPRequestURITooLong', http_status: 414, message: 'Request URI Too Large' }, { name: 'HTTPUnsupportedMediaType', http_status: 415, message: 'Unsupported Media Type' }, { name: 'HTTPRequestedRangeNotSatisfiable', http_status: 416, message: 'Requested Range Not Satisfiable' }, { name: 'HTTPExpectationFailed', http_status: 417, message: 'Expectation Failed' }, { name: 'HTTPTeaPot', http_status: 418, message: 'I\'m A Teapot. (RFC 2324)' }, { name: 'HTTPInternalServerError', http_status: 500, message: 'Internal Server Error' }, { name: 'HTTPNotImplemented', http_status: 501, message: 'Not Implemented' }, { name: 'HTTPBadGateway', http_status: 502, message: 'Bad Gateway' }, { name: 'HTTPServiceUnavailable', http_status: 503, message: 'Service Unavailable' }, { name: 'HTTPGatewayTimeout', http_status: 504, message: 'Gateway Timeout' }, { name: 'HTTPVersionNotSupported', http_status: 505, message: 'Version Not Supported' }] exceptions_map.each { |x| BrocadeAPIClient.const_set(x[:name], BrocadeException.new(http_status: x[:http_status], message: x[:message])) } attr_accessor :code_map @@code_map = Hash.new('BrocadeException') exceptions_map.each do |c| inst = BrocadeAPIClient.const_get(c[:name]) @@code_map[inst.http_status] = c end def self.exception_from_response(response, _body) # Return an instance of an ClientException cls = @@code_map[response.code] BrocadeAPIClient.const_get(cls[:name]) end end
65.0625
185
0.624207
7a0995aaab2421aab0427f2f7f21b7c48ec55b79
247
cask :v1 => 'kibako' do version :latest sha256 :no_check url 'https://updates.kibakoapp.com/download/latest' homepage 'https://www.kibakoapp.com/' license :unknown # todo: improve this machine-generated value app 'Kibako.app' end
22.454545
66
0.708502
ffbaef8ed90783d6d3e71749156089d1d0ca468c
2,806
namespace :regions do desc 'Import regions from YAML without deleting old data' task import: :environment do file_path = "#{Rails.root}/tmp/import/regions.yml" media_dir = "#{Rails.root}/tmp/import/regions" ignored = %w(image header_image) if File.exists? file_path File.open file_path, 'r' do |file| YAML.load(file).each do |id, data| attributes = data.reject { |key| ignored.include?(key) } entity = Region.find_by(id: id) || Region.new(id: id) entity.assign_attributes(attributes) if data.key?('image') && entity.image.blank? image_file = "#{media_dir}/image/#{id}/#{data['image']}" if File.exists?(image_file) entity.image = Pathname.new(image_file).open end end if data.key?('header_image') && entity.header_image.blank? image_file = "#{media_dir}/header_image/#{id}/#{data['header_image']}" if File.exists?(image_file) entity.header_image = Pathname.new(image_file).open end end entity.save! print "\r#{id} " end puts end Region.connection.execute "select setval('regions_id_seq', (select max(id) from regions));" puts "Done. We have #{Region.count} regions now" else puts "Cannot find file #{file_path}" end end desc 'Dump regions to YAML' task dump: :environment do file_path = "#{Rails.root}/tmp/export/regions.yml" media_dir = "#{Rails.root}/tmp/export/regions" ignored = %w(id users_count image header_image) File.open file_path, 'w' do |file| Region.order('id asc').each do |entity| print "\r#{entity.id} " file.puts "#{entity.id}:" entity.attributes.reject { |a, v| ignored.include?(a) || v.nil? }.each do |attribute, value| file.puts " #{attribute}: #{value.inspect}" end unless entity.image.blank? image_name = "#{entity.long_slug}#{File.extname(File.basename(entity.image.path))}" image_dir = "#{media_dir}/image/#{entity.id}" FileUtils.mkdir_p(image_dir) unless Dir.exists?(image_dir) FileUtils.copy(entity.image.path, "#{image_dir}/#{image_name}") file.puts " image: #{image_name.inspect}" end unless entity.header_image.blank? image_name = "#{entity.long_slug}#{File.extname(File.basename(entity.header_image.path))}" image_dir = "#{media_dir}/header_image/#{entity.id}" FileUtils.mkdir_p(image_dir) unless Dir.exists?(image_dir) FileUtils.copy(entity.header_image.path, "#{image_dir}/#{image_name}") file.puts " header_image: #{image_name.inspect}" end end puts end end end
41.264706
100
0.604063
62e03e68aeeb21bcccff35d80a7c8b75255a2cce
584
# frozen_string_literal: true require 'spec_helper' describe 'User activates Pushover' do include_context 'project service activation' before do stub_request(:post, /.*api.pushover.net.*/) end it 'activates service', :js do visit_project_integration('Pushover') fill_in('Api key', with: 'verySecret') fill_in('User key', with: 'verySecret') fill_in('Device', with: 'myDevice') select('High Priority', from: 'Priority') select('Bike', from: 'Sound') click_test_integration expect(page).to have_content('Pushover activated.') end end
23.36
55
0.696918
e9cc357970338f4a61a1fc4a7084f1307e275795
441
# frozen_string_literal: true require_dependency "#{Rails.root}/lib/training_module" # Controller for data on which trainings a user has completed class TrainingStatusController < ApplicationController def show @course = Course.find(params[:course_id]) @assigned_training_modules = @course.training_modules @user = User.find(params[:user_id]) end def user @user = User.find_by(username: params[:username]) end end
25.941176
61
0.755102
110ce65d4c1e4e58179a08f919a95fd7572da95e
3,969
require File.expand_path('../helper', __FILE__) class TestRakeTaskManager < Rake::TestCase def setup super @tm = Rake::TestCase::TaskManager.new end def test_create_task_manager refute_nil @tm assert_equal [], @tm.tasks end def test_define_task t = @tm.define_task(Rake::Task, :t) assert_equal "t", t.name assert_equal @tm, t.application end def test_index e = assert_raises RuntimeError do @tm['bad'] end assert_equal "Don't know how to build task 'bad'", e.message end def test_name_lookup t = @tm.define_task(Rake::Task, :t) assert_equal t, @tm[:t] end def test_namespace_task_create @tm.in_namespace("x") do t = @tm.define_task(Rake::Task, :t) assert_equal "x:t", t.name end assert_equal ["x:t"], @tm.tasks.collect { |t| t.name } end def test_anonymous_namespace anon_ns = @tm.in_namespace(nil) do t = @tm.define_task(Rake::Task, :t) assert_equal "_anon_1:t", t.name end task = anon_ns[:t] assert_equal "_anon_1:t", task.name end def test_create_filetask_in_namespace @tm.in_namespace("x") do t = @tm.define_task(Rake::FileTask, "fn") assert_equal "fn", t.name end assert_equal ["fn"], @tm.tasks.collect { |t| t.name } end def test_namespace_yields_same_namespace_as_returned yielded_namespace = nil returned_namespace = @tm.in_namespace("x") do |ns| yielded_namespace = ns end assert_equal returned_namespace, yielded_namespace end def test_name_lookup_with_implicit_file_tasks FileUtils.touch 'README.rdoc' t = @tm["README.rdoc"] assert_equal "README.rdoc", t.name assert Rake::FileTask === t end def test_name_lookup_with_nonexistent_task assert_raises(RuntimeError) { @tm["DOES NOT EXIST"] } end def test_name_lookup_in_multiple_scopes aa = nil bb = nil xx = @tm.define_task(Rake::Task, :xx) top_z = @tm.define_task(Rake::Task, :z) @tm.in_namespace("a") do aa = @tm.define_task(Rake::Task, :aa) mid_z = @tm.define_task(Rake::Task, :z) @tm.in_namespace("b") do bb = @tm.define_task(Rake::Task, :bb) bot_z = @tm.define_task(Rake::Task, :z) assert_equal ["a", "b"], @tm.current_scope assert_equal bb, @tm["a:b:bb"] assert_equal aa, @tm["a:aa"] assert_equal xx, @tm["xx"] assert_equal bot_z, @tm["z"] assert_equal mid_z, @tm["^z"] assert_equal top_z, @tm["^^z"] assert_equal top_z, @tm["rake:z"] end assert_equal ["a"], @tm.current_scope assert_equal bb, @tm["a:b:bb"] assert_equal aa, @tm["a:aa"] assert_equal xx, @tm["xx"] assert_equal bb, @tm["b:bb"] assert_equal aa, @tm["aa"] assert_equal mid_z, @tm["z"] assert_equal top_z, @tm["^z"] assert_equal top_z, @tm["rake:z"] end assert_equal [], @tm.current_scope assert_equal [], xx.scope assert_equal ['a'], aa.scope assert_equal ['a', 'b'], bb.scope end def test_lookup_with_explicit_scopes t1, t2, t3, s = (0...4).collect { nil } t1 = @tm.define_task(Rake::Task, :t) @tm.in_namespace("a") do t2 = @tm.define_task(Rake::Task, :t) s = @tm.define_task(Rake::Task, :s) @tm.in_namespace("b") do t3 = @tm.define_task(Rake::Task, :t) end end assert_equal t1, @tm[:t, []] assert_equal t2, @tm[:t, ["a"]] assert_equal t3, @tm[:t, ["a", "b"]] assert_equal s, @tm[:s, ["a", "b"]] assert_equal s, @tm[:s, ["a"]] end def test_correctly_scoped_prerequisites_are_invoked values = [] @tm = Rake::Application.new @tm.define_task(Rake::Task, :z) do values << "top z" end @tm.in_namespace("a") do @tm.define_task(Rake::Task, :z) do values << "next z" end @tm.define_task(Rake::Task, :x => :z) end @tm["a:x"].invoke assert_equal ["next z"], values end end
25.120253
64
0.613757
4ac7e593dd043080d47cf894c7b69d44b4d46631
10,348
# -*- coding: utf-8 -*- #-- # Copyright (C) 2004 Mauricio Julio Fernández Pradier # See LICENSE.txt for additional licensing information. #++ require 'zlib' require 'gems/security' class Gems::Package class Error < Gems::Error; end class FormatError < Error attr_reader :path def initialize(message, path = nil) @path = path message << " in #{path}" if path super message end end class PathError < Error def initialize(destination, destination_dir) super "installing into parent path %s of %s is not allowed" % [destination, destination_dir] end end class NonSeekableIO < Error; end class TooLongFileName < Error; end ## # Raised when a tar file is corrupt class TarInvalidError < Error; end ## # The files in this package. This is not the contents of the gem, just the # files in the top-level container. attr_reader :files ## # The security policy used for verifying the contents of this package. attr_accessor :security_policy ## # Sets the Gem::Specification to use to build this package. attr_writer :spec def self.build(spec) gem_file = spec.file_name package = new gem_file package.spec = spec package.build gem_file end ## # Creates a new Gem::Package for the file at +gem+. # # If +gem+ is an existing file in the old format a Gem::Package::Old will be # returned. def self.new(gem) return super unless Gems::Package == self return super unless File.exist? gem start = File.read gem, 20 return super unless start return super unless start.include? 'MD5SUM =' Gem::Package::Old.new gem end ## # Creates a new package that will read or write to the file +gem+. def initialize(gem) # :notnew: @gem = gem @contents = nil @digest = Gems::Security::DIGEST_ALGORITHM @files = nil @security_policy = nil @spec = nil @signer = nil end ## # Adds the files listed in the packages's Gem::Specification to data.tar.gz # and adds this file to the +tar+. def add_contents(tar) # :nodoc: tar.add_file_signed 'data.tar.gz', 0444, @signer do |io| Zlib::GzipWriter.wrap io do |gz_io| Gems::Package::TarWriter.new gz_io do |data_tar| add_files data_tar end end end end ## # Adds files included the package's Gem::Specification to the +tar+ file def add_files(tar) # :nodoc: @spec.files.each do |file| stat = File.stat file tar.add_file_simple file, stat.mode, stat.size do |dst_io| open file, 'rb' do |src_io| dst_io.write src_io.read 16384 until src_io.eof? end end end end ## # Adds the package's Gem::Specification to the +tar+ file def add_metadata(tar) # :nodoc: metadata = @spec.to_yaml metadata_gz = Gem.gzip metadata tar.add_file_signed 'metadata.gz', 0444, @signer do |io| io.write metadata_gz end end ## # Builds this package based on the specification set by #spec= def build @spec.validate @spec.mark_version if @spec.signing_key then @signer = Gem::Security::Signer.new @spec.signing_key, @spec.cert_chain @spec.signing_key = nil @spec.cert_chain = @signer.cert_chain.map { |cert| cert.to_s } else @signer = Gem::Security::Signer.new nil, nil @spec.cert_chain = @signer.cert_chain.map { |cert| cert.to_pem } if @signer.cert_chain end with_destination @gem do |gem_io| Gems::Package::TarWriter.new gem_io do |gem| add_metadata gem add_contents gem end end say <<-EOM Successfully built RubyGem Name: #{@spec.name} Version: #{@spec.version} File: #{File.basename @spec.cache_file} EOM ensure @signer = nil end ## # A list of file names contained in this gem def contents return @contents if @contents verify unless @spec @contents = [] read_io do |io| gem_tar = Gems::Package::TarReader.new io gem_tar.each do |entry| next unless entry.full_name == 'data.tar.gz' open_tar_gz entry do |pkg_tar| pkg_tar.each do |contents_entry| @contents << contents_entry.full_name end end return @contents end end end ## # Creates a digest of the TarEntry +entry+ from the digest algorithm set by # the security policy. def digest entry # :nodoc: digester = @digest.new digester << entry.read(16384) until entry.eof? entry.rewind digester end ## # Extracts the files in this package into +destination_dir+ def extract_files(destination_dir) verify unless @spec FileUtils.mkdir_p destination_dir read_io do |io| reader = Gems::Package::TarReader.new io reader.each do |entry| next unless entry.full_name == 'data.tar.gz' extract_tar_gz entry, destination_dir return # ignore further entries end end end ## # Extracts all the files in the gzipped tar archive +io+ into # +destination_dir+. # # If an entry in the archive contains a relative path above # +destination_dir+ or an absolute path is encountered an exception is # raised. def extract_tar_gz(io, destination_dir) # :nodoc: open_tar_gz io do |tar| tar.each do |entry| destination = install_location entry.full_name, destination_dir prepare_destination destination with_destination destination, entry.header.mode do |out| out.write entry.read out.fsync rescue nil # for filesystems without fsync(2) end end end end ## # Returns the full path for installing +filename+. # # If +filename+ is not inside +destination_dir+ an exception is raised. def install_location(filename, destination_dir) # :nodoc: raise Gems::Package::PathError.new(filename, destination_dir) if filename.start_with? '/' destination = File.join destination_dir, filename destination = File.expand_path destination #raise Gem::Package::PathError.new(destination, destination_dir) unless #destination.start_with? destination_dir destination.untaint destination end ## # Loads a Gem::Specification from the TarEntry +entry+ def load_spec entry # :nodoc: case entry.full_name when 'metadata' then @spec = Gem::Specification.from_yaml entry.read when 'metadata.gz' then args = [entry] args << { :external_encoding => Encoding::UTF_8 } if Object.const_defined? :Encoding # TODO: Decouple from Rubygems if possible Zlib::GzipReader.wrap(*args) do |gzio| @spec = Gem::Specification.from_yaml gzio.read end end end ## # Opens +io+ as a gzipped tar archive def open_tar_gz(io) # :nodoc: Zlib::GzipReader.wrap io do |gzio| tar = Gems::Package::TarReader.new gzio yield tar end end ## # The spec for this gem. # # If this is a package for a built gem the spec is loaded from the # gem and returned. If this is a package for a gem being built the provided # spec is returned. def spec verify unless @spec @spec end ## # Verifies that this gem: # # * Contains a valid gem specification # * Contains a contents archive # * The contents archive is not corrupt # # After verification the gem specification from the gem is available from # #spec def verify @files = [] @spec = nil digests = {} signatures = {} checksums = {} read_io do |io| reader = Gems::Package::TarReader.new io reader.each do |entry| file_name = entry.full_name @files << file_name case file_name when /\.sig$/ then signatures[$`] = entry.read if @security_policy next when /\.sum$/ then checksums[$`] = entry.read next else digests[file_name] = digest entry end case file_name when /^metadata(.gz)?$/ then load_spec entry when 'data.tar.gz' then verify_gz entry end end end unless @spec then raise Gems::Package::FormatError.new 'package metadata is missing', @gem end unless @files.include? 'data.tar.gz' then raise Gems::Package::FormatError.new \ 'package content (data.tar.gz) is missing', @gem end verify_checksums digests, checksums @security_policy.verify_signatures @spec, digests, signatures if @security_policy true rescue Errno::ENOENT => e raise Gems::Package::FormatError.new e.message rescue Gems::Package::TarInvalidError => e raise Gems::Package::FormatError.new e.message, @gem end ## # Verifies that +entry+ is a valid gzipped file. def verify_gz entry # :nodoc: Zlib::GzipReader.wrap entry do |gzio| gzio.read 16384 until gzio.eof? # gzip checksum verification end rescue Zlib::GzipFile::Error => e raise Gems::Package::FormatError.new(e.message, entry.full_name) end ## # Verifies the +checksums+ against the +digests+. This check is not # cryptographically secure. Missing checksums are ignored. def verify_checksums digests, checksums # :nodoc: checksums.sort.each do |name, checksum| digest = digests[name] checksum =~ /#{digest.name}\t(.*)/ unless digest.hexdigest == $1 then raise Gems::Package::FormatError.new("checksum mismatch for #{name}", @gem) end end end # abstract the rest of the code from the file system so regular I/O can be used def read_io if @io @io.rewind yield @io return end open @gem, 'rb' do |io| @io = StringIO.new(io.read, "rb") yield @io end end def prepare_destination(destination) FileUtils.rm_rf destination FileUtils.mkdir_p File.dirname(destination) end def with_destination(destination, permissions=nil) open destination, 'wb', permissions do |out| yield out end end end require 'gems/package/digest_io' require 'gems/package/old' require 'gems/package/tar_header' require 'gems/package/tar_reader' require 'gems/package/tar_reader/entry' require 'gems/package/tar_writer'
22.995556
81
0.645149
bf1dcdf61aa09f474cc83882f67921cc1d86dd18
111
class PlanBilling < ActiveRecord::Base belongs_to :data_plan belongs_to :music_plan belongs_to :user end
18.5
38
0.792793
accbbcf3f12be0f5200ffb573743f27d2debfd59
1,751
require 'test_helper' class UsersEditTest < ActionDispatch::IntegrationTest def setup @user = users(:michael) end test "unsuccessful edit" do log_in_as(@user) get edit_user_path(@user) patch user_path(@user), params: { user: { name: "", email: "foo@invalid", password: "foo", password_confirmation: "bar" } } assert_template 'users/edit' end test "successful edit" do log_in_as(@user) get edit_user_path(@user) assert_template 'users/edit' name = "Foo Bar" email = "[email protected]" patch user_path(@user), params: { user: { name: name, email: email, password: "", password_confirmation: "" } } assert_not flash.empty? assert_redirected_to @user @user.reload assert_equal name, @user.name assert_equal email, @user.email end test "successful edit with friendly forwarding" do get edit_user_path(@user) log_in_as(@user) assert_redirected_to edit_user_url(@user) name = "Foo Bar" email = "[email protected]" patch user_path(@user), params: { user: { name: name, email: email, password: "", password_confirmation: "" } } assert_not flash.empty? assert_redirected_to @user @user.reload assert_equal name, @user.name assert_equal email, @user.email end end
33.037736
78
0.499714
bb792b2b1c4afaf578ae8649deabc483a76f7f11
1,033
require 'spec_helper' describe Puppet::Type.type(:package).provider(:pip3) do it { is_expected.to be_installable } it { is_expected.to be_uninstallable } it { is_expected.to be_upgradeable } it { is_expected.to be_versionable } it { is_expected.to be_install_options } it { is_expected.to be_targetable } it "should inherit most things from pip provider" do expect(described_class < Puppet::Type.type(:package).provider(:pip)) end it "should use pip3 command" do expect(described_class.cmd).to eq(["pip3"]) end context 'calculated specificity' do include_context 'provider specificity' context 'when is not defaultfor' do subject { described_class.specificity } it { is_expected.to eql 1 } end context 'when is defaultfor' do let(:os) { Puppet.runtime[:facter].value(:operatingsystem) } subject do described_class.defaultfor(operatingsystem: os) described_class.specificity end it { is_expected.to be > 100 } end end end
26.487179
72
0.698935
878d63e275a4d52575ab1a91e2009d0458653c31
1,327
Given(/^I am on the cabinet page$/) do @cabinet_page.visit_home_page end When(/^I start typing a medication name$/) do @cabinet_page.type_search_characters(@medication) end Then(/^I should see the medication in the list$/) do expect(@medication).to eq(@cabinet_page.autocomplete_text) end When(/^I select that medication$/) do @cabinet_page.select_autocomplete_text(@cabinet_page.autocomplete_text) @cabinet_page.press_add_button end Then(/^I should see the medication in my cabinet$/) do assert_selector '.pill-name', text: @medication end Then(/^I see the medicine's description$/) do expect(@med_description.has_text?).to be_truthy end And(/^I see dosage information for the medicine$/) do expect(@med_dosage.has_text?).to be_truthy end And(/^I see warning information for the medicine$/) do wait_for_ajax expect(@med_warnings.has_text?).to be_truthy end When(/^I enter an incorrect search term$/) do @incorrect_term = 'not found' @cabinet_page.type_search_characters(@incorrect_term) @cabinet_page.press_add_button end Then(/^I receive an error message letting me know that I need to try a different search$/) do error_message = "Could not find results for '#{@incorrect_term}', please try again." expect(error_message).to eq(find('#error-message-container .error-message').text) end
29.488889
93
0.762622
91b7f307488dd6c38959cb77afdfeabd642c58f0
690
# frozen_string_literal: true module ActiveRecord module Embedded class Aggregation # Driver for JSON/JSONB query support in PostgreSQL. Uses a +@>+ # query to look for partial JSON in the +data+ Array. class Postgresql < Aggregation delegate :any?, :empty?, to: :results def results criteria = parent.where("#{as} @> ?", params) criteria = criteria.offset(from) unless from.zero? criteria = criteria.limit(to) unless to == -1 criteria.map { |record| [record, query_for(record)] } end private def params { data: [filters] }.to_json end end end end end
25.555556
70
0.592754
1da30dd65885ccba8d22c082616e179a9c688a84
829
Pod::Spec.new do |s| s.name = "Device" s.version = "2.0.0" s.summary = "Light weight tool for detecting the current device and screen size written in swift." s.description = "Swift library for detecting the running device's model and screen size. With the newer  devices, developers have more work to do. This library simplifies their job by allowing them to get information about the running device and easily target the ones they want." s.homepage = "https://github.com/Ekhoo/Device" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "Lucas Ortis" => "[email protected]" } s.platform = :ios, "8.0" s.source = { :git => "https://github.com/Ekhoo/Device.git", :tag => s.version.to_s } s.source_files = "Source/*.swift" s.requires_arc = true end
51.8125
284
0.6538
79d637e5e13e3fcbb096015ef9bbc6855f35fc61
3,049
# frozen_string_literal: true require 'test_helper' class ActsAsEditable::ActsAsEditableTest < ActiveSupport::TestCase it 'edits get created on new project' do project = create(:project, name: 'Foo', description: 'Best of projects!', created_at: Time.current) _(CreateEdit.where(target: project).count).must_equal 1 _(PropertyEdit.where(target: project, key: 'name', value: 'Foo').count).must_equal 1 _(PropertyEdit.where(target: project, key: 'description', value: 'Best of projects!').count).must_equal 1 _(PropertyEdit.where(target: project, key: 'updated_at').count).must_equal 0 end it 'edits get their property edits merged if they are recent to one another' do project = create(:project, name: 'Foobar') project.update(name: 'Goobaz') _(PropertyEdit.where(target: project, key: 'name', value: 'Foobar').count).must_equal 0 _(PropertyEdit.where(target: project, key: 'name', value: 'Goobaz').count).must_equal 1 end it 'edits do not get their property edits merged if they are not recent to one another' do long_ago = Time.current - 5.days Time.stubs(:now).returns long_ago project = create(:project, name: 'Foobar') Time.unstub(:now) project.update(name: 'Goobaz') _(PropertyEdit.where(target: project, key: 'name', value: 'Foobar').count).must_equal 1 _(PropertyEdit.where(target: project, key: 'name', value: 'Goobaz').count).must_equal 1 end it 'edits do not get their property edits merged if they are not by the same editor' do project = create(:project, name: 'Foobar') project.editor_account = create(:account) project.update(name: 'Goobaz') _(PropertyEdit.where(target: project, key: 'name', value: 'Foobar').count).must_equal 1 _(PropertyEdit.where(target: project, key: 'name', value: 'Goobaz').count).must_equal 1 end it 'destroy does not delete from db and undoes the CreateEdit' do project = create(:project, name: 'Foobar') project.destroy project = Project.where(id: project.id).first _(project.deleted).must_equal true _(CreateEdit.where(target: project).first.undone).must_equal true end it 'destroy errors with no editor' do project = create(:project, name: 'Foobar') project = Project.where(id: project.id).first _(proc { project.destroy }).must_raise ActsAsEditable::NoEditorAccountError _(project.deleted).must_equal false _(CreateEdit.where(target: project).first.undone).must_equal false end it 'must record edits for custom attributes' do project = create(:project, organization: nil) _(PropertyEdit.where(key: %w[tag_list url], target: project).count).must_equal 0 edits_count = PropertyEdit.where(target: project).count project.update(tag_list: Faker::Lorem.words.join(' '), url: Faker::Internet.url) _(PropertyEdit.where(target: project).count).must_equal edits_count + 2 _(PropertyEdit.where(key: 'tag_list', target: project).count).must_equal 1 _(PropertyEdit.where(key: 'url', target: project).count).must_equal 1 end end
45.507463
109
0.718268
ab790a8c537a81b9f7b364beb34aca7e5ff9f724
5,741
class Checkov < Formula include Language::Python::Virtualenv desc "Shiny new formula" homepage "https://github.com/bridgecrewio/checkov" url "https://files.pythonhosted.org/packages/d1/8d/fb9815b10cc6af4e8eacfcfed6312bec8b5a1aca9a00d76b8eb9b27fd761/checkov-1.0.303.tar.gz" sha256 "0aa2c9f63d63146d33a02f33b0fff0c8ddfebc5b05e59bb07cc75621363fe31c" depends_on "python3" resource "boto3" do url "https://files.pythonhosted.org/packages/ad/08/0d977abed3d7adbd7158ffc1027c63e56381877e7442b06c7a849cb4cc1f/boto3-1.12.43.tar.gz" sha256 "1a6a3d95d20cacd677e2af5cbff7027abea35b78f1b8126388ef7fa517655cfe" end resource "botocore" do url "https://files.pythonhosted.org/packages/0c/47/b88dcace59102cffe24e4b2d15f6c7b60df8ee79f82e9c2264d5c90a3c01/botocore-1.15.49.tar.gz" sha256 "a474131ba7a7d700b91696a27e8cdcf1b473084addf92f90b269ebd8f5c3d3e0" end resource "certifi" do url "https://files.pythonhosted.org/packages/b8/e2/a3a86a67c3fc8249ed305fc7b7d290ebe5e4d46ad45573884761ef4dea7b/certifi-2020.4.5.1.tar.gz" sha256 "51fcb31174be6e6664c5f69e3e1691a2d72a1a12e90f872cbdb1567eb47b6519" end resource "chardet" do url "https://files.pythonhosted.org/packages/fc/bb/a5768c230f9ddb03acc9ef3f0d4a3cf93462473795d18e9535498c8f929d/chardet-3.0.4.tar.gz" sha256 "84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae" end resource "colorama" do url "https://files.pythonhosted.org/packages/82/75/f2a4c0c94c85e2693c229142eb448840fba0f9230111faa889d1f541d12d/colorama-0.4.3.tar.gz" sha256 "e96da0d330793e2cb9485e9ddfd918d456036c7149416295932478192f4436a1" end resource "docopt" do url "https://files.pythonhosted.org/packages/a2/55/8f8cab2afd404cf578136ef2cc5dfb50baa1761b68c9da1fb1e4eed343c9/docopt-0.6.2.tar.gz" sha256 "49b3a825280bd66b3aa83585ef59c4a8c82f2c8a522dbe754a8bc8d08c85c491" end resource "docutils" do url "https://files.pythonhosted.org/packages/93/22/953e071b589b0b1fee420ab06a0d15e5aa0c7470eb9966d60393ce58ad61/docutils-0.15.2.tar.gz" sha256 "a2aeea129088da402665e92e0b25b04b073c04b2dce4ab65caaa38b7ce2e1a99" end resource "dpath" do url "https://files.pythonhosted.org/packages/88/b2/abc5803f37a2ea1045d68765acfcb4ec166bc9e08c3ba451c53af29a73f2/dpath-1.5.0.tar.gz" sha256 "496615b4ea84236d18e0d286122de74869a60e0f87e2c7ec6787ff286c48361b" end resource "idna" do url "https://files.pythonhosted.org/packages/ad/13/eb56951b6f7950cadb579ca166e448ba77f9d24efc03edd7e55fa57d04b7/idna-2.8.tar.gz" sha256 "c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407" end resource "jmespath" do url "https://files.pythonhosted.org/packages/3c/56/3f325b1eef9791759784aa5046a8f6a1aff8f7c898a2e34506771d3b99d8/jmespath-0.10.0.tar.gz" sha256 "b85d0567b8666149a93172712e68920734333c0ce7e89b78b3e987f71e5ed4f9" end resource "junit-xml" do url "https://files.pythonhosted.org/packages/a6/2a/f8d5aab80bb31fcc789d0f2b34b49f08bd6121cd8798d2e37f416df2b9f8/junit-xml-1.8.tar.gz" sha256 "602f1c480a19d64edb452bf7632f76b5f2cb92c1938c6e071dcda8ff9541dc21" end resource "lark-parser" do url "https://files.pythonhosted.org/packages/34/b8/aa7d6cf2d5efdd2fcd85cf39b33584fe12a0f7086ed451176ceb7fb510eb/lark-parser-0.7.8.tar.gz" sha256 "26215ebb157e6fb2ee74319aa4445b9f3b7e456e26be215ce19fdaaa901c20a4" end resource "python-dateutil" do url "https://files.pythonhosted.org/packages/be/ed/5bbc91f03fa4c839c4c7360375da77f9659af5f7086b7a7bdda65771c8e0/python-dateutil-2.8.1.tar.gz" sha256 "73ebfe9dbf22e832286dafa60473e4cd239f8592f699aa5adaf10050e6e1823c" end resource "python-hcl2" do url "https://files.pythonhosted.org/packages/cf/3f/3ff50ca76d5a44a7043b791d3876b5e693b6a2f64db832539e3f162e8323/python-hcl2-0.2.5.tar.gz" sha256 "51a9c7e41929a440daf0e8b9a153e3afb7d0628b10c536a656ea95f87a5fe1f6" end resource "PyYAML" do url "https://files.pythonhosted.org/packages/8d/c9/e5be955a117a1ac548cdd31e37e8fd7b02ce987f9655f5c7563c656d5dcb/PyYAML-5.2.tar.gz" sha256 "c0ee8eca2c582d29c3c2ec6e2c4f703d1b7f1fb10bc72317355a746057e7346c" end resource "requests" do url "https://files.pythonhosted.org/packages/01/62/ddcf76d1d19885e8579acb1b1df26a852b03472c0e46d2b959a714c90608/requests-2.22.0.tar.gz" sha256 "11e007a8a2aa0323f5a921e9e6a2d7e4e67d9877e85773fba9ba6419025cbeb4" end resource "s3transfer" do url "https://files.pythonhosted.org/packages/50/de/2b688c062107942486c81a739383b1432a72717d9a85a6a1a692f003c70c/s3transfer-0.3.3.tar.gz" sha256 "921a37e2aefc64145e7b73d50c71bb4f26f46e4c9f414dc648c6245ff92cf7db" end resource "six" do url "https://files.pythonhosted.org/packages/94/3e/edcf6fef41d89187df7e38e868b2dd2182677922b600e880baad7749c865/six-1.13.0.tar.gz" sha256 "30f610279e8b2578cab6db20741130331735c781b56053c59c4076da27f06b66" end resource "tabulate" do url "https://files.pythonhosted.org/packages/c4/41/523f6a05e6dc3329a5660f6a81254c6cd87e5cfb5b7482bae3391d86ec3a/tabulate-0.8.6.tar.gz" sha256 "5470cc6687a091c7042cee89b2946d9235fe9f6d49c193a4ae2ac7bf386737c8" end resource "termcolor" do url "https://files.pythonhosted.org/packages/8a/48/a76be51647d0eb9f10e2a4511bf3ffb8cc1e6b14e9e4fab46173aa79f981/termcolor-1.1.0.tar.gz" sha256 "1d6d69ce66211143803fbc56652b41d73b4a400a2891d7bf7a1cdf4c02de613b" end resource "urllib3" do url "https://files.pythonhosted.org/packages/ad/fc/54d62fa4fc6e675678f9519e677dfc29b8964278d75333cf142892caf015/urllib3-1.25.7.tar.gz" sha256 "f3c5fd51747d450d4dcf6f923c81f78f811aab8205fda64b0aba34a4e48b0745" end def install virtualenv_create(libexec, "python3") virtualenv_install_with_resources end test do false end end
45.928
145
0.826859
08abb9cdb8369a35779e88a7ccb87bfd639dd2d7
2,820
require 'spec_helper' require 'mail' require 'mandrails/message_builder' describe Mandrails::MessageBuilder do include Factories::Emails subject { described_class.new(text_mail).as_json } context 'subject' do it 'sets :subject' do subject[:subject].should == 'Hi' end end context 'recipients' do it 'sets :to Array' do subject[:to].should == [{ email: "[email protected]", name: "[email protected]" }] end context 'To, Cc & Bcc' do subject { described_class.new(cc_mail).as_json } it 'sets :to by combining To & Cc' do subject[:to].should == [{ email: "[email protected]", name: "[email protected]" }, { email: "[email protected]", name: "[email protected]" }] end end end context 'from' do it 'sets :from_email and :from_name' do subject[:from_email].should == '[email protected]' subject[:from_name].should be_nil end it 'sets :from_name based on header' do text_mail[:from_name] = 'Mila' subject[:from_name].should == 'Mila' end context 'with default from_name & from_email' do subject { described_class.new(text_mail, from_name: "App", from_mail: "[email protected]").as_json } it 'sets :from_name from default' do subject[:from_name].should == 'App' end end end context 'body' do context 'text only mail' do subject { described_class.new(text_mail).as_json } it 'sets :html key to nil' do subject[:html].should be_nil end it 'sets :text' do subject[:text].should == 'Yoo buddy' end end context 'html only mail' do subject { described_class.new(html_mail).as_json } it 'sets :html' do subject[:html].should == '<b>Yoo</b> buddy' end it 'sets :text to nil' do subject[:text].should be_nil end end context 'multipart mail' do subject { described_class.new(multipart_mail).as_json } it 'sets :html' do subject[:html].should == '<b>Yoo</b> buddy' end it 'sets :text' do subject[:text].should == 'Yoo buddy' end end end context 'attachments' do subject { described_class.new(attachment_mail).as_json } it 'sets :text' do subject[:text].should == 'Yooo with attachment' end it 'has two attachments' do subject[:attachments].length.should == 2 end context 'first attachment (pdf)' do subject { described_class.new(attachment_mail).as_json[:attachments].first } it 'has :type as application/pdf' do subject[:type].should == 'application/pdf' end it 'has :name' do subject[:name].should == 'file.pdf' end it 'has Base64 encoded :content' do subject[:content].should == 'UERGIEZJTEUgQlJPIQ==' end end end end
24.310345
131
0.613475
7a268b1cd721687f4905e0cb83c07ea737043ef4
6,691
# encoding: utf-8 require 'tabula' require 'date' module Evacuees class PDFExtractor attr_reader :path, :title, :date, :header, :body def initialize(path, range = nil) @path = path @range = range || 3..5 end def extract caption, raw_body = TabulaWrapper.new(@path, @range).extract @title = parse_title(caption) @date = parse_date(@title) @header = select_header(@date) @body = refine_rows(raw_body) self end private def parse_title(text) text[/(所在都道府県別の避難者等の数(平成.{2}年.{1,2}月.{1,2}日現在))/] end def parse_date(text) # 1. Extract the zenkaku Heisei year, month, and day. # 2. Transpose the zenkaku numbers with their single-byte counterparts. # 3. Split the extracted date into an array at the year and month kanji. # 4. Comvert the Heisei year to a Gregorian year. # 5. Zero pad the month and day. # 6. Join the date array into a string with a '-' separator. date_string = text[/.{2}年.{1,2}月.{1,2}/] .tr('0-9', '0-9') .split(/[年月]/) .map.with_index { |column, index| index == 0 ? column.to_i + 1988 : column } .map.with_index { |column, index| index == 0 ? column : column.rjust(2, '0') } .join('-') Date.parse(date_string) end def select_header(date) original_header = [ "都道府県コード", "都道府県名", "避難所(公民館、学校等)", "旅館・ホテル", "その他(親族・知人宅等)", "住宅等(公営、仮設、民間、病院含む)", "計", "所在判明市区町村数", "注釈", "年月日" ] new_header = [ "都道府県コード", "都道府県名", "住宅等市区町村数(公営、応急仮設、民間賃貸等)", "親族・知人宅等", "病院等", "計", "所在判明市区町村数", "注釈", "年月日" ] @date < Date.new(2014,2,13) ? original_header : new_header end def refine_rows(rows) #-- # TODO: Break this up into more easily read parts. #++ row_count = 47 # Clean the extracted rows. rows.map! do |row| # 1. Transpose zenkaku characters with their single-byte counterparts. # 2. Remove carriage returns, white space, and commas. # 3. Delete empty columns. # 4. Insert a space between a number and a footnote or # calculated change in evacuees. # 5. Insert a space between a number and a prefecture name. # 6. Replace missing data columns with 'NA'. row.map { |column| column.tr('()+-ー,0-9 ', '()+\-—,0-9 ') } .map { |column| column.gsub(/[\r\s,]/, '') } .reject { |column| column.empty? } .map { |column| column.gsub(/([0-9])(\()/, '\1 \2') } .map { |column| column.gsub(/^([0-9]{1,2})(\W{2,3}[都道府県]$)/, '\1 \2') } .map { |column| column.gsub(/^[-—]$/, 'NA')} end # Delete header and total rows. #-- # TODO: Consistently extract table headers. #++ rows.reject! { |row| row.first.match(/^[0-9]{1,2}\s\W{2,3}[都道府県]$/).nil? } # Delete the subtotal column (included in tables before 2011-11-17). rows.each { |row| row.delete_at(4) } if date < Date.new(2011,11,17) # Transform the cleaned rows. rows.map! do |row| notes = [] # 1. Delete calculated changes in evacuees. # 2. Transform prefecture numbers and footnotes into columns. # 3. Delete empty columns. # 5. Insert each footnote column into a temporary array. # 5. Delete footnote columns. # 6. Insert a new footnotes column at the end of the row. row.map { |column| column.gsub(/\s\([0\+\-]([^\)]+)?\)/, '') } .map { |column| column.split(/[\s\(\)]/) }.flatten .reject { |column| column.empty? } .each { |column| notes << column if /[*※]/ =~ column } .reject { |column| /[*※]/.match(column) } .push(notes.empty? ? 'NA' : notes.join(' ')) end # Transform prefecture numbers into ISO 3166-2 codes. rows.each { |row| row.first.replace(['JP-', row.first.rjust(2, '0')].join('')) } # Tranform number strings into numbers. rows.map! { |row| row.map { |column| /^[0-9]+$/ =~ column ? column.to_i : column } } # Add the date to each row. rows.map! { |row| row.push(@date.to_s) } # Validate the number of rows in the table. if row_count != rows.length raise(StandardError, "Counted #{rows.length} rows, expected #{row_count}") end # Validate the number of columns in each row. rows.each do |row| if header.length != row.length raise(StandardError, "Counted #{row.length} columns, expected #{header.length}") end end rows end TabulaWrapper = Struct.new(:path, :range) do def extract pages = Tabula::Extraction::ObjectExtractor.new(path, range).extract if pages.first.spreadsheets.empty? raise(StandardError, "#{path.split('/').last} has no extractable text") end caption = extract_caption(pages.first) rows = extract_table(pages) [caption, rows] end def horizontal_lines(page) page.spreadsheets.first.horizontal_ruling_lines end def extract_caption(page) page_top = 0 page_left = 0 page_bottom = 842 # A4 height page_right = 595 # A4 width # Offset the top of the caption area to exclude the page number. caption_area_top = 45 # Set the bottom of the extractor to the top of the table. caption_area_bottom = horizontal_lines(page)[0].to_json({}).split(',').last.to_f # 1. Extract the caption text. # 2. Replace each element with its text value, a character. # 3. Delete empty elements (spaces). # 4. Join the character array into a string with no separator. page.get_text([caption_area_top, page_left, caption_area_bottom, page_right]) .map { |element| element.text.strip } .reject { |element| element.empty? } .join('') end def extract_table(pages) page_top = 0 page_left = 0 page_bottom = 842 # A4 height page_right = 595 # A4 width rows = [] # Extract the table rows from each extracted page. pages.each do |page| # Offset the top of the table to exclude the problematic # merged columns in the header row. table_area_top = horizontal_lines(page)[1].to_json({}).split(',').last.to_f rows.push(*page.get_area([table_area_top, page_left, page_bottom, page_right]).spreadsheets.first.to_a) end rows end end end end
31.413146
113
0.56703
088570bd5aed56dde548b6e3c2bef91b07c35fbd
419
require "delegated_presenter/version" require 'delegate' require "active_support/concern" require "active_support/dependencies/autoload" require "active_support/core_ext/module/delegation" require "active_support/inflector" module DelegatedPresenter extend ActiveSupport::Autoload autoload :Base autoload :Error autoload :PresentsBeforeRendering end require 'delegated_presenter/railtie' if defined?(Rails)
23.277778
56
0.832936
1895f4a2bc2c4060fb7dda94bf0cbeba9c3c8513
4,359
require "language/haskell" class Agda < Formula include Language::Haskell::Cabal desc "Dependently typed functional programming language" homepage "https://wiki.portal.chalmers.se/agda/" stable do url "https://hackage.haskell.org/package/Agda-2.6.0/Agda-2.6.0.tar.gz" sha256 "bf71bc634a9fe40d717aae76b5b160dfd13a06365615e7822043e5d476c06fb8" resource "stdlib" do url "https://github.com/agda/agda-stdlib.git", :tag => "v1.0.1", :revision => "442abf2b3418d4d488381a2f8ca4e99bbf8cfc8e" end end bottle do sha256 "33438627ea54c158323b499f5cff0acb0fcdb1498ed46709254182d3926c99a8" => :mojave sha256 "8e41acf29ecb3319d8ef00b77de952cfccafef87bf705bc32c1837073ce62acb" => :high_sierra sha256 "a49f81d7e0f49023a23067d0e496e2a387258d91820f23838f2ef804bea86714" => :sierra end head do url "https://github.com/agda/agda.git" resource "stdlib" do url "https://github.com/agda/agda-stdlib.git" end end depends_on "cabal-install" => [:build, :test] depends_on "emacs" depends_on "ghc" def install # install Agda core install_cabal_package :using => ["alex", "happy", "cpphs"] resource("stdlib").stage lib/"agda" # generate the standard library's bytecode cd lib/"agda" do cabal_sandbox :home => buildpath, :keep_lib => true do cabal_install "--only-dependencies" cabal_install system "GenerateEverything" end end # generate the standard library's documentation and vim highlighting files cd lib/"agda" do system bin/"agda", "-i", ".", "-i", "src", "--html", "--vim", "README.agda" end # compile the included Emacs mode system bin/"agda-mode", "compile" elisp.install_symlink Dir["#{share}/*/Agda-#{version}/emacs-mode/*"] end def caveats; <<~EOS To use the Agda standard library by default: mkdir -p ~/.agda echo #{HOMEBREW_PREFIX}/lib/agda/standard-library.agda-lib >>~/.agda/libraries echo standard-library >>~/.agda/defaults EOS end test do simpletest = testpath/"SimpleTest.agda" simpletest.write <<~EOS module SimpleTest where data ℕ : Set where zero : ℕ suc : ℕ → ℕ infixl 6 _+_ _+_ : ℕ → ℕ → ℕ zero + n = n suc m + n = suc (m + n) infix 4 _≡_ data _≡_ {A : Set} (x : A) : A → Set where refl : x ≡ x cong : ∀ {A B : Set} (f : A → B) {x y} → x ≡ y → f x ≡ f y cong f refl = refl +-assoc : ∀ m n o → (m + n) + o ≡ m + (n + o) +-assoc zero _ _ = refl +-assoc (suc m) n o = cong suc (+-assoc m n o) EOS stdlibtest = testpath/"StdlibTest.agda" stdlibtest.write <<~EOS module StdlibTest where open import Data.Nat open import Relation.Binary.PropositionalEquality +-assoc : ∀ m n o → (m + n) + o ≡ m + (n + o) +-assoc zero _ _ = refl +-assoc (suc m) n o = cong suc (+-assoc m n o) EOS iotest = testpath/"IOTest.agda" iotest.write <<~EOS module IOTest where open import Agda.Builtin.IO open import Agda.Builtin.Unit postulate return : ∀ {A : Set} → A → IO A {-# COMPILE GHC return = \\_ -> return #-} main : _ main = return tt EOS stdlibiotest = testpath/"StdlibIOTest.agda" stdlibiotest.write <<~EOS module StdlibIOTest where open import IO main : _ main = run (putStr "Hello, world!") EOS # typecheck a simple module system bin/"agda", simpletest # typecheck a module that uses the standard library system bin/"agda", "-i", lib/"agda"/"src", stdlibtest # compile a simple module using the JS backend system bin/"agda", "--js", simpletest # test the GHC backend cabal_sandbox do cabal_install "text", "ieee754" dbpath = Dir["#{testpath}/.cabal-sandbox/*-packages.conf.d"].first dbopt = "--ghc-flag=-package-db=#{dbpath}" # compile and run a simple program system bin/"agda", "-c", dbopt, iotest assert_equal "", shell_output(testpath/"IOTest") # compile and run a program that uses the standard library system bin/"agda", "-c", "-i", lib/"agda"/"src", dbopt, stdlibiotest assert_equal "Hello, world!", shell_output(testpath/"StdlibIOTest") end end end
27.24375
93
0.61872
1ab41c8cffdf4202669d72dd75e7eef235dcde07
1,581
require_relative 'lib/CLI_Data_Gem_pp/version' Gem::Specification.new do |spec| spec.name = "CLI_Data_Gem_pp" spec.version = CLIDataGemPp::VERSION spec.authors = ["Uchoosecode"] spec.email = ["[email protected]"] spec.summary = %q{Write a short summary, because RubyGems requires one.} spec.description = %q{Write a longer description or delete this line.} spec.homepage = "Put your gem's website or public repo URL here." spec.license = "MIT" spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0") spec.metadata["allowed_push_host"] = "Set to 'http://mygemserver.com'" spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = "Put your gem's public repo URL here." spec.metadata["changelog_uri"] = "Put your gem's CHANGELOG.md URL here." # # Specify which files should be added to the gem when it is released. # # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 2.0" spec.add_development_dependency "rake", "~> 12.0" spec.add_development_dependency "rspec", "~> 3.0" spec.add_development_dependency "pry" spec.add_dependency "rest-client" spec.add_dependency "json" end
42.72973
89
0.677419
389f862d6a95398694371eb5488e7d561e4e5b38
7,003
module ActiveMerchant #:nodoc: module Billing #:nodoc: class UsaEpayGateway < Gateway class_inheritable_accessor :test_url, :live_url self.live_url = 'https://www.usaepay.com/gate.php' self.test_url = 'https://sandbox.usaepay.com/gate.php' self.supported_cardtypes = [:visa, :master, :american_express] self.supported_countries = ['US'] self.homepage_url = 'http://www.usaepay.com/' self.display_name = 'USA ePay' TRANSACTIONS = { :authorization => 'authonly', :purchase => 'sale', :capture => 'capture' } def initialize(options = {}) requires!(options, :login) @options = options super end def authorize(money, credit_card, options = {}) post = {} add_amount(post, money) add_invoice(post, options) add_credit_card(post, credit_card) add_address(post, credit_card, options) add_customer_data(post, options) commit(:authorization, post) end def purchase(money, credit_card, options = {}) post = {} add_amount(post, money) add_invoice(post, options) add_credit_card(post, credit_card) add_address(post, credit_card, options) add_customer_data(post, options) commit(:purchase, post) end def capture(money, authorization, options = {}) post = { :refNum => authorization } add_amount(post, money) commit(:capture, post) end private def add_amount(post, money) post[:amount] = amount(money) end def expdate(credit_card) year = format(credit_card.year, :two_digits) month = format(credit_card.month, :two_digits) "#{month}#{year}" end def add_customer_data(post, options) address = options[:billing_address] || options[:address] || {} post[:street] = address[:address1] post[:zip] = address[:zip] if options.has_key? :email post[:custemail] = options[:email] post[:custreceipt] = 'No' end if options.has_key? :customer post[:custid] = options[:customer] end if options.has_key? :ip post[:ip] = options[:ip] end if options.has_key? :addcustomer post[:addcustomer] = 'yes' end if options.has_key? :schedule post[:schedule] = options[:schedule] end if options.has_key? :billsourcekey post[:billsourcekey] = 'yes' end end def add_address(post, credit_card, options) billing_address = options[:billing_address] || options[:address] add_address_for_type(:billing, post, credit_card, billing_address) if billing_address add_address_for_type(:shipping, post, credit_card, options[:shipping_address]) if options[:shipping_address] end def add_address_for_type(type, post, credit_card, address) prefix = address_key_prefix(type) post[address_key(prefix, 'fname')] = credit_card.first_name post[address_key(prefix, 'lname')] = credit_card.last_name post[address_key(prefix, 'company')] = address[:company] unless address[:company].blank? post[address_key(prefix, 'street')] = address[:address1] unless address[:address1].blank? post[address_key(prefix, 'street2')] = address[:address2] unless address[:address2].blank? post[address_key(prefix, 'city')] = address[:city] unless address[:city].blank? post[address_key(prefix, 'state')] = address[:state] unless address[:state].blank? post[address_key(prefix, 'zip')] = address[:zip] unless address[:zip].blank? post[address_key(prefix, 'country')] = address[:country] unless address[:country].blank? post[address_key(prefix, 'phone')] = address[:phone] unless address[:phone].blank? end def address_key_prefix(type) case type when :shipping then 'ship' when :billing then 'bill' end end def address_key(prefix, key) "#{prefix}#{key}".to_sym end def add_invoice(post, options) post[:invoice] = options[:order_id] end def add_credit_card(post, credit_card) post[:card] = credit_card.number post[:cvv2] = credit_card.verification_value if credit_card.verification_value? post[:expir] = expdate(credit_card) post[:name] = credit_card.name end def parse(body) fields = {} for line in body.split('&') key, value = *line.scan( %r{^(\w+)\=(.*)$} ).flatten fields[key] = CGI.unescape(value.to_s) end { :status => fields['UMstatus'], :auth_code => fields['UMauthCode'], :ref_num => fields['UMrefNum'], :batch => fields['UMbatch'], :avs_result => fields['UMavsResult'], :avs_result_code => fields['UMavsResultCode'], :cvv2_result => fields['UMcvv2Result'], :cvv2_result_code => fields['UMcvv2ResultCode'], :vpas_result_code => fields['UMvpasResultCode'], :result => fields['UMresult'], :error => fields['UMerror'], :error_code => fields['UMerrorcode'], :acs_url => fields['UMacsurl'], :payload => fields['UMpayload'], :customer_num => fields['UMcustnum'] }.delete_if{|k, v| v.nil?} end def commit(action, parameters) url = @options[:test] || test? ? self.test_url : self.live_url response = parse( ssl_post(url, post_data(action, parameters)) ) Response.new(response[:status] == 'Approved', message_from(response), response, :test => false, :authorization => response[:ref_num], :cvv_result => response[:cvv2_result_code], :avs_result => { :street_match => response[:avs_result_code].to_s[0,1], :postal_match => response[:avs_result_code].to_s[1,1], :code => response[:avs_result_code].to_s[2,1] } ) end def message_from(response) if response[:status] == "Approved" return 'Success' else return 'Unspecified error' if response[:error].blank? return response[:error] end end def post_data(action, parameters = {}) parameters[:command] = TRANSACTIONS[action] parameters[:key] = @options[:login] parameters[:software] = 'Active Merchant' parameters[:testmode] = 0 parameters.collect { |key, value| "UM#{key}=#{CGI.escape(value.to_s)}" }.join("&") end end end end
33.033019
116
0.571755
d513d0502937e1db474081e4bd67983dc5b202f2
2,043
# frozen_string_literal: true require 'spec_helper' require 'ttfunk/table/vorg' RSpec.describe TTFunk::Table::Vorg do let(:font_path) { test_font('NotoSansCJKsc-Thin', :otf) } let(:font) { TTFunk::File.open(font_path) } let(:cmap) { font.cmap.unicode.first } let(:vorg_table) { font.vertical_origins } let(:origins) { vorg_table.origins } describe '#origins' do it 'includes origins for certain chars traditionally written vertically' do code_points = %w[〱 0 1 2 3 4 5 6 7 8 9].map do |c| c.unpack1('U*') end glyph_ids = code_points.map { |cp| cmap[cp] } glyph_ids.each { |glyph_id| expect(origins).to include(glyph_id) } end end describe '#for' do it 'finds the vertical origin when explicitly available' do glyph_id = cmap['〱'.unpack1('U*')] expect(vorg_table.origins).to include(glyph_id) expect(vorg_table.for(glyph_id)).to_not( eq(vorg_table.default_vert_origin_y) ) end it 'falls back to the default vertical origin' do glyph_id = cmap['ろ'.unpack1('U*')] expect(vorg_table.origins).to_not include(glyph_id) expect(vorg_table.for(glyph_id)).to( eq(vorg_table.default_vert_origin_y) ) end end describe '.encode' do let(:encoded) { described_class.encode(vorg_table) } let(:reconstituted) do described_class.new(TestFile.new(StringIO.new(encoded))) end it 'includes all the same vertical origins' do expect(reconstituted.origins.size).to eq(origins.size) origins.each do |glyph_id, origin| expect(reconstituted.origins[glyph_id]).to eq(origin) end end it 'includes the same version information' do expect(reconstituted.major_version).to eq(vorg_table.major_version) expect(reconstituted.minor_version).to eq(vorg_table.minor_version) end it 'includes the same default vertical origin' do expect(reconstituted.default_vert_origin_y).to( eq(vorg_table.default_vert_origin_y) ) end end end
30.044118
79
0.68184
d5b974b2d31ba69d376fac3b5d421d34f1618a53
6,099
class Environment < ActiveRecord::Base # Used to generate random suffixes for the slug LETTERS = 'a'..'z' NUMBERS = '0'..'9' SUFFIX_CHARS = LETTERS.to_a + NUMBERS.to_a belongs_to :project, required: true, validate: true has_many :deployments, dependent: :destroy has_one :last_deployment, -> { order('deployments.id DESC') }, class_name: 'Deployment' before_validation :nullify_external_url before_validation :generate_slug, if: ->(env) { env.slug.blank? } before_save :set_environment_type validates :name, presence: true, uniqueness: { scope: :project_id }, length: { maximum: 255 }, format: { with: Gitlab::Regex.environment_name_regex, message: Gitlab::Regex.environment_name_regex_message } validates :slug, presence: true, uniqueness: { scope: :project_id }, length: { maximum: 24 }, format: { with: Gitlab::Regex.environment_slug_regex, message: Gitlab::Regex.environment_slug_regex_message } validates :external_url, uniqueness: { scope: :project_id }, length: { maximum: 255 }, allow_nil: true, addressable_url: true delegate :stop_action, :manual_actions, to: :last_deployment, allow_nil: true scope :available, -> { with_state(:available) } scope :stopped, -> { with_state(:stopped) } scope :order_by_last_deployed_at, -> do max_deployment_id_sql = Deployment.select(Deployment.arel_table[:id].maximum). where(Deployment.arel_table[:environment_id].eq(arel_table[:id])). to_sql order(Gitlab::Database.nulls_first_order("(#{max_deployment_id_sql})", 'ASC')) end state_machine :state, initial: :available do event :start do transition stopped: :available end event :stop do transition available: :stopped end state :available state :stopped after_transition do |environment| environment.expire_etag_cache end end def predefined_variables [ { key: 'CI_ENVIRONMENT_NAME', value: name, public: true }, { key: 'CI_ENVIRONMENT_SLUG', value: slug, public: true } ] end def recently_updated_on_branch?(ref) ref.to_s == last_deployment.try(:ref) end def nullify_external_url self.external_url = nil if self.external_url.blank? end def set_environment_type names = name.split('/') self.environment_type = if names.many? names.first else nil end end def includes_commit?(commit) return false unless last_deployment last_deployment.includes_commit?(commit) end def last_deployed_at last_deployment.try(:created_at) end def update_merge_request_metrics? (environment_type || name) == "production" end def first_deployment_for(commit) ref = project.repository.ref_name_for_sha(ref_path, commit.sha) return nil unless ref deployment_iid = ref.split('/').last deployments.find_by(iid: deployment_iid) end def ref_path "refs/environments/#{Shellwords.shellescape(name)}" end def formatted_external_url return nil unless external_url external_url.gsub(/\A.*?:\/\//, '') end def stop_action? available? && stop_action.present? end def stop_with_action!(current_user) return unless available? stop! stop_action&.play(current_user) end def actions_for(environment) return [] unless manual_actions manual_actions.select do |action| action.expanded_environment_name == environment end end def has_terminals? project.deployment_service.present? && available? && last_deployment.present? end def terminals project.deployment_service.terminals(self) if has_terminals? end def has_metrics? project.monitoring_service.present? && available? && last_deployment.present? end def metrics project.monitoring_service.environment_metrics(self) if has_metrics? end # An environment name is not necessarily suitable for use in URLs, DNS # or other third-party contexts, so provide a slugified version. A slug has # the following properties: # * contains only lowercase letters (a-z), numbers (0-9), and '-' # * begins with a letter # * has a maximum length of 24 bytes (OpenShift limitation) # * cannot end with `-` def generate_slug # Lowercase letters and numbers only slugified = name.to_s.downcase.gsub(/[^a-z0-9]/, '-') # Must start with a letter slugified = 'env-' + slugified unless LETTERS.cover?(slugified[0]) # Repeated dashes are invalid (OpenShift limitation) slugified.gsub!(/\-+/, '-') # Maximum length: 24 characters (OpenShift limitation) slugified = slugified[0..23] # Cannot end with a dash (Kubernetes label limitation) slugified.chop! if slugified.end_with?('-') # Add a random suffix, shortening the current string if necessary, if it # has been slugified. This ensures uniqueness. if slugified != name slugified = slugified[0..16] slugified << '-' unless slugified.end_with?('-') slugified << random_suffix end self.slug = slugified end def external_url_for(path, commit_sha) return unless self.external_url public_path = project.public_path_for_source_path(path, commit_sha) return unless public_path [external_url, public_path].join('/') end def expire_etag_cache Gitlab::EtagCaching::Store.new.tap do |store| store.touch(etag_cache_key) end end def etag_cache_key Gitlab::Routing.url_helpers.namespace_project_environments_path( project.namespace, project, format: :json) end private # Slugifying a name may remove the uniqueness guarantee afforded by it being # based on name (which must be unique). To compensate, we add a random # 6-byte suffix in those circumstances. This is not *guaranteed* uniqueness, # but the chance of collisions is vanishingly small def random_suffix (0..5).map { SUFFIX_CHARS.sample }.join end end
26.986726
89
0.684374
4ad73d150bd4df9f9f3683348597da19689a5f1e
939
module Hits class << self #hit = 0b0000000000000000 #16 bits CAP_MASK = 0b1000000000000000 #1st bit only IMP_MASK = 0b0110000000000000 #2nd and 3rd bit POS_MASK = 0b0001111111111111 #4th to 16th #Anchor hits dont need to be handled because in simple wikipedia, anchor #text for internal links is always the title of the document it is pointing to #cap = Capitalization = 0 or 1 #imp = Importance = 0 for normal, 1 for bold, 2 for fancy ( title ) #pos = position < 8192 def newHit(cap, imp, pos) pos= 8191 if pos > 8191 newHit = 0b0000000000000000 | cap << 15 | imp << 13 | pos end #Will return 3 values def extractHit(ahit) hit = ahit.to_i cap = (hit & CAP_MASK) >> 15 imp = (hit & IMP_MASK) >> 13 pos = (hit & POS_MASK) return cap, imp, pos end end end
32.37931
82
0.582535
abc396462a94a7b560b836eb346eca8b98c243da
831
require 'test_helper' class UserMailerTest < ActionMailer::TestCase test 'account_activation_and_password_reset_emails' do user = users(:test_user) [{ type: 'activation', method: 'account_activation', subject: 'Account activation' }, { type: 'reset', method: 'password_reset', subject: 'Password reset' }].each do |emails_hash| user.send("#{emails_hash[:type]}_token=", User.new_token) mail = UserMailer.send("#{emails_hash[:method]}", user) assert_equal "#{emails_hash[:subject]}", mail.subject assert_match user.send("#{emails_hash[:type]}_token"), mail.body.encoded assert_equal [user.email], mail.to assert_equal ['[email protected]'], mail.from assert_match user.email, mail.body.encoded assert_match CGI.escape(user.email), mail.body.encoded end end end
46.166667
98
0.703971
1835ec1d180148a41555a3fcfffcba16a1c528cf
4,391
class CorpusEmitter PIPE = "\n | " class CSArg TRANSLATIONS = {"integer" => "number", "string" => "string", "float" => "number", "boolean" => "boolean" } attr_reader :name, :allowed_values def initialize(name:, allowed_values:) @name, @allowed_values = name, allowed_values end def camelize name.camelize end def values allowed_values .map { |v| TRANSLATIONS[v] || v.camelize } .uniq .sort .join(PIPE) end def to_ts "\n #{name}: #{values};" end end class CSNode UNDEFINED = "undefined" attr_reader :name, :allowed_args, :allowed_body_types def initialize(name:, allowed_args:, allowed_body_types: []) @name, @allowed_args, @allowed_body_types = name, allowed_args, allowed_body_types end def camelize name.camelize end def arg_names allowed_args .map{ |x| ARGS[x] } .each { |x| raise "NON-EXISTENT ARG TYPE" unless x } .map(&:to_ts) .join("") end def items_joined_by_pipe allowed_body_types.map(&:camelize).join(PIPE) end def body_names b = items_joined_by_pipe (b.length > 0) ? "(#{b})[] | undefined" : UNDEFINED end def has_body? body_names != UNDEFINED end def body_type "export type #{camelize}BodyItem = #{items_joined_by_pipe};" if has_body? end def body_attr "body?: #{ has_body? ? (camelize + "BodyItem[] | undefined") : UNDEFINED };" end def to_ts """ #{body_type} export interface #{camelize} { kind: #{name.inspect}; args: {#{arg_names} }; comment?: string | undefined; #{body_attr} } """ end end HASH = JSON.load(open("http://localhost:3000/api/corpus")).deep_symbolize_keys ARGS = {} HASH[:args] .map { |x| CSArg.new(x) } .each { |x| ARGS[x.name] = x } NODES = HASH[:nodes].map { |x| CSNode.new(x) } def const(key, val) "\nexport const #{key} = #{val};" end def enum_type(key, val, inspect = true) "\nexport type #{key} = #{(inspect ? val.map(&:inspect) : val).join(PIPE)};" end def self.generate self.new.generate end def generate result = NODES.map(&:to_ts) result.unshift(""" // THIS INTERFACE WAS AUTO GENERATED ON #{Date.today} // DO NOT EDIT THIS FILE. // IT WILL BE OVERWRITTEN ON EVERY CELERYSCRIPT UPGRADE. """) result.push(enum_type :CeleryNode, NODES.map(&:name).map(&:camelize), false) result.push(const(:LATEST_VERSION, Sequence::LATEST_VERSION)) result.push(const :DIGITAL, CeleryScriptSettingsBag::DIGITAL) result.push(const :ANALOG, CeleryScriptSettingsBag::ANALOG) result.push(enum_type :ALLOWED_PIN_MODES, CeleryScriptSettingsBag::ALLOWED_PIN_MODES) result.push(enum_type :ALLOWED_MESSAGE_TYPES, CeleryScriptSettingsBag::ALLOWED_MESSAGE_TYPES) result.push(enum_type :ALLOWED_CHANNEL_NAMES, CeleryScriptSettingsBag::ALLOWED_CHANNEL_NAMES) result.push(enum_type :ALLOWED_DATA_TYPES, CeleryScriptSettingsBag::ALLOWED_DATA_TYPES) result.push(enum_type :ALLOWED_OPS, CeleryScriptSettingsBag::ALLOWED_OPS) result.push(enum_type :ALLOWED_PACKAGES, CeleryScriptSettingsBag::ALLOWED_PACKAGES) result.push(enum_type :ALLOWED_AXIS, CeleryScriptSettingsBag::ALLOWED_AXIS) result.push(enum_type :Color, Sequence::COLORS) result.push(enum_type :LegalArgString, HASH[:args].map{ |x| x[:name] }.sort.uniq) result.push(enum_type :LegalKindString, HASH[:nodes].map{ |x| x[:name] }.sort.uniq) result.push(enum_type :LegalSequenceKind, CeleryScriptSettingsBag::STEPS.sort) result.push(enum_type :DataChangeType, CeleryScriptSettingsBag::ALLOWED_CHAGES) result.push(enum_type :PointType, CeleryScriptSettingsBag::ALLOWED_POINTER_TYPE) result.push(enum_type :AllowedPinTypes, CeleryScriptSettingsBag::ALLOWED_PIN_TYPES) result.push(enum_type :PlantStage, CeleryScriptSettingsBag::PLANT_STAGES) File.open("latest_corpus.ts", "w") do |f| f.write(result.join.gsub("\n\n\n", "\n").gsub("\n\n", "\n").gsub("\n\n", "\n").strip) end end end CorpusEmitter.generate
28.888158
91
0.630608
abe5c9517a25c3fe2a9941aa8e6fdadc3db6d035
1,854
# # Be sure to run `pod lib lint TaggerKit.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'TaggerKit' s.version = '0.5.0' s.summary = 'TaggerKit is a straightforward library that helps you implement tags in your iOS project.' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC This library helps you to quickly implement tags in your iOS apps, so you can go on and test your idea without having to worry about logic and custom collection layouts. DESC s.homepage = 'https://github.com/nekonora/TaggerKit' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { '[email protected]' => '[email protected]' } s.source = { :git => 'https://github.com/nekonora/TaggerKit.git', :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/_nknr' s.ios.deployment_target = '11.0' s.swift_version = '5' s.source_files = 'TaggerKit/Classes/**/*' s.resource_bundles = { 'TaggerKit' => ['TaggerKit/Assets/*.png'] } s.resources = 'TaggerKit/Assets/**/*.{png,storyboard}' # s.public_header_files = 'Pod/Classes/**/*.h' s.frameworks = 'UIKit' # s.dependency 'AFNetworking', '~> 2.3' end
40.304348
169
0.659115
79fbc01d2ebe102e0dbc67d939f30df706b2c1be
711
Pod::Spec.new do |s| s.name = 'AWSKinesis' s.version = '2.6.29' s.summary = 'Amazon Web Services SDK for iOS.' s.description = 'The AWS SDK for iOS provides a library, code samples, and documentation for developers to build connected mobile applications using AWS.' s.homepage = 'http://aws.amazon.com/mobile/sdk' s.license = 'Apache License, Version 2.0' s.author = { 'Amazon Web Services' => 'amazonwebservices' } s.platform = :ios, '8.0' s.source = { :git => 'https://github.com/aws/aws-sdk-ios.git', :tag => s.version} s.requires_arc = true s.dependency 'AWSCore', '2.6.29' s.source_files = 'AWSKinesis/*.{h,m}' end
39.5
157
0.611814
1c8ca1fabdb3cfb5b08bed0cf8f23249fc75af3f
949
# frozen_string_literal: true require 'rails_helper' require_relative '../shared/descriptive_field_sets/field_set_base' RSpec.describe Curator::DescriptiveFieldSets::Publication, type: :model do subject { create(:curator_descriptives_publication) } it_behaves_like 'field_set_base' describe 'attributes' do let(:fields) { %i(edition_name edition_number volume issue_number) } it { is_expected.to respond_to(*fields) } describe 'attr_json settings' do let(:field_types) { fields.map { |field| described_class.attr_json_registry.fetch(field, nil)&.type } } it 'expects the attributes to have the following types' do expect(field_types).to all(be_a_kind_of(ActiveModel::Type::String)) end it 'expects the attributes to have types that match values' do fields.each do |field| expect(subject.public_send(field)).to be_an_instance_of(String) end end end end end
33.892857
109
0.726027
39c690ce89d5f5a6be89bf0fe3cca3b18e81e5c4
4,961
#!/opt/puppetlabs/puppet/bin/ruby require 'json' require 'puppet' def log_files_list_by_server(*args) header_params = {} argstring = args[0].delete('\\') arg_hash = JSON.parse(argstring) # Remove task name from arguments - should contain all necessary parameters for URI arg_hash.delete('_task') operation_verb = 'Get' query_params, body_params, path_params = format_params(arg_hash) uri_string = "https://management.azure.com//subscriptions/%{subscription_id}/resourceGroups/%{resource_group_name}/providers/Microsoft.DBforMySQL/servers/%{server_name}/logFiles" % path_params unless query_params.empty? uri_string = uri_string + '?' + to_query(query_params) end header_params['Content-Type'] = 'application/json' # first of #{parent_consumes} return nil unless authenticate(header_params) == true uri = URI(uri_string) Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http| if operation_verb == 'Get' req = Net::HTTP::Get.new(uri) elsif operation_verb == 'Put' req = Net::HTTP::Put.new(uri) elsif operation_verb == 'Delete' req = Net::HTTP::Delete.new(uri) end header_params.each { |x, v| req[x] = v } unless header_params.empty? unless body_params.empty? req.body=body_params.to_json end Puppet.debug("URI is (#{operation_verb}) #{uri} headers are #{header_params}") response = http.request req # Net::HTTPResponse object Puppet.debug("Called (#{operation_verb}) endpoint at #{uri}") Puppet.debug("response code is #{response.code} and body is #{response.body}") response end end def to_query(hash) if hash return_value = hash.map { |x, v| "#{x}=#{v}" }.reduce { |x, v| "#{x}&#{v}" } if !return_value.nil? return return_value end end return '' end def op_param(name, inquery, paramalias, namesnake) operation_param = { :name => name, :location => inquery, :paramalias => paramalias, :namesnake => namesnake } return operation_param end def format_params(key_values) query_params = {} body_params = {} path_params = {} key_values.each do |key,value| if value.include? '{' key_values[key]=JSON.parse(value.gsub("\'","\"")) end end op_params = [ op_param('api-version', 'query', 'api_version', 'api_version'), op_param('resourceGroupName', 'path', 'resource_group_name', 'resource_group_name'), op_param('serverName', 'path', 'server_name', 'server_name'), op_param('subscriptionId', 'path', 'subscription_id', 'subscription_id'), op_param('value', 'body', 'value', 'value'), ] op_params.each do |i| location = i[:location] name = i[:name] paramalias = i[:paramalias] name_snake = i[:namesnake] if location == 'query' query_params[name] = key_values[name_snake] unless key_values[name_snake].nil? query_params[name] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil? elsif location == 'body' body_params[name] = key_values[name_snake] unless key_values[name_snake].nil? body_params[name] = ENV["azure_#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil? else path_params[name_snake.to_sym] = key_values[name_snake] unless key_values[name_snake].nil? path_params[name_snake.to_sym] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil? end end return query_params,body_params,path_params end def fetch_oauth2_token Puppet.debug('Getting oauth2 token') @client_id = ENV['azure_client_id'] @client_secret = ENV['azure_client_secret'] @tenant_id = ENV['azure_tenant_id'] uri = URI("https://login.microsoftonline.com/#{@tenant_id}/oauth2/token") response = Net::HTTP.post_form(uri, 'grant_type' => 'client_credentials', 'client_id' => @client_id, 'client_secret' => @client_secret, 'resource' => 'https://management.azure.com/') Puppet.debug("get oauth2 token response code is #{response.code} and body is #{response.body}") success = response.is_a? Net::HTTPSuccess if success return JSON[response.body]["access_token"] else raise Puppet::Error, "Unable to get oauth2 token - response is #{response} and body is #{response.body}" end end def authenticate(header_params) token = fetch_oauth2_token if token header_params['Authorization'] = "Bearer #{token}" return true else return false end end def task # Get operation parameters from an input JSON params = STDIN.read result = log_files_list_by_server(params) if result.is_a? Net::HTTPSuccess puts result.body else raise result.body end rescue StandardError => e result = {} result[:_error] = { msg: e.message, kind: 'puppetlabs-azure_arm/error', details: { class: e.class.to_s }, } puts result exit 1 end task
32.006452
194
0.667204
bb2b39141e9a9e39d7aa6298b96a755cd0c8ee14
610
cask 'unity-ios-support-for-editor' do version '2019.2.11f1,5f859a4cfee5' sha256 '6191bd3323909ec4615ce5b835b63f22819508d6d172ba8ac8815797cfe69646' url "https://netstorage.unity3d.com/unity/#{version.after_comma}/MacEditorTargetInstaller/UnitySetup-iOS-Support-for-Editor-#{version.before_comma}.pkg" appcast 'https://public-cdn.cloud.unity3d.com/hub/prod/releases-darwin.json' name 'Unity iOS Build Support' homepage 'https://unity3d.com/unity/' depends_on cask: 'unity' pkg "UnitySetup-iOS-Support-for-Editor-#{version.before_comma}.pkg" uninstall pkgutil: 'com.unity3d.iOSSupport' end
38.125
154
0.785246
f71a21764f26783cb403883d33f9d6e0a062736f
5,709
# frozen_string_literal: true # Copyright 2015-2017, the Linux Foundation, IDA, and the # CII Best Practices badge contributors # SPDX-License-Identifier: MIT require 'test_helper' # rubocop:disable Metrics/ClassLength class UserTest < ActiveSupport::TestCase setup do @user = User.new( name: 'Example User', email: '[email protected]', provider: 'local', password: 'p@$$w0rd', password_confirmation: 'p@$$w0rd' ) end test 'should be valid' do assert @user.valid? end test 'name should be present' do @user.name = '' assert_not @user.valid? end test 'email should be present' do @user.email = ' ' assert_not @user.valid? end test 'username should not be too long' do @user.name = 'a' * 51 assert_not @user.valid? end test 'email should not be too long' do @user.email = 'e' * 250 + '@mail.com' assert_not @user.valid? end test 'email validation should accept good emails' do good_emails = %w[ [email protected] [email protected] [email protected] [email protected] [email protected] ] good_emails.each do |good_email| @user.email = good_email assert @user.valid?, "#{good_email.inspect} should be valid" end end test 'email validation should reject bad emails' do bad_emails = %w[ user@mail,com user_at_foo.org user.name@mail. foo@bar_baz.com foo@bar+baz.com ] bad_emails.each do |bad_email| @user.email = bad_email assert_not @user.valid?, "#{bad_email.inspect} should be invalid" end end test 'emails should be unique' do duplicate_user = @user.dup @user.save! assert_not duplicate_user.valid? end test 'emails should be unique when ignoring case' do duplicate_user = @user.dup duplicate_user.email = @user.email.upcase @user.save! assert_not duplicate_user.valid? end # test 'password should be present and not empty' do # @user.password = @user.password_confirmation = ' ' * 7 # assert_not @user.valid? # end test 'password should have a minimum length' do @user.password = @user.password_confirmation = 'a' * 7 assert_not @user.valid? end test 'rekey test' do # This is a somewhat complicated setup to create a user with an old key. # We don't bother setting up an old blind index, because we're going # to just obliterate it anyway. user1 = User.new # Set a different email address to initialize attr_encrypted user1.email = 'wrong_email' # Now insert some encrypted data using an "old" key old_key = ['ea' * 32].pack('H*') old_iv = Base64.decode64(user1.encrypted_email_iv) email_address = '[email protected]' user1.encrypted_email = User.encrypt_email( email_address, key: old_key, iv: old_iv ) # Setup done, now invoke rekey to test rekeying the record. user1.rekey(old_key) # Check if rekey results are correct assert email_address, user1.email new_blind_index = BlindIndex.generate_bidx( # Recalc so test's less fragile email_address, key: [User::TEST_EMAIL_BLIND_INDEX_KEY].pack('H*'), options: User.blind_indexes[:email] ) assert new_blind_index, user1.email_bidx end test 'associated projects should be destroyed' do @user.save! @user.projects.create!( homepage_url: 'https://www.example.org', repo_url: 'https://www.example.org/code' ) assert_difference 'Project.count', -1 do @user.destroy end end test 'authenticated? should return false for a user with nil digest' do assert_not @user.authenticated?(:remember, '') end test 'gravatar URL for local user' do avatar_id = Digest::MD5.hexdigest(users(:admin_user).email.downcase) assert_equal "https://secure.gravatar.com/avatar/#{avatar_id}?d=mm&size=80", users(:admin_user).avatar_url end test 'gravatar URL for github user' do assert_equal 'https://avatars.githubusercontent.com/github-user?size=80', users(:github_user).avatar_url end test 'Bcrypt of text with full rounds' do ActiveModel::SecurePassword.min_cost = false assert_match(/\$2a\$/, User.digest('foobar')) ActiveModel::SecurePassword.min_cost = true end class StubUserEmail < User def email raise OpenSSL::Cipher::CipherError end end test 'Test user.email_if_decryptable when not decryptable' do u = StubUserEmail.new assert_equal 'CANNOT_DECRYPT', u.email_if_decryptable end test 'Data model encrypted email addresses and blind index keys work' do # We precompute the user data fixtures, and it's possible we got it wrong. # Walk through the data set to do sanity checks for each value. User.find_each do |user| # puts(user.name) assert user.name.present?, "Empty name for #{user.id}" assert user.encrypted_email.present?, "Email not present for #{user.name}" assert( user.encrypted_email_iv.present?, "Email IV not present for #{user.name}" ) # This will also fail if the email is not encrypted correctly: assert user.email.present?, "Email not present for #{user.name}" assert user.provider.present?, "Provider not present for #{user.name}" assert( (user.provider != 'local' || user.password_digest.present?), "Local user has no password: #{user.name}, #{user.email}" ) # An incorrect bidx could lead to confusing test results, so we # *definitely* want the following check. # Check that bidx was computed correctly: assert_equal User.generate_email_bidx(user.email), user.email_bidx end end end # rubocop:enable Metrics/ClassLength
31.027174
80
0.678052
269b3356c6a2e42f92f1b38b4c78f1f69ac6de79
414
require 'bbk/app/matchers/base' module BBK module App module Matchers class Headers < Base def initialize(rule) @rule = rule.with_indifferent_access end def match(headers, _payload = nil, _delivery_info = nil, *_args) match_impl(@rule, headers.with_indifferent_access) rescue StandardError nil end end end end end
17.25
72
0.611111
e975e058582dab04ee1ad9b32319b426fcbbbe97
23,286
#!/usr/bin/env ruby # coding: utf-8 # = nessus_rest.rb: communicate with Nessus(6+) over JSON REST interface # # Author:: Vlatko Kosturjak # # (C) Vlatko Kosturjak, Kost. Distributed under MIT license. # # == What is this library? # # This library is used for communication with Nessus over JSON REST interface. # You can start, stop, pause and resume scan. Watch progress and status of scan, # download report, etc. # # == Requirements # # Required libraries are standard Ruby libraries: uri, net/https and json. # # == Usage: # # require 'nessus_rest' # # n=NessusREST::Client.new ({:url=>'https://localhost:8834', :username=>'user', :password=> 'password'}) # qs=n.scan_quick_template('basic','name-of-scan','localhost') # scanid=qs['scan']['id'] # n.scan_wait4finish(scanid) # n.report_download_file(scanid,'csv','myscanreport.csv') # require 'openssl' require 'uri' require 'net/http' require 'net/https' require 'json' # NessusREST module - for all stuff regarding Nessus REST JSON # module NessusREST # Client class implementation of Nessus (6+) JSON REST protocol. # Class which uses standard JSON lib to parse nessus JSON REST replies. # # == Typical Usage: # # require 'nessus_rest' # # n=NessusREST::Client.new ({:url=>'https://localhost:8834', :username=>'user', :password=> 'password'}) # qs=n.scan_quick_template('basic','name-of-scan','localhost') # scanid=qs['scan']['id'] # n.scan_wait4finish(scanid) # n.report_download_file(scanid,'csv','myscanreport.csv') # class Client attr_accessor :quick_defaults attr_accessor :defsleep, :httpsleep, :httpretry, :ssl_use, :ssl_verify, :autologin attr_reader :x_cookie class << self @connection @token end # initialize quick scan defaults: these will be used when not specifying defaults # # Usage: # # n.init_quick_defaults() def init_quick_defaults @quick_defaults=Hash.new @quick_defaults['enabled']=false @quick_defaults['launch']='ONETIME' @quick_defaults['launch_now']=true @quick_defaults['description']='Created with nessus_rest' end # initialize object: try to connect to Nessus Scanner using URL, user and password # (or any other defaults) # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') def initialize(params={}) # defaults @nessusurl = params.fetch(:url,'https://127.0.0.1:8834/') @username = params.fetch(:username,'nessus') @password = params.fetch(:password,'nessus') @ssl_verify = params.fetch(:ssl_verify,false) @ssl_use = params.fetch(:ssl_use,true) @autologin = params.fetch(:autologin, true) @defsleep = params.fetch(:defsleep, 1) @httpretry = params.fetch(:httpretry, 3) @httpsleep = params.fetch(:httpsleep, 1) init_quick_defaults() uri = URI.parse(@nessusurl) @connection = Net::HTTP.new(uri.host, uri.port) @connection.use_ssl = @ssl_use if @ssl_verify @connection.verify_mode = OpenSSL::SSL::VERIFY_PEER else @connection.verify_mode = OpenSSL::SSL::VERIFY_NONE end yield @connection if block_given? authenticate(@username, @password) if @autologin end # Tries to authenticate to the Nessus REST JSON interface # # returns: true if logged in, false if not # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :autologin=>false) # if n.authenticate('user','pass') # puts "Logged in" # else # puts "Error" # end def authenticate(username, password) @username = username @password = password authdefault end alias_method :login, :authenticate # Tries to authenticate to the Nessus REST JSON interface # # returns: true if logged in, false if not # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :autologin=>false, # :username=>'nessususer', :password=>'nessuspassword') # if n.authdefault # puts "Logged in" # else # puts "Error" # end def authdefault payload = { :username => @username, :password => @password, :json => 1, :authenticationmethod => true } res = http_post(:uri=>"/session", :data=>payload) if res['token'] @token = "token=#{res['token']}" @x_cookie = {'X-Cookie'=>@token} return true else false end end # checks if we're logged in correctly # # returns: true if logged in, false if not # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # if n.authenticated # puts "Logged in" # else # puts "Error" # end def authenticated if (@token && @token.include?('token=')) return true else return false end end # try to get server properties # # returns: JSON parsed object with server properties # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.get_server_properties def get_server_properties http_get(:uri=>"/server/properties", :fields=>x_cookie) end alias_method :server_properties, :get_server_properties # Add user to server # # returns: JSON parsed object # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.user_add('user','password','16','local') # # Reference: # https://localhost:8834/api#/resources/users/create def user_add(username, password, permissions, type) payload = { :username => username, :password => password, :permissions => permissions, :type => type, :json => 1 } http_post(:uri=>"/users", :fields=>x_cookie, :data=>payload) end # delete user with user_id # # returns: result code # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # puts n.user_delete(1) def user_delete(user_id) res = http_delete(:uri=>"/users/#{user_id}", :fields=>x_cookie) return res.code end # change password for user_id # # returns: result code # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # puts n.user_chpasswd(1,'newPassword') def user_chpasswd(user_id, password) payload = { :password => password, :json => 1 } res = http_put(:uri=>"/users/#{user_id}/chpasswd", :data=>payload, :fields=>x_cookie) return res.code end # logout from the server # # returns: result code # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # puts n.user_logout def user_logout res = http_delete(:uri=>"/session", :fields=>x_cookie) return res.code end alias_method :logout, :user_logout # Get List of Policies # # returns: JSON parsed object with list of policies # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.list_policies def list_policies http_get(:uri=>"/policies", :fields=>x_cookie) end # Get List of Users # # returns: JSON parsed object with list of users # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.list_users def list_users http_get(:uri=>"/users", :fields=>x_cookie) end # Get List of Folders # # returns: JSON parsed object with list of folders # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.list_folders def list_folders http_get(:uri=>"/folders", :fields=>x_cookie) end # Get List of Scanners # # returns: JSON parsed object with list of scanners # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.list_scanners def list_scanners http_get(:uri=>"/scanners", :fields=>x_cookie) end # Get List of Families # # returns: JSON parsed object with list of families # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.list_families def list_families http_get(:uri=>"/plugins/families", :fields=>x_cookie) end # Get List of Plugins # # returns: JSON parsed object with list of plugins # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.list_plugins def list_plugins(family_id) http_get(:uri=>"/plugins/families/#{family_id}", :fields=>x_cookie) end # Get List of Templates # # returns: JSON parsed object with list of templates # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.list_templates def list_templates(type) res = http_get(:uri=>"/editor/#{type}/templates", :fields=>x_cookie) end def plugin_details(plugin_id) http_get(:uri=>"/plugins/plugin/#{plugin_id}", :fields=>x_cookie) end # check if logged in user is administrator # # returns: boolean value depending if user is administrator or not # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # if n.is_admin # puts "Administrator" # else # puts "NOT administrator" # end def is_admin res = http_get(:uri=>"/session", :fields=>x_cookie) if res['permissions'] == 128 return true else return false end end # Get server status # # returns: JSON parsed object with server status # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.server_status def server_status http_get(:uri=>"/server/status", :fields=>x_cookie) end def scan_create(uuid, settings) payload = { :uuid => uuid, :settings => settings, :json => 1 }.to_json http_post(:uri=>"/scans", :body=>payload, :fields=>x_cookie, :ctype=>'application/json') end def scan_launch(scan_id) http_post(:uri=>"/scans/#{scan_id}/launch", :fields=>x_cookie) end # Get List of Scans # # returns: JSON parsed object with list of scans # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.scan_list def scan_list http_get(:uri=>"/scans", :fields=>x_cookie) end alias_method :list_scans, :scan_list def scan_details(scan_id) http_get(:uri=>"/scans/#{scan_id}", :fields=>x_cookie) end def scan_pause(scan_id) http_post(:uri=>"/scans/#{scan_id}/pause", :fields=>x_cookie) end def scan_resume(scan_id) http_post(:uri=>"/scans/#{scan_id}/resume", :fields=>x_cookie) end def scan_stop(scan_id) http_post(:uri=>"/scans/#{scan_id}/stop", :fields=>x_cookie) end def scan_export(scan_id, format) payload = { :format => format }.to_json http_post(:uri=>"/scans/#{scan_id}/export", :body=>payload, :ctype=>'application/json', :fields=>x_cookie) end def scan_export_status(scan_id, file_id) request = Net::HTTP::Get.new("/scans/#{scan_id}/export/#{file_id}/status") request.add_field("X-Cookie", @token) res = @connection.request(request) res = JSON.parse(res.body) return res end # delete scan with scan_id # # returns: boolean (true if deleted) # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # puts n.scan_delete(1) def scan_delete(scan_id) res = http_delete(:uri=>"/scans/#{scan_id}", :fields=>x_cookie) if res.code == 200 then return true end return false end def policy_delete(policy_id) res = http_delete(:uri=>"/policies/#{policy_id}", :fields=>x_cookie) return res.code end # Get template by type and uuid. Type can be 'policy' or 'scan' # # returns: JSON parsed object with template # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.editor_templates('scan',uuid) def editor_templates (type, uuid) res = http_get(:uri=>"/editor/#{type}/templates/#{uuid}", :fields=>x_cookie) end # Performs scan with templatename provided (name, title or uuid of scan). # Name is your scan name and targets are targets for scan # # returns: JSON parsed object with scan info # # Usage: # # require 'nessus_rest' # # n=NessusREST::Client.new ({:url=>'https://localhost:8834', :username=>'user', :password=> 'password'}) # qs=n.scan_quick_template('basic','name-of-scan','localhost') # scanid=qs['scan']['id'] # n.scan_wait4finish(scanid) # n.report_download_file(scanid,'csv','myscanreport.csv') # def scan_quick_template (templatename, name, targets) templates=list_templates('scan')['templates'].select do |temp| temp['uuid'] == templatename or temp['name'] == templatename or temp['title'] == templatename end if templates.nil? then return nil end tuuid=templates.first['uuid'] et=editor_templates('scan',tuuid) et.merge!(@quick_defaults) et['name']=name et['text_targets']=targets sc=scan_create(tuuid,et) end # Performs scan with scan policy provided (uuid of policy or policy name). # Name is your scan name and targets are targets for scan # # returns: JSON parsed object with scan info # # Usage: # # require 'nessus_rest' # # n=NessusREST::Client.new ({:url=>'https://localhost:8834', :username=>'user', :password=> 'password'}) # qs=n.scan_quick_policy('myscanpolicy','name-of-scan','localhost') # scanid=qs['scan']['id'] # n.scan_wait4finish(scanid) # n.report_download_file(scanid,'nessus','myscanreport.nessus') # def scan_quick_policy (policyname, name, targets) policies=list_policies['policies'].select do |pol| pol['id'] == policyname or pol['name'] == policyname end if policies.nil? then return nil end policy = policies.first tuuid=policy['template_uuid'] et=Hash.new et.merge!(@quick_defaults) et['name']=name et['policy_id'] = policy['id'] et['text_targets']=targets sc=scan_create(tuuid,et) end def scan_status(scan_id) sd=scan_details(scan_id) if not sd['error'].nil? return 'error' end return sd['info']['status'] end def scan_finished?(scan_id) ss=scan_status(scan_id) if ss == 'completed' or ss == 'canceled' or ss == 'imported' then return true end return false end def scan_wait4finish(scan_id) while not scan_finished?(scan_id) do # puts scan_status(scan_id) sleep @defsleep end end # Get host details from the scan # # returns: JSON parsed object with host details # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.host_detail(123, 1234) def host_detail(scan_id, host_id) res = http_get(:uri=>"/scans/#{scan_id}/hosts/#{host_id}", :fields=>x_cookie) end def report_download(scan_id, file_id) res = http_get(:uri=>"/scans/#{scan_id}/export/#{file_id}/download", :raw_content=> true, :fields=>x_cookie) end def report_download_quick(scan_id, format) se=scan_export(scan_id,format) # ready, loading while (status = scan_export_status(scan_id,se['file'])['status']) != "ready" do # puts status if status.nil? or status == '' then return nil end sleep @defsleep end rf=report_download(scan_id,se['file']) return rf end def report_download_file(scan_id, format, outputfn) report_content=report_download_quick(scan_id, format) File.open(outputfn, 'w') do |f| f.write(report_content) end end # # private? # # Perform HTTP put method with uri, data and fields # # returns: HTTP result object # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # payload = { # :password => password, # :json => 1 # } # res = n.http_put(:uri=>"/users/#{user_id}/chpasswd", :data=>payload, :fields=>n.x_cookie) # puts res.code def http_put(opts={}) ret=http_put_low(opts) if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then authdefault ret=http_put_low(opts) return ret else return ret end end def http_put_low(opts={}) uri = opts[:uri] data = opts[:data] fields = opts[:fields] || {} res = nil tries = @httpretry req = Net::HTTP::Put.new(uri) req.set_form_data(data) unless (data.nil? || data.empty?) fields.each_pair do |name, value| req.add_field(name, value) end begin tries -= 1 res = @connection.request(req) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e if tries>0 sleep @httpsleep retry else return res end rescue URI::InvalidURIError return res end res end # Perform HTTP delete method with uri, data and fields # # returns: HTTP result object # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # res = n.http_delete(:uri=>"/session", :fields=>n.x_cookie) # puts res.code def http_delete(opts={}) ret=http_delete_low(opts) if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then authdefault ret=http_delete_low(opts) return ret else return ret end end def http_delete_low(opts={}) uri = opts[:uri] fields = opts[:fields] || {} res = nil tries = @httpretry req = Net::HTTP::Delete.new(uri) fields.each_pair do |name, value| req.add_field(name, value) end begin tries -= 1 res = @connection.request(req) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e if tries>0 sleep @httpsleep retry else return res end rescue URI::InvalidURIError return res end res end # Perform HTTP get method with uri and fields # # returns: JSON parsed object (if JSON parseable) # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.http_get(:uri=>"/users", :fields=>n.x_cookie) def http_get(opts={}) raw_content = opts[:raw_content] || false ret=http_get_low(opts) if !raw_content then if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then authdefault ret=http_get_low(opts) return ret else return ret end else return ret end end def http_get_low(opts={}) uri = opts[:uri] fields = opts[:fields] || {} raw_content = opts[:raw_content] || false json = {} tries = @httpretry req = Net::HTTP::Get.new(uri) fields.each_pair do |name, value| req.add_field(name, value) end begin tries -= 1 res = @connection.request(req) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e if tries>0 sleep @httpsleep retry else return json end rescue URI::InvalidURIError return json end if !raw_content parse_json(res.body) else res.body end end # Perform HTTP post method with uri, data, body and fields # # returns: JSON parsed object (if JSON parseable) # # Usage: # # n=NessusREST::Client.new (:url=>'https://localhost:8834', :username=>'user', :password=> 'password') # pp n.http_post(:uri=>"/scans/#{scan_id}/launch", :fields=>n.x_cookie) def http_post(opts={}) if opts.has_key?(:authenticationmethod) then # i know authzmethod = opts.delete(:authorizationmethod) is short, but not readable authzmethod = opts[:authenticationmethod] opts.delete(:authenticationmethod) end ret=http_post_low(opts) if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then if not authzmethod authdefault ret=http_post_low(opts) return ret end else return ret end end def http_post_low(opts={}) uri = opts[:uri] data = opts[:data] fields = opts[:fields] || {} body = opts[:body] ctype = opts[:ctype] json = {} tries = @httpretry req = Net::HTTP::Post.new(uri) req.set_form_data(data) unless (data.nil? || data.empty?) req.body = body unless (body.nil? || body.empty?) req['Content-Type'] = ctype unless (ctype.nil? || ctype.empty?) fields.each_pair do |name, value| req.add_field(name, value) end begin tries -= 1 res = @connection.request(req) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e if tries>0 sleep @httpsleep retry else return json end rescue URI::InvalidURIError return json end parse_json(res.body) end # Perform JSON parsing of body # # returns: JSON parsed object (if JSON parseable) # def parse_json(body) buf = {} begin buf = JSON.parse(body) rescue JSON::ParserError end buf end end # of Client class end # of NessusREST module
27.987981
146
0.606072
39640422e787540804d47ffa1562f5e53b06374e
5,972
# frozen_string_literal: true require 'spec_helper' describe Simulation::Contagion::Population::Builder do let(:simulation) { create(:simulation) } let(:contagion) { simulation.contagion } let(:behavior) { contagion.behaviors.last } let(:group) do create( :contagion_group, contagion: contagion, behavior: behavior, size: size, infected: infected ) end let(:size) { Random.rand(300..1000) } let(:infected) { Random.rand(100..size) } let!(:instant) do create(:contagion_instant, contagion: contagion) end describe '.build' do context 'when building from group' do subject(:population) do described_class.build( instant: instant, group: group, state: state ) end context 'when state is healthy' do let(:state) do Simulation::Contagion::Population::HEALTHY end it do expect(population).not_to be_persisted end it do expect(population) .to be_a(Simulation::Contagion::Population) end it do expect(population.instant) .to eq(instant) end it do expect(population.behavior) .to eq(behavior) end it 'creates population with right healthy size' do expect(population.size) .to eq(size - infected) end it do expect(population).to be_healthy end it 'sets day to be 0' do expect(population.days).to be_zero end it 'does not add interactions' do expect(population.interactions) .to be_zero end end context 'when state is infected' do let(:state) do Simulation::Contagion::Population::INFECTED end it do expect(population).not_to be_persisted end it do expect(population) .to be_a(Simulation::Contagion::Population) end it do expect(population.instant) .to eq(instant) end it do expect(population.behavior) .to eq(behavior) end it 'creates population with right infected size' do expect(population.size) .to eq(infected) end it do expect(population).to be_infected end it 'sets day to be 0' do expect(population.days).to be_zero end it 'does not add interactions' do expect(population.interactions) .to be_zero end end end context 'when building from another population' do subject(:population) do described_class.build( instant: instant, population: previous_population ) end let(:previous_population) do create(:contagion_population, group: group, state: state) end let(:previous_instant) { previour_population.instant } let(:state) do Simulation::Contagion::Population::STATES.sample end it do expect(population).not_to be_persisted end it do expect(population) .to be_a(Simulation::Contagion::Population) end it do expect(population.instant) .to eq(instant) end it do expect(population.behavior) .to eq(behavior) end it 'creates population with right size' do expect(population.size) .to eq(previous_population.size) end it do expect(population.state).to eq(state) end it 'increment days' do expect(population.days).to eq(1) end it 'does not add interactions' do expect(population.interactions) .to be_zero end end context 'when building passing extra params' do subject(:population) do described_class.build( instant: instant, group: group, behavior: new_behavior, state: state, size: size ) end let(:size) { Random.rand(100..119) } let(:state) do Simulation::Contagion::Population::DEAD end let(:new_behavior) do create(:contagion_behavior, contagion: contagion) end it do expect(population).not_to be_persisted end it do expect(population) .to be_a(Simulation::Contagion::Population) end it do expect(population.instant) .to eq(instant) end it do expect(population.behavior) .to eq(new_behavior) end it 'creates population with given size' do expect(population.size).to eq(size) end it 'creates population with given state' do expect(population.state).to eq(state) end it 'initialize days' do expect(population.days).to be_zero end it 'sets interactions' do expect(population.interactions) .to be_zero end context 'when there is already a population for same params' do let!(:previous_population) do described_class.build( instant: instant, group: group, behavior: new_behavior, state: state, size: initial_size ).tap(&:save!) end let(:initial_size) { Random.rand(50..249) } it 'changes size of preexisting population' do expect(population.id) .to eq(previous_population.id) end it 'sums sizes' do expect(population.size) .to eq(size + initial_size) end it 'changes instantce population size' do expect { population } .to change { instant.populations.first.size } .by(size) end end end end end
22.367041
69
0.562626
1df296074475c17fd3ac341ce0dadde84f5c624d
2,864
# Copyright (c) Universidade Federal Fluminense (UFF). # This file is part of SAPOS. Please, consult the license terms in the LICENSE file. class Student < ApplicationRecord mount_uploader :photo, ProfileUploader has_many :student_majors, :dependent => :destroy has_many :majors, :through => :student_majors #delete cascade for enrollment -- when a student is deleted, so are his enrollments has_many :enrollments, :dependent => :restrict_with_exception belongs_to :city belongs_to :birth_city, :class_name => 'City', :foreign_key => 'birth_city_id' belongs_to :birth_state, :class_name => 'State', :foreign_key => 'birth_state_id' belongs_to :birth_country, :class_name => 'Country', :foreign_key => 'birth_country_id' belongs_to :user, optional: true has_paper_trail validates :name, :presence => true validates :cpf, :presence => true, :uniqueness => true validate :changed_to_different_user before_save :set_birth_state_by_birth_city def has_user? return true unless self.user_id.nil? ! User.where(email: self.emails).empty? end def has_email? ! (self.email.nil? || self.email.empty?) end def emails return [] unless self.has_email? return self.email.split(/[\s,;]/).filter { |email| email != "" } end def first_email emails = self.emails return nil if emails.empty? return emails[0] end def can_have_new_user? return false unless has_email? return false if has_user? return true end def enrollments_number self.enrollments.collect { |enrollment| enrollment.enrollment_number }.join(', ') end def to_label "#{self.name}" end def birthplace return nil if birth_city.nil? and birth_state.nil? return "#{birth_state.country.name}" if birth_city.nil? "#{birth_city.state.country.name}" end def nationality if not birth_country.nil? return "#{birth_country.nationality}" elsif not birth_state.nil? return "#{birth_state.country.nationality}" elsif not birth_city.nil? return "#{birth_city.state.country.nationality}" end nil end def identity_issuing_place_to_label return "#{I18n.t('pdf_content.enrollment.header.identity_issuing_state')}" unless State.where("name LIKE ?", self.identity_issuing_place).empty? return "#{I18n.t('pdf_content.enrollment.header.identity_issuing_country')}" end def mount_uploader_name :photo end def changed_to_different_user if (user_id_changed?) && (!user_id.nil?) && (!user_id_was.nil?) errors.add(:user, :changed_to_different_user) end end protected def set_birth_state_by_birth_city self.birth_state_id = birth_city.state_id unless birth_city.nil? end end
28.078431
149
0.683659
6ae2773dd5981eb2d68cd97df45e1a597945cafe
316
class CreateInfoNodes < ActiveRecord::Migration def change create_table :info_nodes do |t| t.string :title t.string :key t.string :node_type t.integer :collection_id t.integer :document_id t.integer :passage_id t.integer :node_id t.timestamps end end end
19.75
47
0.651899
4aba27db0ec3f72b7a6dd33c35d3463ea7ec5caa
1,747
require 'spec_helper' describe "datadog_agent::integration" do context 'supported agents' do ALL_SUPPORTED_AGENTS.each do |agent_major_version| let(:pre_condition) { "class {'::datadog_agent': agent_major_version => #{agent_major_version}}" } if agent_major_version == 5 let(:conf_file) { '/etc/dd-agent/conf.d/test.yaml' } else let(:conf_dir) { "#{CONF_DIR}/test.d" } let(:conf_file) { "#{conf_dir}/conf.yaml" } end let (:title) { "test" } let (:params) {{ :instances => [ { 'one' => "two" } ] }} it { should compile } if agent_major_version == 5 it { should contain_file("#{conf_dir}").that_comes_before("File[#{conf_file}]") } end it { should contain_file("#{conf_file}").with_content(/init_config: /) } gem_spec = Gem.loaded_specs['puppet'] if gem_spec.version >= Gem::Version.new('4.0.0') it { should contain_file("#{conf_file}").with_content(/---\ninit_config: \ninstances:\n- one: two\n/) } else it { should contain_file("#{conf_file}").with_content(/--- \n init_config: \n instances: \n - one: two/) } end it { should contain_file("#{conf_file}").that_notifies("Service[#{SERVICE_NAME}]") } context 'with logs' do let(:params) {{ :instances => [ { 'one' => "two" } ], :logs => %w(one two), }} if gem_spec.version >= Gem::Version.new('4.0.0') it { should contain_file(conf_file).with_content(%r{logs:\n- one\n- two}) } else it { should contain_file(conf_file).with_content(%r{logs:\n - one\n - two}) } end end end end end
34.254902
119
0.559817
878de53e6e27ed833cd1f9df858a2d8acb949bae
281
require 'minitest/autorun' require_relative '../lib/i2c/drivers/lcd' class MiniTest::Test def initialize(name = nil) @test_name = name super(name) unless name.nil? end def fixture(name = @test_name) File.join(File.dirname(__FILE__), 'fixtures', name) end end
20.071429
55
0.701068
ab167936044beb8ac9edb0c85abf03293f10ca63
2,583
require 'spec_helper' describe BatchEditsController do before do controller.stub(:has_access?).and_return(true) @user = FactoryGirl.find_or_create(:jill) sign_in @user User.any_instance.stub(:groups).and_return([]) controller.stub(:clear_session_user) ## Don't clear out the authenticated session request.env["HTTP_REFERER"] = 'test.host/original_page' end routes { Internal::Application.routes } describe "edit" do before do @one = GenericFile.new(creator: "Fred", language: 'en')#, resource_type: 'foo') @one.apply_depositor_metadata('mjg36') @two = GenericFile.new(creator: "Wilma", publisher: 'Rand McNally', language: 'en', resource_type: 'bar') @two.apply_depositor_metadata('mjg36') @one.save! @two.save! controller.batch = [@one.pid, @two.pid] controller.should_receive(:can?).with(:edit, @one.pid).and_return(true) controller.should_receive(:can?).with(:edit, @two.pid).and_return(true) end it "should be successful" do get :edit response.should be_successful assigns[:terms].should == [:creator, :contributor, :description, :tag, :rights, :publisher, :date_created, :subject, :language, :identifier, :based_near, :related_url] assigns[:show_file].creator.should == ["Fred", "Wilma"] assigns[:show_file].publisher.should == ["Rand McNally"] assigns[:show_file].language.should == ["en"] end end describe "update" do before do @one = GenericFile.new(creator: "Fred", language: 'en') @one.apply_depositor_metadata('mjg36') @two = GenericFile.new(creator: "Wilma", publisher: 'Rand McNally', language: 'en') @two.apply_depositor_metadata('mjg36') @one.save! @two.save! controller.batch = [@one.pid, @two.pid] controller.should_receive(:can?).with(:edit, @one.pid).and_return(true) controller.should_receive(:can?).with(:edit, @two.pid).and_return(true) end it "should be successful" do put :update , update_type:"delete_all" response.should be_redirect expect {GenericFile.find(@one.id)}.to raise_error(ActiveFedora::ObjectNotFoundError) expect {GenericFile.find(@two.id)}.to raise_error(ActiveFedora::ObjectNotFoundError) end it "should update the records" do put :update , update_type:"update", "generic_file"=>{"subject"=>["zzz"]} response.should be_redirect GenericFile.find(@one.id).subject.should == ["zzz"] GenericFile.find(@two.id).subject.should == ["zzz"] end end end
39.738462
111
0.667054
f78b8276e5c940bfbeb0b81a11d610fd3cefe87f
8,444
module Fog module Vcloud class Compute class Server < Fog::Vcloud::Model identity :href, :aliases => :Href ignore_attributes :xmlns, :xmlns_i, :xmlns_xsi, :xmlns_xsd attribute :type attribute :name attribute :status attribute :network_connections, :aliases => :NetworkConnectionSection, :squash => :NetworkConnection attribute :os, :aliases => :OperatingSystemSection attribute :virtual_hardware, :aliases => :VirtualHardwareSection attribute :description, :aliases => :Description attribute :storage_size, :aliases => :size attribute :links, :aliases => :Link, :type => :array attribute :tasks, :aliases => :Tasks, :type => :array attribute :vm_data, :aliases => :Children, :squash => :Vm def ip_address load_unless_loaded! vm[0][:NetworkConnectionSection][:NetworkConnection][:IpAddress] end def friendly_status load_unless_loaded! case status when '0' 'creating' when '8' 'off' when '4' 'on' else 'unkown' end end def ready? reload_status # always ensure we have the correct status running_tasks = tasks && tasks.flatten.any? {|ti| ti.kind_of?(Hash) && ti[:status] == 'running' } status != '0' && !running_tasks # 0 is provisioning, and no running tasks end def on? reload_status # always ensure we have the correct status status == '4' end def off? reload_status # always ensure we have the correct status status == '8' end def power_on power_operation( :power_on => :powerOn ) end def power_off power_operation( :power_off => :powerOff ) end def shutdown power_operation( :power_shutdown => :shutdown ) end def power_reset power_operation( :power_reset => :reset ) end # This is the real power-off operation def undeploy connection.undeploy href end def graceful_restart requires :href shutdown wait_for { off? } power_on end def vm load_unless_loaded! self.vm_data end def name=(new_name) attributes[:name] = new_name @changed = true end def cpus if cpu_mess { :count => cpu_mess[:"rasd:VirtualQuantity"].to_i, :units => cpu_mess[:"rasd:AllocationUnits"] } end end def cpus=(qty) @changed = true cpu_mess[:"rasd:VirtualQuantity"] = qty.to_s end def memory if memory_mess { :amount => memory_mess[:"rasd:VirtualQuantity"].to_i, :units => memory_mess[:"rasd:AllocationUnits"] } end end def memory=(amount) @changed = true @update_memory_value = amount amount end def disks disk_mess.map do |dm| { :number => dm[:"rasd:AddressOnParent"], :size => dm[:"rasd:VirtualQuantity"].to_i, :resource => dm[:"rasd:HostResource"] } end end def add_disk(size) if @disk_change == :deleted raise RuntimeError, "Can't add a disk w/o saving changes or reloading" else load_unless_loaded! @disk_change = :added @add_disk = { :'rasd:HostResource' => {:vcloud_capacity => size}, :'rasd:AddressOnParent' => (disk_mess.map { |dm| dm[:'rasd:AddressOnParent'] }.sort.last.to_i + 1).to_s, :'rasd:ResourceType' => '17' } end true end def delete_disk(number) if @disk_change == :added raise RuntimeError, "Can't delete a disk w/o saving changes or reloading" else load_unless_loaded! unless number == 0 @disk_change = :deleted @remove_disk = number end end true end def description=(description) @description_changed = true unless attributes[:description] == description || attributes[:description] == nil attributes[:description] = description end def name=(name) @name_changed = true unless attributes[:name] == name || attributes[:name] == nil attributes[:name] = name end def reload reset_tracking super end def save if new_record? #Lame ... raise RuntimeError, "Should not be here" else if on? if @changed raise RuntimeError, "Can't save cpu, name or memory changes while the VM is on." end end if @update_memory_value memory_mess[:"rasd:VirtualQuantity"] = @update_memory_value.to_s connection.configure_vm_memory(memory_mess) end if @disk_change == :deleted data = disk_mess.delete_if do |vh| vh[:'rasd:ResourceType'] == '17' && vh[:'rasd:AddressOnParent'].to_s == @remove_disk.to_s end connection.configure_vm_disks(vm_href, data) end if @disk_change == :added data = disk_mess data << @add_disk connection.configure_vm_disks(vm_href, data) end if @name_changed || @description_changed edit_uri = links.select {|i| i[:rel] == 'edit'} edit_uri = edit_uri.kind_of?(Array) ? edit_uri.flatten[0][:href] : edit_uri[:href] connection.configure_vm_name_description(edit_uri, self.name, self.description) end end reset_tracking true end def destroy if on? undeploy wait_for { off? } end wait_for { off? } # be sure.. wait_for { ready? } # be doubly sure.. sleep 2 # API lies. need to give it some time to be happy. connection.delete_vapp(href).body[:status] == "running" end alias :delete :destroy def vm_href load_unless_loaded! #require 'pp' #pp vm_data #vm_data[0][:Link].select {|v| v[:rel] == 'edit'}[0][:href] vm_data.kind_of?(Array)? vm_data[0][:href] : vm_data[:href] end private def reset_tracking @disk_change = false @changed = false @update_memory_value = nil @name_changed = false @description_changed = nil end def _compose_vapp_data { :name => name, :cpus => cpus[:count], :memory => memory[:amount], :disks => disks } end def virtual_hardware_section load_unless_loaded! vm[0][:"ovf:VirtualHardwareSection"][:"ovf:Item"] end def memory_mess load_unless_loaded! if virtual_hardware_section virtual_hardware_section.detect { |item| item[:"rasd:ResourceType"] == "4" } end end def cpu_mess load_unless_loaded! if virtual_hardware_section virtual_hardware_section.detect { |item| item[:"rasd:ResourceType"] == "3" } end end def disk_mess load_unless_loaded! if virtual_hardware_section virtual_hardware_section.select { |item| item[:"rasd:ResourceType"] == "17" } else [] end end def power_operation(op) requires :href begin connection.send(op.keys.first, href + "/power/action/#{op.values.first}" ) rescue Excon::Errors::InternalServerError => e #Frankly we shouldn't get here ... raise e unless e.to_s =~ /because it is already powered o(n|ff)/ end true end def reload_status self.status = connection.get_vapp(href).body[:status] end end end end end
28.917808
136
0.528896
26f0c87e1fd29f1ab96791a9ebc2280d68844cbe
2,126
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=172800' } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker # Add Rack::LiveReload to the bottom of the middleware stack with the default options: config.middleware.insert_after ActionDispatch::Static, Rack::LiveReload end
35.433333
88
0.764817
62194ad5b417993b0d057709ae6add8f921c2cd9
1,794
# encoding: utf-8 # This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # /spec/fixtures/responses/whois.eenet.ee/ee/status_registered.expected # # and regenerate the tests with the following rake task # # $ rake spec:generate # require 'spec_helper' require 'whois/parsers/whois.eenet.ee.rb' describe Whois::Parsers::WhoisEenetEe, "status_registered.expected" do subject do file = fixture("responses", "whois.eenet.ee/ee/status_registered.txt") part = Whois::Record::Part.new(body: File.read(file)) described_class.new(part) end describe "#status" do it do expect(subject.status).to eq(:registered) end end describe "#available?" do it do expect(subject.available?).to eq(false) end end describe "#registered?" do it do expect(subject.registered?).to eq(true) end end describe "#created_on" do it do expect(subject.created_on).to be_a(Time) expect(subject.created_on).to eq(Time.parse("2003-04-22")) end end describe "#updated_on" do it do expect(subject.updated_on).to be_a(Time) expect(subject.updated_on).to eq(Time.parse("2010-05-28")) end end describe "#expires_on" do it do expect { subject.expires_on }.to raise_error(Whois::AttributeNotSupported) end end describe "#nameservers" do it do expect(subject.nameservers).to be_a(Array) expect(subject.nameservers.size).to eq(2) expect(subject.nameservers[0]).to be_a(Whois::Parser::Nameserver) expect(subject.nameservers[0].name).to eq("ns1.google.com") expect(subject.nameservers[1]).to be_a(Whois::Parser::Nameserver) expect(subject.nameservers[1].name).to eq("ns2.google.com") end end end
26.776119
80
0.686734
7a3d1f90e6447f2e3c94b9f8669b7b7a09401d7f
1,034
class Cvsync < Formula homepage "http://www.cvsync.org/" url "http://www.cvsync.org/dist/cvsync-0.24.19.tar.gz" sha256 "75d99fc387612cb47141de4d59cb3ba1d2965157230f10015fbaa3a1c3b27560" depends_on "openssl" def install ENV["PREFIX"] = prefix ENV["MANDIR"] = man ENV["CVSYNC_DEFAULT_CONFIG"] = etc/"cvsync.conf" ENV["CVSYNCD_DEFAULT_CONFIG"] = etc/"cvsyncd.conf" ENV["HASH_TYPE"] = "openssl" # Makefile from 2005 assumes Darwin doesn't define `socklen_t' and defines # it with a CC macro parameter making gcc unhappy about double define. inreplace "mk/network.mk", /^CFLAGS \+= \-Dsocklen_t=int/, "" # Remove owner and group parameters from install. inreplace "mk/base.mk", /^INSTALL_(.{3})_OPTS\?=.*/, 'INSTALL_\1_OPTS?= -c -m ${\1MODE}' # These paths must exist or "make install" fails. bin.mkpath lib.mkpath man1.mkpath system "make", "install" end test do assert_match "#{version}", shell_output("#{bin}/cvsync -h 2>&1", 1) end end
28.722222
78
0.665377
912e565b8e4d978a7e437a19ce0898f90401e28e
1,146
# -*- encoding : utf-8 -*- module SlncFileColumnHelper def fc_thumbnail(im_path, mode, dim, link_original=true, title='') if im_path.to_s.strip != '' then im_path = '/' << im_path unless im_path =~ /^\// # TODO añadir parsing de dim si mode == f if mode == 'f' then style = 'style="width: ' << dim.split('x')[0] << 'px; height: ' << dim.split('x')[1] << 'px;"' else style = '' end html_out = '<img ' << style << ' src="/cache/thumbnails/' << mode << '/' << dim << im_path << '" />' if link_original '<a ' << 'title="' << tohtmlattribute(title) << '" href="' << im_path << '">' << html_out << '</a>' else html_out end else '' end end def fc_image(im_path, alt='') if im_path.to_s.strip != '' then im_path = '/' << im_path unless im_path =~ /^\// '<img alt="' << tohtmlattribute(alt) << '" src="' << im_path << '" />' else '' end end def fc_path(file_path) ((file_path =~ /^\//) ? file_path : '/' << file_path) unless file_path.nil? end end ActionView::Base.send :include, SlncFileColumnHelper
29.384615
107
0.521815
035392a07638c13c6038bc5878c1c573e254e64d
1,281
# # Be sure to run `pod lib lint SchibstedAccount.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'SchibstedAccount' s.version = '1.0.0-rc6' s.summary = "SDK for a Schibsted identity service" s.license = { :type => "MIT" } s.homepage = "https://schibsted.github.io/account-sdk-ios/" s.authors = { "Schibsted" => "[email protected]", } s.source = { :git => 'https://github.com/schibsted/account-sdk-ios.git', :tag => s.version.to_s } s.ios.deployment_target = '9.0' s.pod_target_xcconfig = { 'SWIFT_VERSION' => '4.0' } s.default_subspecs = ['Manager', 'UI'] s.subspec "Core" do |ss| ss.source_files = ['Source/Core/**/*.swift'] end s.subspec "Manager" do |ss| ss.source_files = ['Source/Manager/**/*.{h,m,swift}'] ss.resources = ['Source/Manager/Configuration.plist'] ss.dependency 'SchibstedAccount/Core' end s.subspec "UI" do |ss| ss.source_files = ['Source/UI/**/*.swift'] ss.resources = ['Source/UI/**/*.{lproj,storyboard,xcassets,xib,strings}'] ss.dependency 'SchibstedAccount/Manager' end end
29.113636
83
0.656518
bb6e4427a8e267a21f2f7f83ce548b9be813b060
2,935
#!/usr/bin/env ruby # Fetch all entries from a datbase, change entries as wanted and save them back again. # Use if you want to change the schema of an existing database. # # Author: srldl # ###################################################### require './server' require './config' require 'net/http' require 'net/ssh' require 'net/scp' require 'time' require 'date' require 'json' module Couch2 class MoveDatabase #Set server fetchHost = Couch::Config::HOST1 fetchPort = Couch::Config::PORT1 fetchPassword = Couch::Config::PASSWORD1 fetchUser = Couch::Config::USER1 #Post to server postHost = Couch::Config::HOST1 postPort = Couch::Config::PORT1 postPassword = Couch::Config::PASSWORD1 postUser = Couch::Config::USER1 #Get ready to put into database server = Couch::Server.new(fetchHost, fetchPort) server2 = Couch::Server.new(postHost, postPort) #Fetch from database db_res = server.get("/"+ Couch::Config::COUCH_DB_NAME + "/_all_docs") #Get ids res = JSON.parse(db_res.body) #Iterate over the Ids from Couch for i in 0..((res["rows"].size)-1) id = res["rows"][i]["id"] #id = "275d07fc-7cd9-cd10-7731-b01ed6679d94" #Fetch the entry with the id from database incl attachments #db_entry = server.get("/"+ Couch::Config::COUCH_EXPEDITION + "/"+id+"?attachments=true") db_entry = server.get("/"+ Couch::Config::COUCH_DB_NAME + "/"+id) @entry = JSON.parse(db_entry.body) # puts @entry if (@entry["total"] === "-1") puts @entry['id'] puts "total-----" #Remove total @entry.tap { |k| k.delete("total") } # p = @entry["other_info"].split('Contact person:', 2).last # puts p # q = p.split(',') # puts q[0] # @entry[:recorded_by_name] = q[0].strip end if ((@entry["files"] === "") || (@entry["files"] === nil)) then #Remove total puts @entry['id'] @entry.tap { |k| k.delete("files") } end # @entry[:kingdom] = 'animalia' #Remove end_date if empty # if (@entry["end_date"] == "") # @entry.tap { |k| k.delete("end_date") } # end #Copy to recorded_by_name #Need to remove revision - otherwise it will not save #@entry.tap { |k| k.delete("_rev") } #Post coursetype doc = @entry.to_json # puts doc #Get new id db_res2 = server2.post("/"+ Couch::Config::COUCH_DB_NAME + "/", doc, postUser, postPassword, "application/json; charset=utf-8") id2 = JSON.parse(db_res2.body) rev = id2["rev"] length = id2["length"] puts rev =begin unless att.nil? puts "att not nil!" server2.post("/"+ Couch::Config::COUCH_EXPEDITION_BKP + "/"+id2["id"]+"/attachment?rev="+rev.to_s, att, postUser, postPassword, content_type,length) end =end end #iterate over ids end #class end #module
24.872881
157
0.591482
2182f6aa8b5eece2bf789b73b4b3394bce2d0774
304
# frozen_string_literal: true class Array #:nodoc: def deep_symbolize_keys map(&:deep_symbolize_keys) end def deep_stringify_keys! map(&:deep_stringify_keys!) end def deep_stringify_keys map(&:deep_stringify_keys) end def except(*value) self - [value].flatten end end
15.2
31
0.713816
218590ad5ce82c93a3da92daa7019d1764b23d62
756
class SubjectSetSubjectCounterWorker include Sidekiq::Worker sidekiq_options queue: :data_high, congestion: Panoptes::CongestionControlConfig. counter_worker.congestion_opts.merge({ reject_with: :reschedule, key: ->(subject_set_id) { "subject_set_#{ subject_set_id }_counter_worker" } }), lock: :until_executing def perform(subject_set_id) # recount this set's subjects set = SubjectSet.find(subject_set_id) set.update_column(:set_member_subjects_count, set.set_member_subjects.count) set.touch # recount the subjects for each workflow this set is in set.workflow_ids.each do |workflow_id| WorkflowSubjectsCountWorker.perform_async(workflow_id) end end end
29.076923
80
0.723545
ff8aeb17c0eb2c482ad4531702b37a6e9034dabd
3,079
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads/v8/services/smart_campaign_setting_service.proto require 'google/ads/googleads/v8/enums/response_content_type_pb' require 'google/ads/googleads/v8/resources/smart_campaign_setting_pb' require 'google/api/annotations_pb' require 'google/api/client_pb' require 'google/api/field_behavior_pb' require 'google/api/resource_pb' require 'google/protobuf/field_mask_pb' require 'google/rpc/status_pb' require 'google/protobuf' Google::Protobuf::DescriptorPool.generated_pool.build do add_file("google/ads/googleads/v8/services/smart_campaign_setting_service.proto", :syntax => :proto3) do add_message "google.ads.googleads.v8.services.GetSmartCampaignSettingRequest" do optional :resource_name, :string, 1 end add_message "google.ads.googleads.v8.services.MutateSmartCampaignSettingsRequest" do optional :customer_id, :string, 1 repeated :operations, :message, 2, "google.ads.googleads.v8.services.SmartCampaignSettingOperation" optional :partial_failure, :bool, 3 optional :validate_only, :bool, 4 optional :response_content_type, :enum, 5, "google.ads.googleads.v8.enums.ResponseContentTypeEnum.ResponseContentType" end add_message "google.ads.googleads.v8.services.SmartCampaignSettingOperation" do optional :update, :message, 1, "google.ads.googleads.v8.resources.SmartCampaignSetting" optional :update_mask, :message, 2, "google.protobuf.FieldMask" end add_message "google.ads.googleads.v8.services.MutateSmartCampaignSettingsResponse" do optional :partial_failure_error, :message, 1, "google.rpc.Status" repeated :results, :message, 2, "google.ads.googleads.v8.services.MutateSmartCampaignSettingResult" end add_message "google.ads.googleads.v8.services.MutateSmartCampaignSettingResult" do optional :resource_name, :string, 1 optional :smart_campaign_setting, :message, 2, "google.ads.googleads.v8.resources.SmartCampaignSetting" end end end module Google module Ads module GoogleAds module V8 module Services GetSmartCampaignSettingRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v8.services.GetSmartCampaignSettingRequest").msgclass MutateSmartCampaignSettingsRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v8.services.MutateSmartCampaignSettingsRequest").msgclass SmartCampaignSettingOperation = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v8.services.SmartCampaignSettingOperation").msgclass MutateSmartCampaignSettingsResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v8.services.MutateSmartCampaignSettingsResponse").msgclass MutateSmartCampaignSettingResult = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v8.services.MutateSmartCampaignSettingResult").msgclass end end end end end
54.982143
185
0.786619
e8efc9158a5858caff28373a204ffc0455e345a4
157
include InitialTestData::Utilities include FactoryGirl::Syntax::Methods store create(:user), :test1 store create(:user), :test2 store create(:user), :test3
22.428571
36
0.77707
622fe37cc7186e65deeebbc4dba032fe94c580b1
454
Then(/^tuist graph$/) do system("swift", "run", "tuist", "graph", "--path", @dir, "--output-path", @dir) end Then(/^tuist graph of ([a-zA-Z]+)$/) do |target_name| system("swift", "run", "tuist", "graph", "--path", @dir, "--output-path", @dir, target_name) end Then(/^I should be able to open a graph file$/) do binary_path = File.join(@dir, "graph.png") out, err, status = Open3.capture3("file", binary_path) assert(status.success?, err) end
32.428571
94
0.625551
335227be614809957102452ef3925c01795f280a
192
class AddIndices < ActiveRecord::Migration def self.up change_table :user_activities do |t| t.index :activity_id t.index :created_at end end def self.down end end
16
42
0.682292
0805056ccfe5ee72085ae744b583810149296503
3,716
# Jekyll plugin for generating an rss 2.0 feed for posts # # Usage: place this file in the _plugins directory and set the required configuration # attributes in the _config.yml file # # Uses the following attributes in _config.yml: # name - the name of the site # url - the url of the site # description - (optional) a description for the feed (if not specified will be generated from name) # author - (optional) the author of the site (if not specified will be left blank) # copyright - (optional) the copyright of the feed (if not specified will be left blank) # rss_path - (optional) the path to the feed (if not specified "/" will be used) # rss_name - (optional) the name of the rss file (if not specified "rss.xml" will be used) # rss_post_limit - (optional) the number of posts in the feed # # Author: Assaf Gelber <[email protected]> # Site: http://agelber.com # Source: http://github.com/agelber/jekyll-rss # # Distributed under the MIT license # Copyright Assaf Gelber 2014 module Jekyll class RssFeed < Page; end class RssGenerator < Generator priority :low safe true # Generates an rss 2.0 feed # # site - the site # # Returns nothing def generate(site) require 'rss' require 'cgi/util' # Create the rss with the help of the RSS module rss = RSS::Maker.make("2.0") do |maker| maker.channel.title = site.config['name'] maker.channel.link = site.config['baseurl'] maker.channel.description = site.config['description'] || "RSS feed for #{site.config['name']}" maker.channel.author = site.config["author"] maker.channel.updated = site.posts.docs.map { |p| p.date }.max maker.channel.copyright = site.config['copyright'] post_limit = site.config['rss_post_limit'].nil? ? site.posts.docs.count : site.config['rss_post_limit'] - 1 site.posts.docs.reverse[0..post_limit].each do |doc| doc.read maker.items.new_item do |item| item.title = doc.data['title'] link = "#{site.config['baseurl']}#{doc.url}" item.guid.content = link item.link = link item.description = "<![CDATA[" + doc.data['excerpt'].to_s.gsub("\n", ' ').gsub(%r{</?[^>]+?>}, '').strip[0...150] + "]]>" item.updated = doc.date end end end # File creation and writing rss_path = ensure_slashes(site.config['rss_path'] || "/") rss_name = site.config['rss_name'] || "rss.xml" full_path = File.join(site.dest, rss_path) ensure_dir(full_path) # We only have HTML in our content_encoded field which is surrounded by CDATA. # So it should be safe to unescape the HTML. feed = CGI::unescapeHTML(rss.to_s) File.open("#{full_path}#{rss_name}", "w") { |f| f.write(feed) } # Add the feed page to the site pages site.pages << Jekyll::RssFeed.new(site, site.dest, rss_path, rss_name) end private # Ensures the given path has leading and trailing slashes # # path - the string path # # Return the path with leading and trailing slashes def ensure_slashes(path) ensure_leading_slash(ensure_trailing_slash(path)) end # Ensures the given path has a leading slash # # path - the string path # # Returns the path with a leading slash def ensure_leading_slash(path) path[0] == "/" ? path : "/#{path}" end # Ensures the given path has a trailing slash # # path - the string path # # Returns the path with a trailing slash def ensure_trailing_slash(path) path[-1] == "/" ? path : "#{path}/" end # Ensures the given directory exists # # path - the string path of the directory # # Returns nothing def ensure_dir(path) FileUtils.mkdir_p(path) end end end
31.491525
127
0.663886
f839fcae86bbd3e4c67440964d97c970345a5027
543
require 'test_helper' class RelationshipTest < ActiveSupport::TestCase def setup @relationship = Relationship.new(follower_id: users(:tester).id, followed_id: users(:seconder).id) end test "should be valid" do assert @relationship.valid? end test "should require a follower_id" do @relationship.follower_id = nil assert_not @relationship.valid? end test "should require a followed_id" do @relationship.followed_id = nil assert_not @relationship.valid? end end
22.625
70
0.6814
1cbef802aeadf1d4d9584458e409c68714418e61
296
require './init' use Rack::Static, :urls => ["/favicon.ico", "/classify.html", "/symbols.html", "/stylesheets", "/images", "/flash", "/javascripts", "/fonts"], :root => "public" map '/api' do run Detexify::LatexApp end run Class.new(Sinatra::Base) { get('/') { redirect '/classify.html' } }
29.6
160
0.621622
abd8479f3c97a1baac9166e6c5bae61e66f2a7ac
341
require 'rails' require 'jaya_mega_lotto/helper' module JayaMegaLotto class Railtie < Rails::Railtie initializer "mega_lotto.action_view" do ActiveSupport.on_load(:action_view) do include JayaMegaLotto::Helper end end rake_tasks do load 'jaya_mega_lotto/tasks/jaya_mega_lotto.rake' end end end
21.3125
55
0.721408
ed02b41dccacc176821e6de7f5c28b0b99611c01
676
module Mutations class UpdateReviewChecklist < GraphQL::Schema::Mutation argument :target_id, ID, required: true argument :review_checklist, GraphQL::Types::JSON, required: true description "Mettre à jour la liste de contrôle d'examen" field :success, Boolean, null: false def resolve(params) mutator = UpdateReviewChecklistMutator.new(context, params) if mutator.valid? mutator.update_review_checklist mutator.notify(:success, "Réussite "," La liste de contrôle de l'examen a bien été mise à jour") { success: true } else mutator.notify_errors { success: false } end end end end
28.166667
104
0.680473
5de1e9e9a4fb9af87e298f730b2021ad86f6011f
4,608
# frozen_string_literal: true require 'openssl/better_defaults/version' require 'openssl' # = Changes made by openssl/better_defaults # # == Miscellaneous resources # # 1. https://www.ruby-lang.org/en/news/2014/10/27/changing-default-settings-of-ext-openssl # 2. https://en.wikipedia.org/wiki/Transport_Layer_Security # 3. https://wiki.mozilla.org/Security/Server_Side_TLS # 4. https://ssllabs.com # 5. https://ssllabs.com/downloads/SSL_TLS_Deployment_Best_Practices.pdf # # == Rationale for disabling features # # Reason | Disabled features | Notes # =========================================================================== # | SSL 2.0 | https://tools.ietf.org/html/rfc6176 # BEST, LUCKY13 | SSL 3.0 Ciphers using CBC mode | # POODLE | SSL 3.0 | # RC4 weaknesses | All RC4-based ciphers | # CRIME | TLS Compression | http://arstechnica.com/security/2012/09/crime-hijacks-https-sessions/ # # === Note on CRIME/BREACH # # Disabling TLS compression avoids CRIME at the TLS level. However, both CRIME # and BREACH can be used against HTTP compression -- which is entirely out # of the scope of this library. # # See also, http://en.wikipedia.org/wiki/CRIME # # === Note on SSL/TLS versions # # Instead of being able to specify a minimum SSL version, OpenSSL only lets you # either enable an individual version, or enable everything. # # Individual options for disabling SSL 2.0 and SSL 3.0 are also available. # # Thus, to enable TLS 1.0+ only, you have to: # # 1. Enable SSL 2.0+ (set ssl_version to "SSLv23"), then # 2. disable SSL 2.0 (OP_NO_SSLv2) and SSL 3.0 (OP_NO_SSLv2). module OpenSSL module SSL class SSLContext remove_const(:DEFAULT_PARAMS) DEFAULT_PARAMS = { # Enable SSL 2.0+ and TLS 1.0+. SSL 2.0 and SSL 3.0 are disabled later on. # See the above NOTE on SSL versions. :ssl_version => 'SSLv23', # Verify the server's certificate against the certificate authority's # certificate. :verify_mode => OpenSSL::SSL::VERIFY_PEER, # TODO: Review cipher list. I copied ruby-lang.org's monkeypatch verbatim. :ciphers => %w{ ECDHE-ECDSA-AES128-GCM-SHA256 ECDHE-RSA-AES128-GCM-SHA256 ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-RSA-AES256-GCM-SHA384 DHE-RSA-AES128-GCM-SHA256 DHE-DSS-AES128-GCM-SHA256 DHE-RSA-AES256-GCM-SHA384 DHE-DSS-AES256-GCM-SHA384 ECDHE-ECDSA-AES128-SHA256 ECDHE-RSA-AES128-SHA256 ECDHE-ECDSA-AES128-SHA ECDHE-RSA-AES128-SHA ECDHE-ECDSA-AES256-SHA384 ECDHE-RSA-AES256-SHA384 ECDHE-ECDSA-AES256-SHA ECDHE-RSA-AES256-SHA DHE-RSA-AES128-SHA256 DHE-RSA-AES256-SHA256 DHE-RSA-AES128-SHA DHE-RSA-AES256-SHA DHE-DSS-AES128-SHA256 DHE-DSS-AES256-SHA256 DHE-DSS-AES128-SHA DHE-DSS-AES256-SHA AES128-GCM-SHA256 AES256-GCM-SHA384 AES128-SHA256 AES256-SHA256 AES128-SHA AES256-SHA !aNULL !eNULL !EXPORT !DES !RC4 !MD5 !PSK !aECDH !EDH-DSS-DES-CBC3-SHA !EDH-RSA-DES-CBC3-SHA !KRB5-DES-CBC3-SHA }.join(':'), :options => -> { # Start with ALL OF THE OPTIONS EVER ENABLED. opts = OpenSSL::SSL::OP_ALL # TODO: Determine the ACTUAL PURPOSE of this line. # (Was copy/pasted from the undocumented ruby-lang.org version.) opts &= ~OpenSSL::SSL::OP_DONT_INSERT_EMPTY_FRAGMENTS if defined?(OpenSSL::SSL::OP_DONT_INSERT_EMPTY_FRAGMENTS) # Disable compression, to avoid CRIME exploit. opts |= OpenSSL::SSL::OP_NO_COMPRESSION if defined?(OpenSSL::SSL::OP_NO_COMPRESSION) # Disable SSL 2.0 and 3.0 here because they conflate versions and options. # Seriously. This should not be specified in the options. # No. Go home, OpenSSL API, you're drunk. # # SSL 2.0 is disabled as recommended by RFC 6176 (see table at top of file). # SSL 3.0 is disabled due to the POODLE vulnerability. opts |= OpenSSL::SSL::OP_NO_SSLv2 if defined?(OpenSSL::SSL::OP_NO_SSLv2) opts |= OpenSSL::SSL::OP_NO_SSLv3 if defined?(OpenSSL::SSL::OP_NO_SSLv3) opts }.call }.freeze end end end
34.909091
126
0.603082
01739961c7cb6233925377a5032afb94c3404799
86
class ManageIQ::Providers::OracleCloud::NetworkManager::FloatingIp < ::FloatingIp end
28.666667
81
0.813953
1d81f53ee20b717d22827709fbf8eea5bb355ea8
2,678
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2020_02_29_220856) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "questions", force: :cascade do |t| t.text "content" t.text "answer_a" t.text "answer_b" t.text "answer_c" t.text "answer_d" t.string "correct_answer" t.bigint "round_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "question_number" t.index ["round_id"], name: "index_questions_on_round_id" end create_table "rounds", force: :cascade do |t| t.string "title" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "user_answers", force: :cascade do |t| t.bigint "user_id" t.bigint "round_id" t.bigint "question_id" t.string "correct_answer" t.string "user_input" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["question_id"], name: "index_user_answers_on_question_id" t.index ["round_id"], name: "index_user_answers_on_round_id" t.index ["user_id"], name: "index_user_answers_on_user_id" end create_table "user_rounds", force: :cascade do |t| t.bigint "user_id" t.bigint "round_id" t.integer "attempts" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["round_id"], name: "index_user_rounds_on_round_id" t.index ["user_id"], name: "index_user_rounds_on_user_id" end create_table "users", force: :cascade do |t| t.string "username" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_foreign_key "questions", "rounds" add_foreign_key "user_answers", "questions" add_foreign_key "user_answers", "rounds" add_foreign_key "user_answers", "users" add_foreign_key "user_rounds", "rounds" add_foreign_key "user_rounds", "users" end
36.189189
86
0.725915
01d4e9a5d1c6723b9792992bc7f2118328077dd9
8,331
# File based CMS require "sinatra" require "sinatra/reloader" if development? require "tilt/erubis" require "redcarpet" require "yaml" require "bcrypt" configure do enable :sessions set :session_secret, "secret" set :erb, escape_html: true if ENV["RACK_ENV"] == "test" set :public_folder, File.expand_path("/public", __FILE__) end end # HELPERS CALLED FROM ERB # ----------------------------------------------------------------------------- helpers do def duplicate_filename(filename) File.basename(filename, ".*") + "_copy" + File.extname(filename) end end # HELPERS # ----------------------------------------------------------------------------- def data_path if ENV["RACK_ENV"] == "test" File.expand_path("../test/data", __FILE__) else File.expand_path("../data", __FILE__) end end def images_path if ENV["RACK_ENV"] == "test" File.expand_path("../test/public/images", __FILE__) else File.expand_path("../public/images", __FILE__) end end def load_file_content(path) content = File.read(path) case File.extname(path) when ".md" erb render_markdown(content) when ".txt" headers["Content-Type"] = "text/plain;charset=utf-8" content end end def credentials_path if ENV["RACK_ENV"] == "test" File.expand_path("../test/users.yml", __FILE__) else File.expand_path("../users.yml", __FILE__) end end def load_users_credentials YAML.load_file(credentials_path) end def render_markdown(text) markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML) markdown.render(text) end # returns validation boolean status and message def validate_new_filename(filename) if filename.empty? [false, "A name is required"] elsif /[^\w\.]/ =~ filename [false, "Name must contain only alphanumeric chars or . or _"] elsif ![".txt", ".md"].include?(File.extname(filename)) [false, "Document must have .md or .txt extensions"] elsif valid_existing_file?(filename) [false, "Name already exists."] else [true, ""] end end def validate_filename(filename) filename = File.basename(filename) return filename if [".txt", ".md"].include?(File.extname(filename)) nil end def valid_existing_file?(filename) return false if filename.nil? File.file?(File.join(data_path, filename)) end def create_new_file(filename) path = File.join(data_path, filename) File.write(path, "") session[:message] = "#{filename} has been created" redirect "/" end def user_signed_in? !!session[:signed_in_user] end def redirect_if_signed_out return if user_signed_in? session[:message] = "You must be signed in to do that." get_list_of_files_and_images status 403 halt erb :index end def valid_login?(username, input_password) credentials = load_users_credentials return false unless credentials.key?(username) bcrypt_password = BCrypt::Password.new(credentials[username]) bcrypt_password == input_password end def valid_new_username?(username) return false if load_users_credentials.key?(username) return false if /\W/ =~ username true end def get_list_of_files_and_images pattern = File.join(data_path, "*") @files = Dir[pattern].select do |path| File.file?(path) && validate_filename(path) end @files = @files.map! { |file| File.basename(file) } image_pattern = File.join(images_path, "*.{png,jpg}") @images = Dir[image_pattern].select { |path| File.file?(path) } @images = @images.map! { |image| File.basename(image) } end # ROUTES # ----------------------------------------------------------------------------- # Show index get "/" do get_list_of_files_and_images erb :index end # Create new document post "/" do redirect_if_signed_out filename = params[:name] validation_status, validation_msg = validate_new_filename(filename) if validation_status path = File.join(data_path, filename) File.write(path, "") session[:message] = "#{filename} has been created" redirect "/" else session[:message] = validation_msg status 422 erb :new end end # Show sign in page get "/users/signin" do erb :sign_in end # Sign in post "/users/signin" do if user_signed_in? session[:message] = "You're already signed in" redirect "/" elsif valid_login?(params[:username], params[:password]) session[:signed_in_user] = params[:username] session[:message] = "Welcome!" redirect "/" else session[:message] = "Invalid credentials" @username = params[:username] status 422 erb :sign_in end end # Sign out post "/users/signout" do session.delete :signed_in_user session[:message] = "You have been signed out." redirect "/" end # Show sign up page get "/users/signup" do erb :sign_up end # Sign up new user post "/users/signup" do username = params[:username] if valid_new_username?(username) credentials = load_users_credentials credentials[username] = BCrypt::Password.create(params[:password]).to_s session[:message] = "User #{username} successfully created" File.write(credentials_path, credentials.to_yaml) redirect "/users/signin" else session[:message] = "Invalid username."\ "Username already exists or contains invalid characters." status 422 erb :sign_up end end # Show form for new document get "/new" do redirect_if_signed_out erb :new end # Show form for uploading image get "/upload_image" do redirect_if_signed_out erb :upload_image end # Upload image post "/upload_image" do redirect_if_signed_out @filename = params[:file][:filename] if %w(.png .jpg).include?(File.extname(@filename)) File.binwrite(File.join(images_path, @filename), params[:file][:tempfile].read) session[:message] = "Image has been uploaded successfully." redirect "/" else session[:message] = "Unsupported image format." status 422 erb :upload_image end end # Show document get "/:filename" do filename = validate_filename(params[:filename]) if valid_existing_file?(filename) load_file_content(File.join(data_path, filename)) else session[:message] = "File doesn't exist." redirect "/" end end # Submit edits of document post "/:filename" do redirect_if_signed_out filename = validate_filename(params[:filename]) if valid_existing_file?(filename) File.write(File.join(data_path, filename), params[:content]) session[:message] = "#{filename} has been updated." else session[:message] = "Can't edit non-existing document." end redirect "/" end # Show form for editing document get "/:filename/edit" do redirect_if_signed_out @filename = validate_filename(params[:filename]) if valid_existing_file?(@filename) @content = File.read(File.join(data_path, @filename)) erb :edit else session[:message] = "Can't edit non-existing document." redirect "/" end end # Show form for duplicating document get "/:source_filename/duplicate" do redirect_if_signed_out @source_filename = validate_filename(params[:source_filename]) if valid_existing_file?(@source_filename) erb :duplicate else session[:message] = "Can't duplicate non-existing document." redirect "/" end end # Duplicate document post "/:source_filename/duplicate" do redirect_if_signed_out new_filename = params[:name] validation_status, validation_msg = validate_new_filename(new_filename) @source_filename = validate_filename(params[:source_filename]) unless valid_existing_file?(@source_filename) validation_status = false validation_msg = "File to duplicate from doesn't exist." end if validation_status new_path = File.join(data_path, new_filename) source_path = File.join(data_path, @source_filename) File.write(new_path, File.read(source_path)) session[:message] = "#{new_filename} has been duplicated from #{@source_filename}" redirect "/" else session[:message] = validation_msg status 422 erb :duplicate end end # Delete document post "/:filename/delete" do redirect_if_signed_out @filename = validate_filename(params[:filename]) if valid_existing_file?(@filename) File.delete(File.join(data_path, @filename)) session[:message] = "#{@filename} deleted successfully." else session[:message] = "Can't delete non-existing document." end redirect "/" end
24.647929
79
0.690913
286d4285e5227e895f5552f78d5c7e8994293bc9
12,753
# 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. # config.secret_key = '79a09f83c662b605f202ef4f059befd0175785135596e1e9ac3162fb26fcf8cac1c341ff69416b86fa86da50da7c7ac5fe75e0e32bd9e6c96fb7b160494b4b27' # ==> 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 = '0dcfe92a446264fc3f7bed584667bdac2e1a7999a5e55bd2f7e6198ceddaa711516dd5fea41717206f5a25ef5114fc571d4776306cbc0f6f4a0e8a76032beb79' # ==> 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..128 # 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 # If true, expires auth token on session timeout. # config.expire_auth_token_on_timeout = false # ==> 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 # ==> 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.05
154
0.750333
26055773346fec928a5de3df4112f1fb3c1f1e1b
2,021
class StoryDataController < ApplicationController include MyUtility before_action :set_story_datum, only: [:show, :edit, :update, :destroy] # GET /story_data def index param_set @count = StoryDatum.search(params[:q]).result.count() @search = StoryDatum.page(params[:page]).search(params[:q]) @search.sorts = 'id asc' if @search.sorts.empty? @story_data = @search.result.per(50) end def param_set @latest_result = Name.maximum('result_no') params_clean(params) reference_number_assign(params, "story_no", "story_no_form") reference_number_assign(params, "title", "title_form") reference_number_assign(params, "max_page", "max_page_form") @pc_name_form = params["pc_name_form"] @story_no_form = params["story_no_form"] @title_form = params["title_form"] @max_page_form = params["max_page_form"] end # GET /story_data/1 #def show #end # GET /story_data/new #def new # @story_datum = StoryDatum.new #end # GET /story_data/1/edit #def edit #end # POST /story_data #def create # @story_datum = StoryDatum.new(story_datum_params) # if @story_datum.save # redirect_to @story_datum, notice: 'Story datum was successfully created.' # else # render action: 'new' # end #end # PATCH/PUT /story_data/1 #def update # if @story_datum.update(story_datum_params) # redirect_to @story_datum, notice: 'Story datum was successfully updated.' # else # render action: 'edit' # end #end # DELETE /story_data/1 #def destroy # @story_datum.destroy # redirect_to story_data_url, notice: 'Story datum was successfully destroyed.' #end private # Use callbacks to share common setup or constraints between actions. def set_story_datum @story_datum = StoryDatum.find(params[:id]) end # Only allow a trusted parameter "white list" through. def story_datum_params params.require(:story_datum).permit(:story_no, :title, :max_page) end end
25.910256
82
0.687778
7a2d559edf1d982719d3b659dc79abc3b6d0d804
3,143
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2014, Google Inc. All Rights Reserved. # # License:: 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. # # This example creates a content metadata key hierarchy. # # This feature is only available to DFP video publishers. require 'securerandom' require 'dfp_api' def create_content_metadata_key_hierarchies(dfp, hierarchy_level_one_key_id, hierarchy_level_two_key_id) # Get the ContentMetadataKeyHierarchyService. cmkh_service = dfp.service(:ContentMetadataKeyHierarchyService, API_VERSION) hierarchy_level_1 = { :custom_targeting_key_id => hierarchy_level_own_key_id, :hierarchy_level => 1 } hierarchy_level_2 = { :custom_targeting_key_id => hierarchy_level_two_key_id, :hierarchy_level => 2 } hierarchy_levels = [hierarchy_level_1, hierarchy_level_2] content_metadata_key_hierarchy = { :name => 'Content Metadata Key Hierarchy %d' % SecureRandom.uuid(), :hierarchy_levels => hierarchy_levels } # Create the content metadata key hierarchy on the server. content_metadata_key_hierarchies = cmkh_service.create_content_metadata_key_hierarchies( [content_metadata_key_hierarchy] ) content_metadata_key_hierarchies.each do |content_metadata_key_hierarchy| puts ('A content metadata key hierarchy with ID %d, name "%s", and %d ' + 'levels was created.') % [content_metadata_key_hierarchy[:id], content_metadata_key_hierarchy[:name], content_metadata_key_hierarchy[:hierarchy_levels].length] end end if __FILE__ == $0 API_VERSION = :v201805 # Get DfpApi instance and load configuration from ~/dfp_api.yml. dfp = DfpApi::Api.new # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in # the configuration file or provide your own logger: # dfp.logger = Logger.new('dfp_xml.log') begin hierarchy_level_one_key_id = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'.to_i hierarchy_level_two_key_id = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'.to_i create_content_metadata_key_hierarchies( dfp, hierarchy_level_one_key_id, hierarchy_level_two_key_id ) # HTTP errors. rescue AdsCommon::Errors::HttpError => e puts "HTTP Error: %s" % e # API errors. rescue DfpApi::Errors::ApiException => e puts "Message: %s" % e.message puts 'Errors:' e.errors.each_with_index do |error, index| puts "\tError [%d]:" % (index + 1) error.each do |field, value| puts "\t\t%s: %s" % [field, value] end end end end
33.084211
79
0.714286
d5b5e5410ee5cc21cb2592f552bccc93cd4f315e
318
module GitHubClassroom def self.github_client(options = {}) client_options = { client_id: Rails.application.secrets.github_client_id, client_secret: Rails.application.secrets.github_client_secret, auto_paginate: true }.merge!(options) Octokit::Client.new(client_options) end end
26.5
68
0.726415
abfd5e42b071955ec8d2c32ce30441d0e506fdc8
234
require "rails_helper" RSpec.describe App::CategoryViewer, type: :helper do it_should_behave_like "a viewer" do let(:model_name) { :category } let(:field_name) { :name } let(:input_field_tag) { "input" } end end
15.6
52
0.675214
339d341c5b89e193247cbc62d4c4b5fcf6fd0855
96
# frozen_string_literal: true class ContactInformationController < StandardStepsController end
19.2
60
0.875