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
9199320934923ef141c59b2bc5310754818d337b
14,125
require 'open3' require 'salus/scan_report' require 'salus/shell_result' require 'salus/bugsnag' require 'shellwords' module Salus::Scanners # Super class for all scanner objects. class Base class UnhandledExitStatusError < StandardError; end class InvalidScannerInvocationError < StandardError; end include Salus::SalusBugsnag attr_reader :report def initialize(repository:, config:) @repository = repository @config = config @report = Salus::ScanReport.new( name, custom_failure_message: @config['failure_message'] ) end def name self.class.name.sub('Salus::Scanners::', '') end # The scanning logic or something that calls a scanner. def run raise NoMethodError end # Returns TRUE if this scanner is appropriate for this repo, ELSE false. def should_run? raise NoMethodError end # Wraps the actual workhorse #run method with some boilerplate: # - appends the scan report to the given global salus report # - uses the #record method of @report to record the running time of the scan, # and also to pass/fail the scan if #run failed to do so # - catches any exceptions, appending them to both the scan report's error # collection and the global salus scan's error collection def run!(salus_report:, required:, pass_on_raise:, reraise:) salus_report.add_scan_report(@report, required: required) begin @report.record { run } if @report.errors.any? pass_on_raise ? @report.pass : @report.fail end rescue StandardError => e error_data = { message: "Unhandled exception running #{name}: #{e.class}: #{e}", error_class: e.class, backtrace: e.backtrace.take(5) } pass_on_raise ? @report.pass : @report.fail # Record the error so that the Salus report captures the issue. @report.error(error_data) salus_report.error(error_data) raise if reraise end end # Runs a command on the terminal. def run_shell(command, env: {}, stdin_data: '') # If we're passed a string, convert it to an array beofre passing to capture3 command = command.split unless command.is_a?(Array) Salus::ShellResult.new(*Open3.capture3(env, *command, stdin_data: stdin_data)) end # Add a textual logline to the report. This is for humans def log(string) @report.log(string) end # Tag the report as having completed successfully def report_success @report.pass end # Tag the report as having failed # (ie. a vulnerability was found, the scanner errored out, etc) def report_failure @report.fail end # Report information about this scan. def report_info(type, message) @report.info(type, message) end # Report a scanner warning such as a possible misconfiguration def report_warn(type, message) @report.warn(type, message) bugsnag_notify(message) end # Report the STDOUT from the scanner. def report_stdout(stdout) @report.info(:stdout, stdout) end # Report the STDERR from the scanner. def report_stderr(stderr) @report.info(:stderr, stderr) end # Report an error in a scanner. def report_error(message, hsh = {}) hsh[:message] = message @report.error(hsh) bugsnag_notify(message) end # Report a dependency of the project def report_dependency(file, hsh = {}) hsh = hsh.merge(dependency_file: file) @report.dependency(hsh) end protected def validate_bool_option(keyword, value) return true if %w[true false].include?(value.to_s.downcase) report_warn(:scanner_misconfiguration, "Expecting #{keyword} to be a Boolean (true/false) \ value but got \ #{"'#{value}'" || 'empty string'} \ instead.") false end def validate_string_option(keyword, value, regex) return true if value&.match?(regex) report_warn(:scanner_misconfiguration, "Expecting #{keyword} to match the regex #{regex} \ but got \ #{"'#{value}'" || 'empty string'} \ instead.") false end def validate_list_option(keyword, value, regex) if value.nil? report_warn(:scanner_misconfiguration, "Expecting non-empty values in #{keyword}") return false end return true if value&.all? { |option| option.match?(regex) } offending_values = value&.reject { |option| option.match?(regex) } report_warn(:scanner_misconfiguration, "Expecting values in #{keyword} to match regex \ '#{regex}' value but the offending values are \ '#{offending_values.join(', ')}'.") false end def validate_file_option(keyword, value) if value.nil? report_warn(:scanner_misconfiguration, "Expecting file/dir defined by #{keyword} to be \ a located in the project repo but got empty string \ instead.") return false end begin config_dir = File.realpath(value) rescue Errno::ENOENT report_warn(:scanner_misconfiguration, "Could not find #{config_dir} defined by \ #{keyword} when expanded into a fully qualified \ path. Value was #{value}") return false end return true if config_dir.include?(Dir.pwd) # assumes the current directory is the proj dir report_warn(:scanner_misconfiguration, "Expecting #{value} defined by \ #{keyword} to be a dir in the project repo but was \ located at '#{config_dir}' instead.") false end # Ex. in scanner config yaml, 'level' can be 'LOW', 'MEDIUM', or 'HIGH'. # We want # level: LOW mapped to config option -l # level: MEDIUM mapped to config option -ll # level: HIGH mapped to config option -lll # # Example input # {{'level' => { 'LOW' => 'l', 'MEDIUM' => 'll', 'HIGH' => 'lll'}, # {'confidence' => { 'LOW' => 'i', 'MEDIUM' => 'ii', 'HIGH' => 'iii'}} def build_flag_args_from_string(string_flag_map) arg_map = {} string_flag_map.each do |string_key, flag_map| arg_map.merge!(build_flag_arg_from_string(string_key, flag_map)) end arg_map end def build_flag_arg_from_string(key, flag_map) arg_map = {} val = @config[key] if val val.upcase! flag = flag_map[val] if flag @config[flag] = true arg_map[flag.to_sym] = { type: :flag, keyword: flag } else msg = "User specified val #{val} for key #{key} not found in scanner configs" report_warn(:scanner_misconfiguration, msg) end end arg_map end def create_flag_option(keyword:, value:, prefix:, suffix:) return '' unless validate_bool_option(keyword, value) if value.to_s.downcase == "true" "#{prefix}#{keyword}#{suffix}" else '' end end def create_bool_option(keyword:, value:, prefix:, separator:, suffix:) return '' unless validate_bool_option(keyword, value) "#{prefix}#{keyword}#{separator}#{Shellwords.escape(value)}#{suffix}" end def create_file_option(keyword:, value:, prefix:, separator:, suffix:) return '' unless validate_file_option(keyword, value) "#{prefix}#{keyword}#{separator}#{Shellwords.escape(value)}#{suffix}" end def create_string_option(keyword:, value:, prefix:, separator:, suffix:, regex: /.*/) return '' unless validate_string_option(keyword, value, regex) "#{prefix}#{keyword}#{separator}#{Shellwords.escape(value)}#{suffix}" end def create_list_option( keyword:, value:, prefix:, separator:, suffix:, regex: /.*/, join_by: ',' ) return '' unless validate_list_option(keyword, value, regex) "#{prefix}#{keyword}#{separator}#{Shellwords.escape(value.join(join_by))}#{suffix}" end def create_list_file_option(keyword:, value:, prefix:, separator:, suffix:, join_by: ',') validated_files = value.select do |file| validate_file_option(keyword, file) end "#{prefix}#{keyword}#{separator}#{Shellwords.escape(validated_files.join(join_by))}#{suffix}" end public def build_option( prefix:, suffix:, separator:, keyword:, value:, type:, regex: /.*/, join_by: ',', max_depth: 1 ) clean_type = type.to_sym.downcase case clean_type when :flag, :string, :bool, :booleans, :file # Allow repeat values if max_depth.positive? && value.is_a?(Array) value.reduce('') do |options, item| options + build_option( type: clean_type, keyword: keyword, value: item, # Use each item in the array as the value prefix: prefix, separator: separator, suffix: suffix, max_depth: max_depth - 1, regex: regex, join_by: join_by ) end else case clean_type when :string create_string_option( keyword: keyword, value: value, prefix: prefix, suffix: suffix, separator: separator, regex: regex ) when :bool, :booleans create_bool_option( keyword: keyword, value: value, prefix: prefix, suffix: suffix, separator: separator ) when :flag create_flag_option(keyword: keyword, value: value, prefix: prefix, suffix: suffix) when :file create_file_option( keyword: keyword, value: value, prefix: prefix, suffix: suffix, separator: separator ) end end when :list create_list_option( keyword: keyword, value: value, prefix: prefix, separator: separator, suffix: suffix, regex: regex, join_by: join_by ) when :list_file, :file_list create_list_file_option( keyword: keyword, value: value, prefix: prefix, separator: separator, suffix: suffix, join_by: join_by ) else report_warn( :scanner_misconfiguration, "Could not interpolate config #{keyword_string} \ the type of #{type}. " ) '' # Return an empty string and warn end end def build_options(prefix:, suffix:, separator:, args:, join_by: ',') default_regex = /.*/ args.reduce('') do |options, (keyword, type_value)| keyword_string = keyword.to_s option = if @config.key?(keyword_string) config_value = @config.fetch(keyword_string) case type_value when Symbol, String build_option( prefix: prefix, suffix: suffix, separator: separator, type: type_value, keyword: keyword_string, value: config_value, join_by: join_by, regex: default_regex ) when Hash # If you are doing something complicated if type_value[:type].nil? warning = "Could not interpolate config \ defined by since there was no type defined in the hash " report_warn(:scanner_misconfiguration, warning) '' # Return an empty string and warn else build_option( prefix: type_value[:prefix] || prefix, suffix: type_value[:suffix] || suffix, separator: type_value[:separator] || separator, keyword: type_value[:keyword] || keyword_string, value: config_value, type: type_value[:type], regex: type_value[:regex] || default_regex, join_by: type_value[:join_by] || join_by ) end when Regexp # Assume it is a string type if just regex is supplied build_option( prefix: prefix, suffix: suffix, separator: separator, type: :string, keyword: keyword_string, value: config_value, join_by: join_by, regex: type_value ) else warning = "Could not interpolate config for #{keyword} \ defined by since the value provided was not a String, Symbol, Regexp or Hash" report_warn(:scanner_misconfiguration, warning) '' # Return an empty string and warn end else '' # Not in the config, just return an empty string end options + option end end end end
33.235294
100
0.546053
ed0311d12857d05cf153b96f2e0f5ed82a42c9b9
541
# frozen_string_literal: true require "bundler/setup" require "englishize_digits" require "active_attr" require "englishize_digits/matchers" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end # Avoid annoying deprecation warning # I18n.enforce_available_locales = true
24.590909
66
0.780037
91aa7e2de3210c0a14de08a827ded8fcfc23cb59
2,219
require 'active_record' require 'fileutils' require 'logger' require 'yaml' module SimplyTranslatable module Test module Database extend self DB_CONFIG = File.expand_path('../database.yml', __FILE__) DRIVER = 'mysql' DEFAULT_STRATEGY = :transaction def load_db require File.expand_path('../../data/data', __FILE__) end def connect puts "CONFIG: #{config[DRIVER]}" ::ActiveRecord::Base.establish_connection config[DRIVER] load_db if in_memory? ::ActiveRecord::Migration.verbose = false load_schema ::ActiveRecord::Schema.migrate :up puts "Migrated in memory" else puts "NOT IN MEMORY" end end def config @config ||= YAML::load(File.open(DB_CONFIG)) end def in_memory? config[DRIVER]['database'].present? end def create! db_config = config[DRIVER] command = case DRIVER when "mysql" "mysql -u #{db_config['username']} -e 'create database #{db_config['database']} character set utf8 collate utf8_general_ci;' >/dev/null" when "postgres", "postgresql" "psql -c 'create database #{db_config['database']};' -U #{db_config['username']} >/dev/null" end puts command end def drop! db_config = config[DRIVER] command = case DRIVER when "mysql" "mysql -u #{db_config['username']} -e 'drop database #{db_config["database"]};' >/dev/null" when "postgres", "postgresql" "psql -c 'drop database #{db_config['database']};' -U #{db_config['username']} >/dev/null" end puts command end def migrate! return if in_memory? ::ActiveRecord::Migration.verbose = true connect load_schema ::ActiveRecord::Schema.migrate :up end def cleaning_strategy(strategy, &block) DatabaseCleaner.clean DatabaseCleaner.cleaning(&block) DatabaseCleaner.strategy = DEFAULT_STRATEGY end def load_schema require File.expand_path('../../data/data', __FILE__) end end end end
25.802326
146
0.590807
7ac7543a786f417ce1761a03ae8abf521b6880d7
13,750
require 'spec_helper' require 'openssl' require 'puppet/network/http' require 'puppet/network/http_pool' describe Puppet::Network::HTTP::Pool do before :each do Puppet::SSL::Key.indirection.terminus_class = :memory Puppet::SSL::CertificateRequest.indirection.terminus_class = :memory end let(:site) do Puppet::Network::HTTP::Site.new('https', 'rubygems.org', 443) end let(:different_site) do Puppet::Network::HTTP::Site.new('https', 'github.com', 443) end let(:ssl_context) { Puppet::SSL::SSLContext.new } let(:verifier) do v = Puppet::SSL::Verifier.new(site.host, ssl_context) allow(v).to receive(:setup_connection) v end def create_pool Puppet::Network::HTTP::Pool.new end def create_pool_with_connections(site, *connections) pool = Puppet::Network::HTTP::Pool.new connections.each do |conn| pool.release(site, verifier, conn) end pool end def create_pool_with_http_connections(site, *connections) pool = Puppet::Network::HTTP::Pool.new connections.each do |conn| pool.release(site, nil, conn) end pool end def create_pool_with_expired_connections(site, *connections) # setting keepalive timeout to -1 ensures any newly added # connections have already expired pool = Puppet::Network::HTTP::Pool.new(-1) connections.each do |conn| pool.release(site, verifier, conn) end pool end def create_connection(site) double(site.addr, :started? => false, :start => nil, :finish => nil, :use_ssl? => true, :verify_mode => OpenSSL::SSL::VERIFY_PEER) end def create_http_connection(site) double(site.addr, :started? => false, :start => nil, :finish => nil, :use_ssl? => false) end context 'when yielding a connection' do it 'yields a connection' do conn = create_connection(site) pool = create_pool_with_connections(site, conn) expect { |b| pool.with_connection(site, verifier, &b) }.to yield_with_args(conn) end it 'returns the connection to the pool' do conn = create_connection(site) expect(conn).to receive(:started?).and_return(true) pool = create_pool pool.release(site, verifier, conn) pool.with_connection(site, verifier) { |c| } expect(pool.pool[site].first.connection).to eq(conn) end it 'can yield multiple connections to the same site' do lru_conn = create_connection(site) mru_conn = create_connection(site) pool = create_pool_with_connections(site, lru_conn, mru_conn) pool.with_connection(site, verifier) do |a| expect(a).to eq(mru_conn) pool.with_connection(site, verifier) do |b| expect(b).to eq(lru_conn) end end end it 'propagates exceptions' do conn = create_connection(site) pool = create_pool pool.release(site, verifier, conn) expect { pool.with_connection(site, verifier) do |c| raise IOError, 'connection reset' end }.to raise_error(IOError, 'connection reset') end it 'does not re-cache connections when an error occurs' do # we're not distinguishing between network errors that would # suggest we close the socket, and other errors conn = create_connection(site) pool = create_pool pool.release(site, verifier, conn) expect(pool).not_to receive(:release).with(site, verifier, conn) pool.with_connection(site, verifier) do |c| raise IOError, 'connection reset' end rescue nil end it 'sets keepalive bit on network socket' do pool = create_pool s = Socket.new(Socket::PF_INET, Socket::SOCK_STREAM) pool.setsockopts(Net::BufferedIO.new(s)) # On windows, Socket.getsockopt() doesn't return exactly the same data # as an equivalent Socket::Option.new() statement, so we strip off the # unrelevant bits only on this platform. # # To make sure we're not voiding the test case by doing this, we check # both with and without the keepalive bit set. # # This workaround can be removed once all the ruby versions we care about # have the patch from https://bugs.ruby-lang.org/issues/11958 applied. # if Puppet::Util::Platform.windows? keepalive = Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, true).data[0] nokeepalive = Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, false).data[0] expect(s.getsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE).data).to eq(keepalive) expect(s.getsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE).data).to_not eq(nokeepalive) else expect(s.getsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE).bool).to eq(true) end end context 'when releasing connections' do it 'releases HTTP connections' do conn = create_connection(site) expect(conn).to receive(:use_ssl?).and_return(false) expect(conn).to receive(:started?).and_return(true) pool = create_pool_with_connections(site, conn) expect(pool).to receive(:release).with(site, verifier, conn) pool.with_connection(site, verifier) {|c| } end it 'releases secure HTTPS connections' do conn = create_connection(site) expect(conn).to receive(:use_ssl?).and_return(true) expect(conn).to receive(:verify_mode).and_return(OpenSSL::SSL::VERIFY_PEER) expect(conn).to receive(:started?).and_return(true) pool = create_pool_with_connections(site, conn) expect(pool).to receive(:release).with(site, verifier, conn) pool.with_connection(site, verifier) {|c| } end it 'closes insecure HTTPS connections' do conn = create_connection(site) expect(conn).to receive(:use_ssl?).and_return(true) expect(conn).to receive(:verify_mode).and_return(OpenSSL::SSL::VERIFY_NONE) pool = create_pool_with_connections(site, conn) expect(pool).not_to receive(:release).with(site, verifier, conn) pool.with_connection(site, verifier) {|c| } end it "doesn't add a closed connection back to the pool" do http = Net::HTTP.new(site.addr) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.start pool = create_pool_with_connections(site, http) pool.with_connection(site, verifier) {|c| c.finish} expect(pool.pool[site]).to be_nil end end end context 'when borrowing' do it 'returns a new connection if the pool is empty' do conn = create_connection(site) pool = create_pool expect(pool.factory).to receive(:create_connection).with(site).and_return(conn) expect(pool.borrow(site, verifier)).to eq(conn) end it 'returns a matching connection' do conn = create_connection(site) pool = create_pool_with_connections(site, conn) expect(pool.factory).not_to receive(:create_connection) expect(pool.borrow(site, verifier)).to eq(conn) end it 'returns a new connection if there are no matching sites' do different_conn = create_connection(different_site) pool = create_pool_with_connections(different_site, different_conn) conn = create_connection(site) expect(pool.factory).to receive(:create_connection).with(site).and_return(conn) expect(pool.borrow(site, verifier)).to eq(conn) end it 'returns a new HTTP connection if the cached connection is HTTPS' do https_site = Puppet::Network::HTTP::Site.new('https', 'www.example.com', 443) old_conn = create_connection(https_site) pool = create_pool_with_connections(https_site, old_conn) http_site = Puppet::Network::HTTP::Site.new('http', 'www.example.com', 443) new_conn = create_http_connection(http_site) allow(pool.factory).to receive(:create_connection).with(http_site).and_return(new_conn) expect(pool.borrow(http_site, nil)).to eq(new_conn) end it 'returns a new HTTPS connection if the cached connection is HTTP' do http_site = Puppet::Network::HTTP::Site.new('http', 'www.example.com', 443) old_conn = create_http_connection(http_site) pool = create_pool_with_http_connections(http_site, old_conn) https_site = Puppet::Network::HTTP::Site.new('https', 'www.example.com', 443) new_conn = create_connection(https_site) allow(pool.factory).to receive(:create_connection).with(https_site).and_return(new_conn) expect(pool.borrow(https_site, verifier)).to eq(new_conn) end it 'returns a new connection if the ssl contexts are different' do old_conn = create_connection(site) pool = create_pool_with_connections(site, old_conn) new_conn = create_connection(site) allow(pool.factory).to receive(:create_connection).with(site).and_return(new_conn) new_verifier = Puppet::SSL::Verifier.new(site.host, Puppet::SSL::SSLContext.new) allow(new_verifier).to receive(:setup_connection) # 'equal' tests that it's the same object expect(pool.borrow(site, new_verifier)).to eq(new_conn) end it 'returns a cached connection if the ssl contexts are the same' do old_conn = create_connection(site) pool = create_pool_with_connections(site, old_conn) expect(pool.factory).not_to receive(:create_connection) # 'equal' tests that it's the same object new_verifier = Puppet::SSL::Verifier.new(site.host, ssl_context) expect(pool.borrow(site, new_verifier)).to equal(old_conn) end it 'returns a cached connection if both connections are http' do http_site = Puppet::Network::HTTP::Site.new('http', 'www.example.com', 80) old_conn = create_http_connection(http_site) pool = create_pool_with_http_connections(http_site, old_conn) # 'equal' tests that it's the same object expect(pool.borrow(http_site, nil)).to equal(old_conn) end it 'returns started connections' do conn = create_connection(site) expect(conn).to receive(:start) pool = create_pool expect(pool.factory).to receive(:create_connection).with(site).and_return(conn) expect(pool.borrow(site, verifier)).to eq(conn) end it "doesn't start a cached connection" do conn = create_connection(site) expect(conn).not_to receive(:start) pool = create_pool_with_connections(site, conn) pool.borrow(site, verifier) end it 'returns the most recently used connection from the pool' do least_recently_used = create_connection(site) most_recently_used = create_connection(site) pool = create_pool_with_connections(site, least_recently_used, most_recently_used) expect(pool.borrow(site, verifier)).to eq(most_recently_used) end it 'finishes expired connections' do conn = create_connection(site) allow(conn).to receive(:started?).and_return(true) expect(conn).to receive(:finish) pool = create_pool_with_expired_connections(site, conn) expect(pool.factory).to receive(:create_connection).and_return(double('conn', :start => nil, :use_ssl? => true)) pool.borrow(site, verifier) end it 'logs an exception if it fails to close an expired connection' do expect(Puppet).to receive(:log_exception).with(be_a(IOError), "Failed to close connection for #{site}: read timeout") conn = create_connection(site) expect(conn).to receive(:started?).and_return(true) expect(conn).to receive(:finish).and_raise(IOError, 'read timeout') pool = create_pool_with_expired_connections(site, conn) expect(pool.factory).to receive(:create_connection).and_return(double('open_conn', :start => nil, :use_ssl? => true)) pool.borrow(site, verifier) end it 'deletes the session when the last connection is borrowed' do conn = create_connection(site) pool = create_pool_with_connections(site, conn) pool.borrow(site, verifier) expect(pool.pool[site]).to be_nil end end context 'when releasing a connection' do it 'adds the connection to an empty pool' do conn = create_connection(site) pool = create_pool pool.release(site, verifier, conn) expect(pool.pool[site].first.connection).to eq(conn) end it 'adds the connection to a pool with a connection for the same site' do pool = create_pool pool.release(site, verifier, create_connection(site)) pool.release(site, verifier, create_connection(site)) expect(pool.pool[site].count).to eq(2) end it 'adds the connection to a pool with a connection for a different site' do pool = create_pool pool.release(site, verifier, create_connection(site)) pool.release(different_site, verifier, create_connection(different_site)) expect(pool.pool[site].count).to eq(1) expect(pool.pool[different_site].count).to eq(1) end end context 'when closing' do it 'clears the pool' do pool = create_pool pool.close expect(pool.pool).to be_empty end it 'closes all cached connections' do conn = create_connection(site) allow(conn).to receive(:started?).and_return(true) expect(conn).to receive(:finish) pool = create_pool_with_connections(site, conn) pool.close end it 'allows a connection to be closed multiple times safely' do http = Net::HTTP.new(site.addr) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.start pool = create_pool expect(pool.close_connection(site, http)).to eq(true) expect(pool.close_connection(site, http)).to eq(false) end end end
33.783784
134
0.683709
21a668d748354df1bba13e0afdbe41f1b9561395
5,909
# 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::Policy::Mgmt::V2019_01_01 module Models # # The policy assignment. # class PolicyAssignment include MsRestAzure # @return [String] The display name of the policy assignment. attr_accessor :display_name # @return [String] The ID of the policy definition or policy set # definition being assigned. attr_accessor :policy_definition_id # @return [String] The scope for the policy assignment. attr_accessor :scope # @return [Array<String>] The policy's excluded scopes. attr_accessor :not_scopes # @return Required if a parameter is used in policy rule. attr_accessor :parameters # @return [String] This message will be part of response in case of # policy violation. attr_accessor :description # @return The policy assignment metadata. attr_accessor :metadata # @return [String] The ID of the policy assignment. attr_accessor :id # @return [String] The type of the policy assignment. attr_accessor :type # @return [String] The name of the policy assignment. attr_accessor :name # @return [PolicySku] The policy sku. This property is optional, # obsolete, and will be ignored. attr_accessor :sku # @return [String] The location of the policy assignment. Only required # when utilizing managed identity. attr_accessor :location # @return [Identity] The managed identity associated with the policy # assignment. attr_accessor :identity # # Mapper for PolicyAssignment class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'PolicyAssignment', type: { name: 'Composite', class_name: 'PolicyAssignment', model_properties: { display_name: { client_side_validation: true, required: false, serialized_name: 'properties.displayName', type: { name: 'String' } }, policy_definition_id: { client_side_validation: true, required: false, serialized_name: 'properties.policyDefinitionId', type: { name: 'String' } }, scope: { client_side_validation: true, required: false, serialized_name: 'properties.scope', type: { name: 'String' } }, not_scopes: { client_side_validation: true, required: false, serialized_name: 'properties.notScopes', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, parameters: { client_side_validation: true, required: false, serialized_name: 'properties.parameters', type: { name: 'Object' } }, description: { client_side_validation: true, required: false, serialized_name: 'properties.description', type: { name: 'String' } }, metadata: { client_side_validation: true, required: false, serialized_name: 'properties.metadata', type: { name: 'Object' } }, id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, sku: { client_side_validation: true, required: false, serialized_name: 'sku', type: { name: 'Composite', class_name: 'PolicySku' } }, location: { client_side_validation: true, required: false, serialized_name: 'location', type: { name: 'String' } }, identity: { client_side_validation: true, required: false, serialized_name: 'identity', type: { name: 'Composite', class_name: 'Identity' } } } } } end end end end
29.994924
77
0.467253
bb1006c6f047cb4c47d98509fc2dcdadca1458c7
3,476
# encoding: UTF-8 require 'forwardable' module MongoMapper module Plugins module Associations class Proxy extend Forwardable alias :proxy_respond_to? :respond_to? alias :proxy_extend :extend instance_methods.each { |m| undef_method m unless m =~ /(^__|^nil\?$|^send$|proxy_|^respond_to_missing\?$|^object_id$)/ } attr_reader :proxy_owner, :association, :target alias :proxy_target :target alias :proxy_association :association def_delegators :proxy_association, :klass, :options def_delegator :klass, :collection def initialize(owner, association) @proxy_owner, @association, @loaded = owner, association, false Array(association.options[:extend]).each { |ext| proxy_extend(ext) } reset end # Active support in rails 3 beta 4 can override to_json after this is loaded, # at least when run in mongomapper tests. The implementation was changed in master # some time after this, so not sure whether this is still a problem. # # In rails 2, this isn't a problem however it also solves an issue where # to_json isn't forwarded because it supports to_json itself def to_json(*options) load_target target.to_json(*options) end # see comments to to_json def as_json(*options) load_target target.as_json(*options) end def inspect load_target target.inspect end def loaded? @loaded end def loaded @loaded = true end def nil? load_target target.nil? end def blank? load_target target.blank? end def present? load_target target.present? end def reload reset load_target self unless target.nil? end # :nocov: def replace(v) raise NotImplementedError end # :nocov: def reset @loaded = false @target = nil end def respond_to?(*args) proxy_respond_to?(*args) || (load_target && target.respond_to?(*args)) end def send(method, *args, &block) if proxy_respond_to?(method, true) super else load_target target.send(method, *args, &block) end end protected def method_missing(method, *args, &block) if load_target target.send(method, *args, &block) end end def load_target unless loaded? if @target.is_a?(Array) && @target.any? @target = find_target + @target.find_all { |record| !record.persisted? } else @target = find_target end loaded end @target rescue MongoMapper::DocumentNotFound reset end # :nocov: def find_target raise NotImplementedError end # :nocov: def flatten_deeper(array) array.collect do |element| (element.respond_to?(:flatten) && !element.is_a?(Hash)) ? element.flatten : element end.flatten end end end end end
25.007194
129
0.539125
ed2b4cb72ae357d31f74fd96004c752a94a74650
508
class AddWatchdogTriggeredAtToDevices < ActiveRecord::Migration[6.0] def change add_column :devices, :last_watchdog, :datetime remove_column :devices, :needs_reset, :boolean # Not used remove_column :devices, :last_saw_mq, :datetime # 0 production use if Object.const_defined?("Device") # Prevent a wave of watchdog alerts after first # deployment. puts "===== Setting `last_watchdog` to default value:" Device.update_all(last_watchdog: Time.now) end end end
33.866667
70
0.712598
1d4af8398b63c8deef4d4fe61a8e7acff0197d56
761
module RedBlocks class Paginator DEFAULT_PER = 10 DEFAULT_PAGE = 1 attr_reader :head, :tail, :per, :page def initialize(per: DEFAULT_PER, page: DEFAULT_PAGE, head: nil, tail: nil) if head && tail unless head >= 0 && tail >= 0 && head <= tail raise ArgumentError.new("head and tail is out of range (head=#{head}, tail=#{tail})") end @head = head @tail = tail return end @per = per.to_i @page = page.to_i @head = @per * (@page - 1) @tail = @head + @per - 1 end def size @per || (@tail - @head + 1) end class All def head; 0 end def tail; -1 end end def self.all All.new end end end
19.025
95
0.51117
ab513cd123d0aee943e3d92f16a79ef173f8fb70
3,256
require 'spec_helper' feature Ticket do let!(:conference) { create(:conference, title: 'ExampleCon') } let!(:organizer_role) { Role.find_by(name: 'organizer', resource: conference) } let!(:organizer) { create(:user, email: '[email protected]', role_ids: [organizer_role.id]) } context 'as a organizer' do before(:each) do sign_in organizer end after(:each) do sign_out end scenario 'add a valid ticket', feature: true, js: true do visit admin_conference_tickets_path(conference.short_title) click_link 'Add Ticket' fill_in 'ticket_title', with: 'Business Ticket' fill_in 'ticket_description', with: 'The business ticket' fill_in 'ticket_price', with: '100' click_button 'Create Ticket' expect(flash).to eq('Ticket successfully created.') expect(Ticket.count).to eq(2) end scenario 'add a invalid ticket', feature: true, js: true do visit admin_conference_tickets_path(conference.short_title) click_link 'Add Ticket' fill_in 'ticket_title', with: '' fill_in 'ticket_price', with: '-1' click_button 'Create Ticket' expect(flash).to eq("Creating Ticket failed: Title can't be blank. Price cents must be greater than or equal to 0.") expect(Ticket.count).to eq(1) end context 'Ticket already created' do let!(:ticket) { create(:ticket, title: 'Business Ticket', price: 100, conference_id: conference.id) } scenario 'edit valid ticket', feature: true, js: true do visit admin_conference_tickets_path(conference.short_title) click_link('Edit', href: edit_admin_conference_ticket_path(conference.short_title, ticket.id)) fill_in 'ticket_title', with: 'Event Ticket' fill_in 'ticket_price', with: '50' click_button 'Update Ticket' ticket.reload # It's necessary to multiply by 100 because the price is in cents expect(ticket.price).to eq(Money.new(50 * 100, 'USD')) expect(ticket.title).to eq('Event Ticket') expect(flash).to eq('Ticket successfully updated.') expect(Ticket.count).to eq(2) end scenario 'edit invalid ticket', feature: true, js: true do visit admin_conference_tickets_path(conference.short_title) click_link('Edit', href: edit_admin_conference_ticket_path(conference.short_title, ticket.id)) fill_in 'ticket_title', with: '' fill_in 'ticket_price', with: '-5' click_button 'Update Ticket' ticket.reload # It's necessary to multiply by 100 because the price is in cents expect(ticket.price).to eq(Money.new(100 * 100, 'USD')) expect(ticket.title).to eq('Business Ticket') expect(flash).to eq("Ticket update failed: Title can't be blank. Price cents must be greater than or equal to 0.") expect(Ticket.count).to eq(2) end scenario 'delete ticket', feature: true, js: true do visit admin_conference_tickets_path(conference.short_title) click_link('Delete', href: admin_conference_ticket_path(conference.short_title, ticket.id)) expect(flash).to eq('Ticket successfully destroyed.') expect(Ticket.count).to eq(1) end end end end
36.58427
122
0.67414
28c28e2face4086a827c6d1419c74c59cea530a5
546
class Link < Post def initialize super @url = '' end def read_from_console puts 'Введите адрес ссылки' @url = $stdin.gets.chomp puts 'Напишите пару слов о том, куда ведёт ссылка' @text = $stdin.gets.chomp end def save file = File.open(file_path, 'w:utf-8') time_string = @created_at.strftime('%Y.%m.%d, %H:%M') file.puts time_string file.puts @url file.puts @text file.close puts 'Ваша ссылка сохранена' end end
19.5
61
0.554945
acdd0e81ef75c9013d7f8150988075efa385fe0e
216
# frozen_string_literal: true RSpec.describe Scrapework do it 'has a version number' do expect(Scrapework::VERSION).not_to be nil end it 'does something useful' do expect(false).to eq(true) end end
18
45
0.722222
abfe8cce7bd2880c0c1f35afbccdd783322ed5a8
2,820
class SpoofMac < Formula desc "Spoof your MAC address in macOS" homepage "https://github.com/feross/SpoofMAC" url "https://pypi.python.org/packages/9c/59/cc52a4c5d97b01fac7ff048353f8dc96f217eadc79022f78455e85144028/SpoofMAC-2.1.1.tar.gz" sha256 "48426efe033a148534e1d4dc224c4f1b1d22299c286df963c0b56ade4c7dc297" head "https://github.com/feross/SpoofMAC.git" bottle do cellar :any_skip_relocation sha256 "f7972b66a491d8513262e3bdb9098850fe91e4c8e0e3d7a12efd24994e47dda5" => :high_sierra sha256 "baa45eb53fc9e1a713ca7693351409f66c833834e7c7d0838115bcf5f38df555" => :sierra sha256 "6c97eaa9a82f7eadb5c1127a0dcf9b0f9f1837e36d3e9978e989471322f42b4a" => :el_capitan sha256 "927644491edf064dcc3145e05107737c3e571b55989ae8d539bf0b499da3685c" => :yosemite sha256 "f7dc1529dd2c83d8bf8667d170299aa592910bb4918174b23f6a9b7d3555084e" => :mavericks end depends_on "python" if MacOS.version <= :snow_leopard resource "docopt" do url "https://pypi.python.org/packages/source/d/docopt/docopt-0.6.2.tar.gz" sha256 "49b3a825280bd66b3aa83585ef59c4a8c82f2c8a522dbe754a8bc8d08c85c491" end def install ENV["PYTHONPATH"] = libexec/"lib/python2.7/site-packages" ENV.prepend_create_path "PYTHONPATH", libexec/"vendor/lib/python2.7/site-packages" resources.each do |r| r.stage { system "python", *Language::Python.setup_install_args(libexec/"vendor") } end system "python", *Language::Python.setup_install_args(libexec) bin.install Dir[libexec/"bin/*"] bin.env_script_all_files(libexec/"bin", :PYTHONPATH => ENV["PYTHONPATH"]) end def caveats; <<~EOS Although spoof-mac can run without root, you must be root to change the MAC. The launchdaemon is set to randomize en0. You can find the interfaces available by running: "spoof-mac list" If you wish to change interface randomized at startup change the plist line: <string>en0</string> to e.g.: <string>en1</string> EOS end plist_options :startup => true, :manual => "spoof-mac" def plist; <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/spoof-mac</string> <string>randomize</string> <string>en0</string> </array> <key>RunAtLoad</key> <true/> <key>StandardErrorPath</key> <string>/dev/null</string> <key>StandardOutPath</key> <string>/dev/null</string> </dict> </plist> EOS end test do system "#{bin}/spoof-mac", "list", "--wifi" end end
34.814815
129
0.697518
e916528e2c400efbb85e6512b9850863be1f7b66
646
# encoding: utf-8 module Backup module Storage class Git < SCMBase protected def init_repo(ssh) super ssh.exec! "#{cmd} config --global user.name 'backup'" ssh.exec! "#{cmd} config --global user.email 'backup@#{Config.hostname}'" ssh.exec! "#{cmd} init" end def commit(ssh) filenames.each do |dir| ssh.exec! "#{self.cmd} add #{dir}" end ssh.exec! "#{cmd} commit -m 'backup #{self.package.time}'" end def cmd "cd '#{remote_path}' && #{utility :git}" end def excludes ['.git'] end end end end
19
81
0.521672
3974f084b22a229d315f8f169d007de29482fb37
404
require 'multi_json' if !MultiJson.respond_to?(:load) || [ Kernel, defined?(ActiveSupport::Dependencies::Loadable) && ActiveSupport::Dependencies::Loadable ].compact.include?(MultiJson.method(:load).owner) module MultiJson class <<self alias :load :decode end end end if !MultiJson.respond_to?(:dump) module MultiJson class <<self alias :dump :encode end end end
20.2
90
0.693069
79128943d7a5a7dddd758d75e35a72ec29b45491
1,040
# frozen_string_literal: true require 'test_helper' class BlogsControllerTest < ActionDispatch::IntegrationTest setup do @blog = blogs(:one) end test 'should get index' do get blogs_url assert_response :success end test 'should get new' do get new_blog_url assert_response :success end test 'should create blog' do assert_difference('Blog.count') do post blogs_url, params: { blog: { body: @blog.body, title: @blog.title } } end assert_redirected_to blog_url(Blog.last) end test 'should show blog' do get blog_url(@blog) assert_response :success end test 'should get edit' do get edit_blog_url(@blog) assert_response :success end test 'should update blog' do patch blog_url(@blog), params: { blog: { body: @blog.body, title: @blog.title } } assert_redirected_to blog_url(@blog) end test 'should destroy blog' do assert_difference('Blog.count', -1) do delete blog_url(@blog) end assert_redirected_to blogs_url end end
20.392157
85
0.688462
2661e3e1e6c6d0be3defb3c273e82e6d30c4c04e
4,540
# # 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. # module Domgen module Appconfig class SystemSetting < Domgen.ParentedElement(:appconfig_repository) attr_reader :key def initialize(appconfig_repository, key, options = {}, &block) @key = key raise "Supplied key for system_setting has non alphanumeric and non underscore characters. key = '#{key}'" unless key.to_s.gsub(/[^0-9A-Za-z_]/, '') == key.to_s appconfig_repository.send(:register_system_setting, self) super(appconfig_repository, options, &block) end attr_writer :key_value # Key used to access flag in database def key_value @key_value.nil? ? self.key.to_s : @key_value end attr_writer :initial_value # Initial value set during database import if not already set def initial_value @initial_value end attr_writer :feature_flag def feature_flag? @feature_flag.nil? ? false : !!@feature_flag end attr_writer :disable_in_integration_test def disable_in_integration_test? feature_flag? && (@disable_in_integration_test.nil? ? false : !!@disable_in_integration_test) end end end FacetManager.facet(:appconfig) do |facet| facet.enhance(Repository) do include Domgen::Java::BaseJavaGenerator include Domgen::Java::JavaClientServerApplication java_artifact :feature_flag_container, nil, :shared, :appconfig, '#{repository.name}FeatureFlags' java_artifact :system_setting_container, nil, :shared, :appconfig, '#{repository.name}SystemSettings' java_artifact :integration_test, :rest, :integration, :appconfig, '#{repository.name}AppconfigTest' attr_writer :short_test_code def short_test_code @short_test_code || 'ac' end attr_writer :all_settings_defined def all_settings_defined? @all_settings_defined.nil? ? true : !!@all_settings_defined end def system_setting(key, options = {}, &block) Domgen::Appconfig::SystemSetting.new(self, key, options, &block) end def feature_flag(key, options = {}, &block) system_setting(key, {:initial_value => true}.merge(options.merge(:feature_flag => true)), &block) end def system_setting_by_name?(key) system_setting_map[key.to_s] end def system_setting_by_name(key) system_setting = system_setting_map[key.to_s] Domgen.error("Unable to locate feature flag #{key}") unless system_setting system_setting end def feature_flags? system_settings.any?{|s| s.feature_flag?} end def system_settings? system_setting_map.size > 0 end def system_settings system_setting_map.values end def pre_complete repository.jaxrs.extensions << 'iris.appconfig.server.rest.SystemSettingRestService' if repository.jaxrs? end def pre_verify if repository.jpa? repository.jpa.application_artifact_fragments << "iris.appconfig#{repository.pgsql? ? '.pg' : ''}:app-config-server" repository.jpa.add_test_factory(short_test_code, 'iris.appconfig.server.test.util.AppConfigFactory') repository.jpa.add_test_module('AppConfigPersistenceTestModule', 'iris.appconfig.server.test.util.AppConfigPersistenceTestModule') repository.jpa.add_test_module('AppConfigRepositoryModule', 'iris.appconfig.server.test.util.AppConfigRepositoryModule') repository.jpa.add_flushable_test_module('AppConfigServicesModule', 'iris.appconfig.server.test.util.AppConfigServicesModule') end end protected def register_system_setting(system_setting) Domgen.error("Attempting to redefine system setting '#{system_setting.key}'") if system_setting_map[system_setting.key.to_s] system_setting_map[system_setting.key.to_s] = system_setting end def system_setting_map @system_setting ||= {} end end end end
34.135338
168
0.699559
f8ac7a7bb2d4e56c6de051c13729907318155948
3,931
module Paysafe class Error < StandardError # Raised on a 4xx HTTP status code ClientError = Class.new(self) # Raised on the HTTP status code 400 BadRequest = Class.new(ClientError) # Raised on the HTTP status code 401 Unauthorized = Class.new(ClientError) # Raised on the HTTP status code 402 RequestDeclined = Class.new(ClientError) # Raised on the HTTP status code 403 Forbidden = Class.new(ClientError) # Raised on the HTTP status code 404 NotFound = Class.new(ClientError) # Raised on the HTTP status code 406 NotAcceptable = Class.new(ClientError) # Raised on the HTTP status code 409 Conflict = Class.new(ClientError) # Raised on the HTTP status code 415 UnsupportedMediaType = Class.new(ClientError) # Raised on the HTTP status code 422 UnprocessableEntity = Class.new(ClientError) # Raised on the HTTP status code 429 TooManyRequests = Class.new(ClientError) # Raised on a 5xx HTTP status code ServerError = Class.new(self) # Raised on the HTTP status code 500 InternalServerError = Class.new(ServerError) # Raised on the HTTP status code 502 BadGateway = Class.new(ServerError) # Raised on the HTTP status code 503 ServiceUnavailable = Class.new(ServerError) # Raised on the HTTP status code 504 GatewayTimeout = Class.new(ServerError) ERRORS_BY_STATUS = { 400 => Paysafe::Error::BadRequest, 401 => Paysafe::Error::Unauthorized, 402 => Paysafe::Error::RequestDeclined, 403 => Paysafe::Error::Forbidden, 404 => Paysafe::Error::NotFound, 406 => Paysafe::Error::NotAcceptable, 409 => Paysafe::Error::Conflict, 415 => Paysafe::Error::UnsupportedMediaType, 422 => Paysafe::Error::UnprocessableEntity, 429 => Paysafe::Error::TooManyRequests, 500 => Paysafe::Error::InternalServerError, 502 => Paysafe::Error::BadGateway, 503 => Paysafe::Error::ServiceUnavailable, 504 => Paysafe::Error::GatewayTimeout, } class << self # Create a new error from an HTTP response # # @param body [String] # @param status [Integer] # @return [Paysafe::Error] def from_response(body, status) klass = ERRORS_BY_STATUS[status] || Paysafe::Error message, error_code = parse_error(body) klass.new(message: message, code: error_code, response: body) end private def parse_error(body) if body.is_a?(Hash) [ body.dig(:error, :message), body.dig(:error, :code) ] else [ '', nil ] end end end # The Paysafe API Error Code # # @return [String] attr_reader :code # The JSON HTTP response in Hash form # # @return [Hash] attr_reader :response # Initializes a new Error object # # @param message [Exception, String] # @param code [String] # @param response [Hash] # @return [Paysafe::Error] def initialize(message: '', code: nil, response: {}) @code = code @response = response super(message) end def to_s [ super, code_text, field_error_text, detail_text ].compact.join(' ') end def id response.dig(:id) if response.is_a?(Hash) end def merchant_ref_num response.dig(:merchant_ref_num) if response.is_a?(Hash) end private def code_text "(Code #{code})" if code end def field_error_text if field_errors msgs = field_errors.map { |f| "The \`#{f[:field]}\` #{f[:error]}." }.join(' ') "Field Errors: #{msgs}".strip end end def field_errors response.dig(:error, :field_errors) if response.is_a?(Hash) end def detail_text "Details: #{details.join('. ')}".strip if details end def details response.dig(:error, :details) if response.is_a?(Hash) end end end
25.861842
86
0.632918
aca99feee5386e65f2389350869797e6813886cc
5,584
# Store object full path in separate table for easy lookup and uniq validation # Object must have name and path db fields and respond to parent and parent_changed? methods. module Routable extend ActiveSupport::Concern included do has_one :route, as: :source, autosave: true, dependent: :destroy validates_associated :route validates :route, presence: true scope :with_route, -> { includes(:route) } before_validation do if full_path_changed? || full_name_changed? prepare_route end end end class_methods do # Finds a single object by full path match in routes table. # # Usage: # # Klass.find_by_full_path('gitlab-org/gitlab-ce') # # Returns a single object, or nil. def find_by_full_path(path) # On MySQL we want to ensure the ORDER BY uses a case-sensitive match so # any literal matches come first, for this we have to use "BINARY". # Without this there's still no guarantee in what order MySQL will return # rows. binary = Gitlab::Database.mysql? ? 'BINARY' : '' order_sql = "(CASE WHEN #{binary} routes.path = #{connection.quote(path)} THEN 0 ELSE 1 END)" where_full_path_in([path]).reorder(order_sql).take end # Builds a relation to find multiple objects by their full paths. # # Usage: # # Klass.where_full_path_in(%w{gitlab-org/gitlab-ce gitlab-org/gitlab-ee}) # # Returns an ActiveRecord::Relation. def where_full_path_in(paths) wheres = [] cast_lower = Gitlab::Database.postgresql? paths.each do |path| path = connection.quote(path) where = if cast_lower "(LOWER(routes.path) = LOWER(#{path}))" else "(routes.path = #{path})" end wheres << where end if wheres.empty? none else joins(:route).where(wheres.join(' OR ')) end end # Builds a relation to find multiple objects that are nested under user membership # # Usage: # # Klass.member_descendants(1) # # Returns an ActiveRecord::Relation. def member_descendants(user_id) joins(:route). joins("INNER JOIN routes r2 ON routes.path LIKE CONCAT(r2.path, '/%') INNER JOIN members ON members.source_id = r2.source_id AND members.source_type = r2.source_type"). where('members.user_id = ?', user_id) end # Builds a relation to find multiple objects that are nested under user # membership. Includes the parent, as opposed to `#member_descendants` # which only includes the descendants. # # Usage: # # Klass.member_self_and_descendants(1) # # Returns an ActiveRecord::Relation. def member_self_and_descendants(user_id) joins(:route). joins("INNER JOIN routes r2 ON routes.path LIKE CONCAT(r2.path, '/%') OR routes.path = r2.path INNER JOIN members ON members.source_id = r2.source_id AND members.source_type = r2.source_type"). where('members.user_id = ?', user_id) end # Returns all objects in a hierarchy, where any node in the hierarchy is # under the user membership. # # Usage: # # Klass.member_hierarchy(1) # # Examples: # # Given the following group tree... # # _______group_1_______ # | | # | | # nested_group_1 nested_group_2 # | | # | | # nested_group_1_1 nested_group_2_1 # # # ... the following results are returned: # # * the user is a member of group 1 # => 'group_1', # 'nested_group_1', nested_group_1_1', # 'nested_group_2', 'nested_group_2_1' # # * the user is a member of nested_group_2 # => 'group1', # 'nested_group_2', 'nested_group_2_1' # # * the user is a member of nested_group_2_1 # => 'group1', # 'nested_group_2', 'nested_group_2_1' # # Returns an ActiveRecord::Relation. def member_hierarchy(user_id) paths = member_self_and_descendants(user_id).pluck('routes.path') return none if paths.empty? wheres = paths.map do |path| "#{connection.quote(path)} = routes.path OR #{connection.quote(path)} LIKE CONCAT(routes.path, '/%')" end joins(:route).where(wheres.join(' OR ')) end end def full_name if route && route.name.present? @full_name ||= route.name else update_route if persisted? build_full_name end end def full_path if route && route.path.present? @full_path ||= route.path else update_route if persisted? build_full_path end end private def full_name_changed? name_changed? || parent_changed? end def full_path_changed? path_changed? || parent_changed? end def build_full_name if parent && name parent.human_name + ' / ' + name else name end end def build_full_path if parent && path parent.full_path + '/' + path else path end end def update_route prepare_route route.save end def prepare_route route || build_route(source: self) route.path = build_full_path route.name = build_full_name @full_path = nil @full_name = nil end end
25.972093
99
0.595093
b9772b0c92cb3f624113913ce0095c337f2527fc
1,053
# Copyright 2015, Google, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Rails.application.routes.draw do resources :books # [START login] get "/login", to: redirect("/auth/google_oauth2") # [END login] # [START sessions] get "/auth/google_oauth2/callback", to: "sessions#create" resource :session, only: [:create, :destroy] # [END sessions] # [START user_books] resources :user_books, only: [:index] # [END user_books] # [START logout] get "/logout", to: "sessions#destroy" # [END logout] root "books#index" end
27
74
0.71415
edcf044b5885a3247d366b25c6a8bb6991513f97
2,152
class Kn < Formula desc "Command-line interface for managing Knative Serving and Eventing resources" homepage "https://github.com/knative/client" url "https://github.com/knative/client.git", tag: "knative-v1.5.0", revision: "0646532018621d3d08525edf6e47a125cf58438b" license "Apache-2.0" head "https://github.com/knative/client.git", branch: "main" bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "94d33b9b5f61f5da57dfdd7c4c2cd3fbf653b9f8fb47f1fd963c0f5b4f585542" sha256 cellar: :any_skip_relocation, arm64_big_sur: "94d33b9b5f61f5da57dfdd7c4c2cd3fbf653b9f8fb47f1fd963c0f5b4f585542" sha256 cellar: :any_skip_relocation, monterey: "210d84300356a5a75f193bea1bb9a4d3f5a4f23739ccb96a5a8e03f665474155" sha256 cellar: :any_skip_relocation, big_sur: "210d84300356a5a75f193bea1bb9a4d3f5a4f23739ccb96a5a8e03f665474155" sha256 cellar: :any_skip_relocation, catalina: "210d84300356a5a75f193bea1bb9a4d3f5a4f23739ccb96a5a8e03f665474155" sha256 cellar: :any_skip_relocation, x86_64_linux: "d11c464196707fdabf4a7cc3b4d161fd305cdc1f72559bbcd1a05ffbd8684bb7" end depends_on "go" => :build def install ENV["CGO_ENABLED"] = "0" ldflags = %W[ -X knative.dev/client/pkg/kn/commands/version.Version=v#{version} -X knative.dev/client/pkg/kn/commands/version.GitRevision=#{Utils.git_head(length: 8)} -X knative.dev/client/pkg/kn/commands/version.BuildDate=#{time.iso8601} ] system "go", "build", "-mod=vendor", *std_go_args(ldflags: ldflags), "./cmd/..." end test do system "#{bin}/kn", "service", "create", "foo", "--namespace", "bar", "--image", "gcr.io/cloudrun/hello", "--target", "." yaml = File.read(testpath/"bar/ksvc/foo.yaml") assert_match("name: foo", yaml) assert_match("namespace: bar", yaml) assert_match("image: gcr.io/cloudrun/hello", yaml) version_output = shell_output("#{bin}/kn version") assert_match("Version: v#{version}", version_output) assert_match("Build Date: ", version_output) assert_match(/Git Revision: [a-f0-9]{8}/, version_output) end end
43.04
123
0.722584
ac71ab6a19a7920cddb0c3174a3412b7ad452a66
447
# frozen_string_literal: true require 'spec_helper' RSpec.describe Faithlife::Endpoints::Funds do describe '#funds', :vcr do before do @client = FactoryBot.build(:client) @funds = @client.funds[:objects] end it 'returns an array' do expect(@funds).to be_an(Array) end it 'returns funds objects' do expect(@funds.first).to be_a(Hash) expect(@funds.first[:id]).to_not be_nil end end end
20.318182
45
0.653244
ac4ecb1e65454fbddd270143da7ae32070c57f8e
2,735
module ActionDispatch module Journey # :nodoc: class Router # :nodoc: class Utils # :nodoc: # Normalizes URI path. # # Strips off trailing slash and ensures there is a leading slash. # Also converts downcase url encoded string to uppercase. # # normalize_path("/foo") # => "/foo" # normalize_path("/foo/") # => "/foo" # normalize_path("foo") # => "/foo" # normalize_path("") # => "/" # normalize_path("/%ab") # => "/%AB" def self.normalize_path(path) path = "/#{path}" path.squeeze!('/') path.sub!(%r{/+\Z}, '') path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase } path = '/' if path == '' path end # URI path and fragment escaping # http://tools.ietf.org/html/rfc3986 class UriEncoder # :nodoc: ENCODE = "%%%02X".freeze ENCODING = Encoding::US_ASCII EMPTY = "".force_encoding(ENCODING).freeze DEC2HEX = (0..255).to_a.map{ |i| ENCODE % i }.map{ |s| s.force_encoding(ENCODING) } ALPHA = "a-zA-Z".freeze DIGIT = "0-9".freeze UNRESERVED = "#{ALPHA}#{DIGIT}\\-\\._~".freeze SUB_DELIMS = "!\\$&'\\(\\)\\*\\+,;=".freeze ESCAPED = /%[a-zA-Z0-9]{2}/.freeze FRAGMENT = /[^#{UNRESERVED}#{SUB_DELIMS}:@\/\?]/.freeze SEGMENT = /[^#{UNRESERVED}#{SUB_DELIMS}:@]/.freeze PATH = /[^#{UNRESERVED}#{SUB_DELIMS}:@\/]/.freeze def escape_fragment(fragment) escape(fragment, FRAGMENT) end def escape_path(path) escape(path, PATH) end def escape_segment(segment) escape(segment, SEGMENT) end def unescape_uri(uri) uri.gsub(ESCAPED) { [$&[1, 2].hex].pack('C') }.force_encoding(uri.encoding) end protected def escape(component, pattern) component.gsub(pattern){ |unsafe| percent_encode(unsafe) }.force_encoding(ENCODING) end def percent_encode(unsafe) safe = EMPTY.dup unsafe.each_byte { |b| safe << DEC2HEX[b] } safe end end ENCODER = UriEncoder.new def self.escape_path(path) ENCODER.escape_path(path.to_s) end def self.escape_segment(segment) ENCODER.escape_segment(segment.to_s) end def self.escape_fragment(fragment) ENCODER.escape_fragment(fragment.to_s) end def self.unescape_uri(uri) ENCODER.unescape_uri(uri) end end end end end
29.728261
97
0.509689
791c311ef72c0a3cc26f22e738a2b7634f5b7419
2,218
# METER An implementation of meter classifier. # # Version: helpers/meter.rb 0.0.1 04/10/14 # Authors: Maciej A. Czyzewski, <[email protected]> class Netflam module Meter # Story points & user karma @votes = :votes @users = :users # Dynamic stream @score = :score class << self def save(story_id) story = Story.find(story_id) user_id = story.user_id created_at = story.created_at score = Netflam::Meter.score(story_id) karma = Netflam::Meter.karma(user_id) $redis.zadd(@votes.to_s, score + 1, story_id) $redis.zadd(@users.to_s, karma + 1, user_id) $redis.zadd(@score.to_s, created_at.to_i / (12 * 60 * 60) + Math.log10(score + 1), story_id) end def destroy(story_id) user_id = Story.find(story_id).user_id score = Netflam::Meter.score(story_id) karma = Netflam::Meter.karma(user_id) if score > 1 $redis.zadd(@votes.to_s, score - 1, story_id) else $redis.zrem(@votes.to_s, story_id) end $redis.zadd(@users.to_s, karma - 1, user_id) end def score(story_id) $redis.zscore(@votes.to_s, story_id).to_i end def karma(user_id) $redis.zscore(@users.to_s, user_id).to_i end def top(a, b) $redis.zrevrange(@score.to_s, a, b) end def type(story_id) inta = $redis.zcard(@votes.to_s) rank = $redis.zrank(@votes.to_s, story_id) bttm = inta / 6 # Types: a b c d e f if rank != nil and inta != nil if rank.between?(0, bttm * 0.1) return "f" elsif rank.between?(bttm * 0.1, bttm * 0.3) return "e" elsif rank.between?(bttm * 0.3, bttm * 0.5) return "d" elsif rank.between?(bttm * 0.5, bttm * 1) return "c" elsif rank.between?(bttm * 1, bttm * 3) return "b" elsif rank.between?(bttm * 3, inta) return "a" end else return "a" end end end end end
26.404762
100
0.52615
1c65613d6bd5a04d3cd8dcff4ac07f353bc9fac9
3,968
require "rspec/autorun" # make a Ruby version of Python's "deque" class Deque attr_reader :items def initialize @items = [] end def add(items) items.each { |item| @items.push(item) } end def get_next_in_queue @items.shift end def is_not_empty @items.length > 0 end end class Person attr_reader :name, :tools attr_accessor :friends def initialize(args) @name = args.fetch('name', 'Anon') @tools = args.fetch('tools', []) # comment next line back in to use .friends instead of relational graph # @friends = [] end end # establish people and what tools they own people = [{ 'name' => 'You', 'tools' => ['ax', 'lawn mower'], }, { 'name' => 'Alice', 'tools' => ['wheelbarrow', 'drill'] }, { 'name' => 'Bob', 'tools' => ['pitch fork', 'shovel'] }, { 'name' => 'Claire', 'tools' => ['pressure washer'] }, { 'name' => 'Anuj', 'tools' => ['screwdriver', 'rake', '🔨'] }, { 'name' => 'Peggy', 'tools' => ['leaf blower', 'chainsaw', 'pruning shears'] }, { 'name' => 'Thom', 'tools' => ['hoe', 'spade', 'gloves'] }, { 'name' => 'Jonny', 'tools' => ['blower'] }] # to determine if a person owns a specific tool def friend_has_tool(friend, desired_tool) friend.tools.include?(desired_tool) end # implementation of BFS algorithm def breadth_first_search(person_looking_for_tool, desired_tool) # init a search queue variable search_queue = Deque.new() # add initial person's friends to that queue search_queue.add(@graph[person_looking_for_tool]) # comment next line back in to use .friends instead of relational graph # search_queue.add(person_looking_for_tool.friends) # init variable to keep track of searched persons searched = [] # while queue has people while search_queue.is_not_empty # get friend and remove them from queue friend = search_queue.get_next_in_queue # check whether friend has tool if friend && friend_has_tool(friend, desired_tool) # if friend has tool # notify user that friend has tool, and we're done! return "#{friend.name} has a #{desired_tool}!" # else if friend doesn't have tool... else # add friend to searched list searched << friend # add friend's friends to queue search_queue.add(@graph[friend]) # comment next line back in to use .friends instead of relational graph # search_queue.add(friend.friends) end end # notify user they are SOL return "Looks like no one you know has access to a #{desired_tool}... :(" end # tests describe 'breadth_first_search' do # test setup before do people.each do |person| instance_variable_set('@' + person['name'].downcase, Person.new(args=person)) end # set up a relational graph @graph = {} @graph[@you] = [@alice, @bob, @claire] @graph[@bob] = [@peggy, @anuj] @graph[@alice] = [@peggy] @graph[@claire] = [@thom, @jonny] @graph[@anuj] = [] @graph[@peggy] = [] @graph[@thom] = [] @graph[@jonny] = [] # comment next lines back in to use .friends instead of relational graph # @you.friends = [@alice, @bob, @claire] # @bob.friends = [@peggy, @anuj] # @alice.friends = [@peggy] # @claire.friends = [@thom, @jonny] # @anuj.friends = [] # @peggy.friends = [] # @thom.friends = [] # @jonny.friends = [] end it "verifies that a friend of a friend has a hammer" do result = breadth_first_search(@you, '🔨') expect(result).to eq('Anuj has a 🔨!') end # TODO: add more test cases end
27.555556
89
0.564264
bf92c360f76b5ec207a83e6110f29bef24eb2662
1,308
require "spec_helper" describe HLJS do it "delegates #highlight to adapter" do expect(described_class.adapter).to receive(:highlight).with("foo", "bar") described_class.highlight "foo", "bar" end it "delegates #supported_syntaxes to adapter" do expect(described_class.adapter).to receive(:supported_syntaxes).once described_class.supported_syntaxes end describe "#adapter=" do args = ["highlightjs", "highlight_js", "highlight js", "HIGHLIGHTJS", :highlightjs, :highlight_js] args.each do |arg| it "should enable HighlightJS with #{arg.inspect}" do described_class.adapter = arg expect(described_class.adapter).to be_instance_of(described_class::Adapters::HighlightJS) end end args = ["SyntaxHighlighter", "Syntax Highlighter", "syntax_highlighter", :syntax_highlighter, :syntaxhighlighter, :SyntaxHighlighter] args.each do |arg| it "should enable SyntaxHighlighter with #{arg.inspect}" do described_class.adapter = arg expect(described_class.adapter).to be_instance_of(described_class::Adapters::SyntaxHighlighter) end end it "raises an ArgumentError on invalid input" do expect{HLJS.adapter=:foo}.to raise_error(ArgumentError, "invalid adapter :foo") end end end
32.7
103
0.713303
aca88ff9f865cf6f2215db12761c609b20f4b7fe
57
module Rack class Cors VERSION = "1.0.1" end end
9.5
21
0.614035
3890b566b50034dfc2f2c17b30fcfc9f184cc792
5,990
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Rails::ContentTag, :config do context 'Rails 5.0', :rails50 do it 'does not register an offense' do expect_no_offenses(<<~RUBY) content_tag(:p, 'Hello world!') RUBY end it 'does not register an offense with empty tag' do expect_no_offenses(<<~RUBY) content_tag(:br) RUBY end it 'does not register an offense with array of classnames' do expect_no_offenses(<<~RUBY) content_tag(:div, "Hello world!", class: ["strong", "highlight"]) RUBY end it 'does not register an offense with nested content_tag' do expect_no_offenses(<<~RUBY) content_tag(:div) { content_tag(:strong, 'Hi') } content_tag(:div, content_tag(:span, 'foo')) RUBY end end context 'Rails 5.1', :rails51 do it 'corrects an offense' do expect_offense(<<~RUBY) content_tag(:p, 'Hello world!') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `tag` instead of `content_tag`. RUBY expect_correction(<<~RUBY) tag.p('Hello world!') RUBY end it 'corrects an offense with empty tag' do expect_offense(<<~RUBY) content_tag(:br) ^^^^^^^^^^^^^^^^ Use `tag` instead of `content_tag`. RUBY expect_correction(<<~RUBY) tag.br() RUBY end it 'corrects an offense with array of classnames' do expect_offense(<<~RUBY) content_tag(:div, "Hello world!", class: ["strong", "highlight"]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `tag` instead of `content_tag`. RUBY expect_correction(<<~RUBY) tag.div("Hello world!", class: ["strong", "highlight"]) RUBY end it 'corrects an offense with nested content_tag' do expect_offense(<<~RUBY) content_tag(:div, content_tag(:span, 'foo')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `tag` instead of `content_tag`. RUBY expect_correction(<<~RUBY) tag.div(tag.span('foo')) RUBY end it 'corrects an offense with nested content_tag with block' do expect_offense(<<~RUBY) content_tag(:div) { content_tag(:strong, 'Hi') } ^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `tag` instead of `content_tag`. ^^^^^^^^^^^^^^^^^ Use `tag` instead of `content_tag`. RUBY expect_correction(<<~RUBY) tag.div() { tag.strong('Hi') } RUBY end it 'corrects an offense when first argument is hash' do expect_offense(<<~RUBY) content_tag({foo: 1}) ^^^^^^^^^^^^^^^^^^^^^ Use `tag` instead of `content_tag`. RUBY expect_correction(<<~RUBY) tag({foo: 1}) RUBY end it 'corrects an offense when first argument is non-identifier string' do expect_offense(<<~RUBY) content_tag('foo-bar', 'baz', class: 'strong') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `tag` instead of `content_tag`. RUBY expect_correction(<<~RUBY) tag.foo_bar('baz', class: 'strong') RUBY end it 'corrects an offense when called with options hash and block' do expect_offense(<<~RUBY) content_tag :div, { class: 'strong' } do ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `tag` instead of `content_tag`. 'body' end RUBY expect_correction(<<~RUBY) tag.div({ class: 'strong' }) do 'body' end RUBY end it 'does not register an offense when `tag` is used with an argument' do expect_no_offenses(<<~RUBY) tag.p('Hello world!') RUBY end it 'does not register an offense when `tag` is used without arguments' do expect_no_offenses(<<~RUBY) tag.br RUBY end it 'does not register an offense when `tag` is used with arguments' do expect_no_offenses(<<~RUBY) tag.div("Hello world!", class: ["strong", "highlight"]) RUBY end it 'does not register an offense when `tag` is nested' do expect_no_offenses(<<~RUBY) tag.div() { tag.strong('Hi') } RUBY end it 'does not register an offense when `content_tag` is called with no arguments' do expect_no_offenses(<<~RUBY) content_tag RUBY end context 'when the first argument is a variable' do it 'does not register an offense when the first argument is a lvar' do expect_no_offenses(<<~RUBY) name = do_something content_tag(name, "Hello world!", class: ["strong", "highlight"]) RUBY end it 'does not register an offense when the first argument is an ivar' do expect_no_offenses(<<~RUBY) content_tag(@name, "Hello world!", class: ["strong", "highlight"]) RUBY end it 'does not register an offense when the first argument is a cvar' do expect_no_offenses(<<~RUBY) content_tag(@@name, "Hello world!", class: ["strong", "highlight"]) RUBY end it 'does not register an offense when the first argument is a gvar' do expect_no_offenses(<<~RUBY) content_tag($name, "Hello world!", class: ["strong", "highlight"]) RUBY end it 'does not register an offense when the first argument is a splat argument' do expect_no_offenses(<<~RUBY) content_tag(*args, &block) RUBY end end context 'when the first argument is a method' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) content_tag(name, "Hello world!", class: ["strong", "highlight"]) RUBY end end context 'when the first argument is a constant' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) content_tag(CONST, "Hello world!", class: ["strong", "highlight"]) RUBY end end end end
29.07767
109
0.564608
b969af4ddb15989e71601cd39fe5b4d0ddb7fa6b
2,514
# encoding: utf-8 require 'spec_helper' RSpec.describe 'string input' do include FormtasticSpecHelper before do @output_buffer = '' mock_everything end after do ::I18n.backend.reload! end describe "placeholder text" do [:email, :number, :password, :phone, :search, :string, :url, :text, :date_picker, :time_picker, :datetime_picker].each do |type| describe "for #{type} inputs" do describe "when found in i18n" do it "should have a placeholder containing i18n text" do with_config :i18n_lookups_by_default, true do ::I18n.backend.store_translations :en, :formtastic => { :placeholders => { :title => 'War and Peace' }} concat(semantic_form_for(@new_post) do |builder| concat(builder.input(:title, :as => type)) end) expect(output_buffer).to have_tag((type == :text ? 'textarea' : 'input') + '[@placeholder="War and Peace"]') end end end describe "when not found in i18n" do it "should not have placeholder" do concat(semantic_form_for(@new_post) do |builder| concat(builder.input(:title, :as => type)) end) expect(output_buffer).not_to have_tag((type == :text ? 'textarea' : 'input') + '[@placeholder]') end end describe "when found in i18n and :input_html" do it "should favor :input_html" do with_config :i18n_lookups_by_default, true do ::I18n.backend.store_translations :en, :formtastic => { :placeholders => { :title => 'War and Peace' }} concat(semantic_form_for(@new_post) do |builder| concat(builder.input(:title, :as => type, :input_html => { :placeholder => "Foo" })) end) expect(output_buffer).to have_tag((type == :text ? 'textarea' : 'input') + '[@placeholder="Foo"]') end end end describe "when found in :input_html" do it "should use the :input_html placeholder" do concat(semantic_form_for(@new_post) do |builder| concat(builder.input(:title, :as => type, :input_html => { :placeholder => "Untitled" })) end) expect(output_buffer).to have_tag((type == :text ? 'textarea' : 'input') + '[@placeholder="Untitled"]') end end end end end end
34.916667
132
0.56245
e9f94fa13aa65706c3a93a72d2d06f9fb0c380a8
79,213
# frozen_string_literal: true # Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. # # 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. module TencentCloud module Faceid module V20180301 # BankCard2EVerification请求参数结构体 class BankCard2EVerificationRequest < TencentCloud::Common::AbstractModel # @param Name: 姓名 # @type Name: String # @param BankCard: 银行卡 # @type BankCard: String attr_accessor :Name, :BankCard def initialize(name=nil, bankcard=nil) @Name = name @BankCard = bankcard end def deserialize(params) @Name = params['Name'] @BankCard = params['BankCard'] end end # BankCard2EVerification返回参数结构体 class BankCard2EVerificationResponse < TencentCloud::Common::AbstractModel # @param Result: 认证结果码 # 计费结果码: # '0': '认证通过' # '-1': '认证未通过' # '-4': '持卡人信息有误' # '-5': '未开通无卡支付' # '-6': '此卡被没收' # '-7': '无效卡号' # '-8': '此卡无对应发卡行' # '-9': '该卡未初始化或睡眠卡' # '-10': '作弊卡、吞卡' # '-11': '此卡已挂失' # '-12': '该卡已过期' # '-13': '受限制的卡' # '-14': '密码错误次数超限' # '-15': '发卡行不支持此交易' # 不计费结果码: # '-2': '姓名校验不通过' # '-3': '银行卡号码有误' # '-16': '验证中心服务繁忙' # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Result, :Description, :RequestId def initialize(result=nil, description=nil, requestid=nil) @Result = result @Description = description @RequestId = requestid end def deserialize(params) @Result = params['Result'] @Description = params['Description'] @RequestId = params['RequestId'] end end # BankCard4EVerification请求参数结构体 class BankCard4EVerificationRequest < TencentCloud::Common::AbstractModel # @param Name: 姓名 # @type Name: String # @param BankCard: 银行卡 # @type BankCard: String # @param Phone: 手机号码 # @type Phone: String # @param IdCard: 开户证件号,与CertType参数的证件类型一致,如:身份证,则传入身份证号。 # @type IdCard: String # @param CertType: 证件类型,请确认该证件为开户时使用的证件类型,未用于开户的证件信息不支持验证。 # 目前默认为0:身份证,其他证件类型暂不支持。 # @type CertType: Integer # @param Encryption: 敏感数据加密信息。对传入信息(姓名、身份证号、手机号、银行卡号)有加密需求的用户可使用此参数,详情请点击左侧链接。 # @type Encryption: :class:`Tencentcloud::Faceid.v20180301.models.Encryption` attr_accessor :Name, :BankCard, :Phone, :IdCard, :CertType, :Encryption def initialize(name=nil, bankcard=nil, phone=nil, idcard=nil, certtype=nil, encryption=nil) @Name = name @BankCard = bankcard @Phone = phone @IdCard = idcard @CertType = certtype @Encryption = encryption end def deserialize(params) @Name = params['Name'] @BankCard = params['BankCard'] @Phone = params['Phone'] @IdCard = params['IdCard'] @CertType = params['CertType'] unless params['Encryption'].nil? @Encryption = Encryption.new.deserialize(params['Encryption']) end end end # BankCard4EVerification返回参数结构体 class BankCard4EVerificationResponse < TencentCloud::Common::AbstractModel # @param Result: 认证结果码 # 收费结果码: # '0': '认证通过' # '-1': '认证未通过' # '-6': '持卡人信息有误' # '-7': '未开通无卡支付' # '-8': '此卡被没收' # '-9': '无效卡号' # '-10': '此卡无对应发卡行' # '-11': '该卡未初始化或睡眠卡' # '-12': '作弊卡、吞卡' # '-13': '此卡已挂失' # '-14': '该卡已过期' # '-15': '受限制的卡' # '-16': '密码错误次数超限' # '-17': '发卡行不支持此交易' # 不收费结果码: # '-2': '姓名校验不通过' # '-3': '身份证号码有误' # '-4': '银行卡号码有误' # '-5': '手机号码不合法' # '-18': '验证中心服务繁忙' # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Result, :Description, :RequestId def initialize(result=nil, description=nil, requestid=nil) @Result = result @Description = description @RequestId = requestid end def deserialize(params) @Result = params['Result'] @Description = params['Description'] @RequestId = params['RequestId'] end end # BankCardVerification请求参数结构体 class BankCardVerificationRequest < TencentCloud::Common::AbstractModel # @param IdCard: 开户证件号,与CertType参数的证件类型一致,如:身份证,则传入身份证号。 # @type IdCard: String # @param Name: 姓名 # @type Name: String # @param BankCard: 银行卡 # @type BankCard: String # @param CertType: 证件类型,请确认该证件为开户时使用的证件类型,未用于开户的证件信息不支持验证。 # 目前默认:0 身份证,其他证件类型需求可以联系小助手faceid001确认。 # @type CertType: Integer # @param Encryption: 敏感数据加密信息。对传入信息(姓名、身份证号、银行卡号)有加密需求的用户可使用此参数,详情请点击左侧链接。 # @type Encryption: :class:`Tencentcloud::Faceid.v20180301.models.Encryption` attr_accessor :IdCard, :Name, :BankCard, :CertType, :Encryption def initialize(idcard=nil, name=nil, bankcard=nil, certtype=nil, encryption=nil) @IdCard = idcard @Name = name @BankCard = bankcard @CertType = certtype @Encryption = encryption end def deserialize(params) @IdCard = params['IdCard'] @Name = params['Name'] @BankCard = params['BankCard'] @CertType = params['CertType'] unless params['Encryption'].nil? @Encryption = Encryption.new.deserialize(params['Encryption']) end end end # BankCardVerification返回参数结构体 class BankCardVerificationResponse < TencentCloud::Common::AbstractModel # @param Result: 认证结果码 # 收费结果码: # '0': '认证通过' # '-1': '认证未通过' # '-5': '持卡人信息有误' # '-6': '未开通无卡支付' # '-7': '此卡被没收' # '-8': '无效卡号' # '-9': '此卡无对应发卡行' # '-10': '该卡未初始化或睡眠卡' # '-11': '作弊卡、吞卡' # '-12': '此卡已挂失' # '-13': '该卡已过期' # '-14': '受限制的卡' # '-15': '密码错误次数超限' # '-16': '发卡行不支持此交易' # 不收费结果码: # '-2': '姓名校验不通过' # '-3': '身份证号码有误' # '-4': '银行卡号码有误' # '-17': '验证中心服务繁忙' # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Result, :Description, :RequestId def initialize(result=nil, description=nil, requestid=nil) @Result = result @Description = description @RequestId = requestid end def deserialize(params) @Result = params['Result'] @Description = params['Description'] @RequestId = params['RequestId'] end end # CheckBankCardInformation请求参数结构体 class CheckBankCardInformationRequest < TencentCloud::Common::AbstractModel # @param BankCard: 银行卡号。 # @type BankCard: String attr_accessor :BankCard def initialize(bankcard=nil) @BankCard = bankcard end def deserialize(params) @BankCard = params['BankCard'] end end # CheckBankCardInformation返回参数结构体 class CheckBankCardInformationResponse < TencentCloud::Common::AbstractModel # @param Result: 认证结果码,收费情况如下。 # 收费结果码: # 0: 查询成功 # -1: 未查到信息 # 不收费结果码 # -2:验证中心服务繁忙 # -3:银行卡不存在 # @type Result: String # @param Description: 业务结果描述 # @type Description: String # @param AccountBank: 开户行 # @type AccountBank: String # @param AccountType: 卡性质:1. 借记卡;2. 贷记卡 # @type AccountType: Integer # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Result, :Description, :AccountBank, :AccountType, :RequestId def initialize(result=nil, description=nil, accountbank=nil, accounttype=nil, requestid=nil) @Result = result @Description = description @AccountBank = accountbank @AccountType = accounttype @RequestId = requestid end def deserialize(params) @Result = params['Result'] @Description = params['Description'] @AccountBank = params['AccountBank'] @AccountType = params['AccountType'] @RequestId = params['RequestId'] end end # CheckIdCardInformation请求参数结构体 class CheckIdCardInformationRequest < TencentCloud::Common::AbstractModel # @param ImageBase64: 身份证人像面的 Base64 值 # 支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。 # 支持的图片大小:所下载图片经Base64编码后不超过 7M。 # 请使用标准的Base64编码方式(带=补位),编码规范参考RFC4648。 # ImageBase64、ImageUrl二者必须提供其中之一。若都提供了,则按照ImageUrl>ImageBase64的优先级使用参数。 # @type ImageBase64: String # @param ImageUrl: 身份证人像面的 Url 地址 # 支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。 # 支持的图片大小:所下载图片经 Base64 编码后不超过 3M。图片下载时间不超过 3 秒。 # 图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。 # 非腾讯云存储的 Url 速度和稳定性可能受一定影响。 # @type ImageUrl: String # @param Config: 以下可选字段均为bool 类型,默认false: # CopyWarn,复印件告警 # BorderCheckWarn,边框和框内遮挡告警 # ReshootWarn,翻拍告警 # DetectPsWarn,PS检测告警 # TempIdWarn,临时身份证告警 # Quality,图片质量告警(评价图片模糊程度) # SDK 设置方式参考: # Config = Json.stringify({"CopyWarn":true,"ReshootWarn":true}) # API 3.0 Explorer 设置方式参考: # Config = {"CopyWarn":true,"ReshootWarn":true} # @type Config: String attr_accessor :ImageBase64, :ImageUrl, :Config def initialize(imagebase64=nil, imageurl=nil, config=nil) @ImageBase64 = imagebase64 @ImageUrl = imageurl @Config = config end def deserialize(params) @ImageBase64 = params['ImageBase64'] @ImageUrl = params['ImageUrl'] @Config = params['Config'] end end # CheckIdCardInformation返回参数结构体 class CheckIdCardInformationResponse < TencentCloud::Common::AbstractModel # @param Sim: 相似度,取值范围 [0.00, 100.00]。推荐相似度大于等于70时可判断为同一人,可根据具体场景自行调整阈值(阈值70的误通过率为千分之一,阈值80的误通过率是万分之一) # @type Sim: Float # @param Result: 业务错误码,成功情况返回Success, 错误情况请参考下方错误码 列表中FailedOperation部分 # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param Name: 姓名 # @type Name: String # @param Sex: 性别 # @type Sex: String # @param Nation: 民族 # @type Nation: String # @param Birth: 出生日期 # @type Birth: String # @param Address: 地址 # @type Address: String # @param IdNum: 身份证号 # @type IdNum: String # @param Portrait: 身份证头像照片的base64编码,如果抠图失败会拿整张身份证做比对并返回空。 # @type Portrait: String # @param Warnings: 告警信息,当在Config中配置了告警信息会停止人像比对,Result返回错误(FailedOperation.OcrWarningOccurred)并有此告警信息,Code 告警码列表和释义: # -9101 身份证边框不完整告警, # -9102 身份证复印件告警, # -9103 身份证翻拍告警, # -9105 身份证框内遮挡告警, # -9104 临时身份证告警, # -9106 身份证 PS 告警。 # -8001 图片模糊告警 # 多个会 | 隔开如 "-9101|-9106|-9104" # @type Warnings: String # @param Quality: 图片质量分数,当请求Config中配置图片模糊告警该参数才有意义,取值范围(0~100),目前默认阈值是50分,低于50分会触发模糊告警。 # @type Quality: Float # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Sim, :Result, :Description, :Name, :Sex, :Nation, :Birth, :Address, :IdNum, :Portrait, :Warnings, :Quality, :RequestId def initialize(sim=nil, result=nil, description=nil, name=nil, sex=nil, nation=nil, birth=nil, address=nil, idnum=nil, portrait=nil, warnings=nil, quality=nil, requestid=nil) @Sim = sim @Result = result @Description = description @Name = name @Sex = sex @Nation = nation @Birth = birth @Address = address @IdNum = idnum @Portrait = portrait @Warnings = warnings @Quality = quality @RequestId = requestid end def deserialize(params) @Sim = params['Sim'] @Result = params['Result'] @Description = params['Description'] @Name = params['Name'] @Sex = params['Sex'] @Nation = params['Nation'] @Birth = params['Birth'] @Address = params['Address'] @IdNum = params['IdNum'] @Portrait = params['Portrait'] @Warnings = params['Warnings'] @Quality = params['Quality'] @RequestId = params['RequestId'] end end # CheckPhoneAndName请求参数结构体 class CheckPhoneAndNameRequest < TencentCloud::Common::AbstractModel # @param Mobile: ⼿机号 # @type Mobile: String # @param Name: 姓名 # @type Name: String attr_accessor :Mobile, :Name def initialize(mobile=nil, name=nil) @Mobile = mobile @Name = name end def deserialize(params) @Mobile = params['Mobile'] @Name = params['Name'] end end # CheckPhoneAndName返回参数结构体 class CheckPhoneAndNameResponse < TencentCloud::Common::AbstractModel # @param Result: 认证结果码,收费情况如下。 # 收费结果码: # 0: 验证结果一致 # 1: 验证结果不一致 # 不收费结果码: # -1:查无记录 # -2:引擎未知错误 # -3:引擎服务异常 # @type Result: String # @param Description: 业务结果描述 # @type Description: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Result, :Description, :RequestId def initialize(result=nil, description=nil, requestid=nil) @Result = result @Description = description @RequestId = requestid end def deserialize(params) @Result = params['Result'] @Description = params['Description'] @RequestId = params['RequestId'] end end # DetectAuth请求参数结构体 class DetectAuthRequest < TencentCloud::Common::AbstractModel # @param RuleId: 用于细分客户使用场景,申请开通服务后,可以在腾讯云慧眼人脸核身控制台(https://console.cloud.tencent.com/faceid) 自助接入里面创建,审核通过后即可调用。如有疑问,请加慧眼小助手微信(faceid001)进行咨询。 # @type RuleId: String # @param TerminalType: 本接口不需要传递此参数。 # @type TerminalType: String # @param IdCard: 身份标识(未使用OCR服务时,必须传入)。 # 规则:a-zA-Z0-9组合。最长长度32位。 # @type IdCard: String # @param Name: 姓名。(未使用OCR服务时,必须传入)最长长度32位。中文请使用UTF-8编码。 # @type Name: String # @param RedirectUrl: 认证结束后重定向的回调链接地址。最长长度1024位。 # @type RedirectUrl: String # @param Extra: 透传字段,在获取验证结果时返回。 # @type Extra: String # @param ImageBase64: 用于人脸比对的照片,图片的Base64值; # Base64编码后的图片数据大小不超过3M,仅支持jpg、png格式。请使用标准的Base64编码方式(带=补位),编码规范参考RFC4648。 # @type ImageBase64: String # @param Encryption: 敏感数据加密信息。对传入信息(姓名、身份证号)有加密需求的用户可使用此参数,详情请点击左侧链接。 # @type Encryption: :class:`Tencentcloud::Faceid.v20180301.models.Encryption` attr_accessor :RuleId, :TerminalType, :IdCard, :Name, :RedirectUrl, :Extra, :ImageBase64, :Encryption def initialize(ruleid=nil, terminaltype=nil, idcard=nil, name=nil, redirecturl=nil, extra=nil, imagebase64=nil, encryption=nil) @RuleId = ruleid @TerminalType = terminaltype @IdCard = idcard @Name = name @RedirectUrl = redirecturl @Extra = extra @ImageBase64 = imagebase64 @Encryption = encryption end def deserialize(params) @RuleId = params['RuleId'] @TerminalType = params['TerminalType'] @IdCard = params['IdCard'] @Name = params['Name'] @RedirectUrl = params['RedirectUrl'] @Extra = params['Extra'] @ImageBase64 = params['ImageBase64'] unless params['Encryption'].nil? @Encryption = Encryption.new.deserialize(params['Encryption']) end end end # DetectAuth返回参数结构体 class DetectAuthResponse < TencentCloud::Common::AbstractModel # @param Url: 用于发起核身流程的URL,仅微信H5场景使用。 # @type Url: String # @param BizToken: 一次核身流程的标识,有效时间为7,200秒; # 完成核身后,可用该标识获取验证结果信息。 # @type BizToken: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Url, :BizToken, :RequestId def initialize(url=nil, biztoken=nil, requestid=nil) @Url = url @BizToken = biztoken @RequestId = requestid end def deserialize(params) @Url = params['Url'] @BizToken = params['BizToken'] @RequestId = params['RequestId'] end end # 活体一比一详情 class DetectDetail < TencentCloud::Common::AbstractModel # @param ReqTime: 请求时间戳。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type ReqTime: String # @param Seq: 本次活体一比一请求的唯一标记。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Seq: String # @param Idcard: 参与本次活体一比一的身份证号。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Idcard: String # @param Name: 参与本次活体一比一的姓名。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Name: String # @param Sim: 本次活体一比一的相似度。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Sim: String # @param IsNeedCharge: 本次活体一比一是否收费 # 注意:此字段可能返回 null,表示取不到有效值。 # @type IsNeedCharge: Boolean # @param Errcode: 本次活体一比一最终结果。0为成功 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Errcode: Integer # @param Errmsg: 本次活体一比一最终结果描述。(仅描述用,文案更新时不会通知。) # 注意:此字段可能返回 null,表示取不到有效值。 # @type Errmsg: String # @param Livestatus: 本次活体结果。0为成功 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Livestatus: Integer # @param Livemsg: 本次活体结果描述。(仅描述用,文案更新时不会通知。) # 注意:此字段可能返回 null,表示取不到有效值。 # @type Livemsg: String # @param Comparestatus: 本次一比一结果。0为成功 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Comparestatus: Integer # @param Comparemsg: 本次一比一结果描述。(仅描述用,文案更新时不会通知。) # 注意:此字段可能返回 null,表示取不到有效值。 # @type Comparemsg: String # @param CompareLibType: 比对库源类型。包括: # 公安商业库; # 业务方自有库(用户上传照片、客户的混合库、混合部署库); # 二次验证库; # 人工审核库; # 注意:此字段可能返回 null,表示取不到有效值。 # @type CompareLibType: String attr_accessor :ReqTime, :Seq, :Idcard, :Name, :Sim, :IsNeedCharge, :Errcode, :Errmsg, :Livestatus, :Livemsg, :Comparestatus, :Comparemsg, :CompareLibType def initialize(reqtime=nil, seq=nil, idcard=nil, name=nil, sim=nil, isneedcharge=nil, errcode=nil, errmsg=nil, livestatus=nil, livemsg=nil, comparestatus=nil, comparemsg=nil, comparelibtype=nil) @ReqTime = reqtime @Seq = seq @Idcard = idcard @Name = name @Sim = sim @IsNeedCharge = isneedcharge @Errcode = errcode @Errmsg = errmsg @Livestatus = livestatus @Livemsg = livemsg @Comparestatus = comparestatus @Comparemsg = comparemsg @CompareLibType = comparelibtype end def deserialize(params) @ReqTime = params['ReqTime'] @Seq = params['Seq'] @Idcard = params['Idcard'] @Name = params['Name'] @Sim = params['Sim'] @IsNeedCharge = params['IsNeedCharge'] @Errcode = params['Errcode'] @Errmsg = params['Errmsg'] @Livestatus = params['Livestatus'] @Livemsg = params['Livemsg'] @Comparestatus = params['Comparestatus'] @Comparemsg = params['Comparemsg'] @CompareLibType = params['CompareLibType'] end end # 核身最佳帧信息 class DetectInfoBestFrame < TencentCloud::Common::AbstractModel # @param BestFrame: 活体比对最佳帧。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type BestFrame: String # @param BestFrames: 自截帧。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type BestFrames: Array attr_accessor :BestFrame, :BestFrames def initialize(bestframe=nil, bestframes=nil) @BestFrame = bestframe @BestFrames = bestframes end def deserialize(params) @BestFrame = params['BestFrame'] @BestFrames = params['BestFrames'] end end # 核身身份证图片信息 class DetectInfoIdCardData < TencentCloud::Common::AbstractModel # @param OcrFront: OCR正面照片的base64编码。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type OcrFront: String # @param OcrBack: OCR反面照片的base64编码 # 注意:此字段可能返回 null,表示取不到有效值。 # @type OcrBack: String # @param ProcessedFrontImage: 旋转裁边后的正面照片base64编码。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type ProcessedFrontImage: String # @param ProcessedBackImage: 旋转裁边后的背面照片base64编码。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type ProcessedBackImage: String # @param Avatar: 身份证正面人像图base64编码。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Avatar: String attr_accessor :OcrFront, :OcrBack, :ProcessedFrontImage, :ProcessedBackImage, :Avatar def initialize(ocrfront=nil, ocrback=nil, processedfrontimage=nil, processedbackimage=nil, avatar=nil) @OcrFront = ocrfront @OcrBack = ocrback @ProcessedFrontImage = processedfrontimage @ProcessedBackImage = processedbackimage @Avatar = avatar end def deserialize(params) @OcrFront = params['OcrFront'] @OcrBack = params['OcrBack'] @ProcessedFrontImage = params['ProcessedFrontImage'] @ProcessedBackImage = params['ProcessedBackImage'] @Avatar = params['Avatar'] end end # 核身文本信息 class DetectInfoText < TencentCloud::Common::AbstractModel # @param ErrCode: 本次流程最终验证结果。0为成功 # 注意:此字段可能返回 null,表示取不到有效值。 # @type ErrCode: Integer # @param ErrMsg: 本次流程最终验证结果描述。(仅描述用,文案更新时不会通知。) # 注意:此字段可能返回 null,表示取不到有效值。 # @type ErrMsg: String # @param IdCard: 本次验证使用的身份证号。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type IdCard: String # @param Name: 本次验证使用的姓名。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Name: String # @param OcrNation: Ocr识别结果。民族。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type OcrNation: String # @param OcrAddress: Ocr识别结果。家庭住址。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type OcrAddress: String # @param OcrBirth: Ocr识别结果。生日。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type OcrBirth: String # @param OcrAuthority: Ocr识别结果。签发机关。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type OcrAuthority: String # @param OcrValidDate: Ocr识别结果。有效日期。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type OcrValidDate: String # @param OcrName: Ocr识别结果。姓名。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type OcrName: String # @param OcrIdCard: Ocr识别结果。身份证号。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type OcrIdCard: String # @param OcrGender: Ocr识别结果。性别。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type OcrGender: String # @param LiveStatus: 本次流程最终活体结果。0为成功 # 注意:此字段可能返回 null,表示取不到有效值。 # @type LiveStatus: Integer # @param LiveMsg: 本次流程最终活体结果描述。(仅描述用,文案更新时不会通知。) # 注意:此字段可能返回 null,表示取不到有效值。 # @type LiveMsg: String # @param Comparestatus: 本次流程最终一比一结果。0为成功 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Comparestatus: Integer # @param Comparemsg: 本次流程最终一比一结果描述。(仅描述用,文案更新时不会通知。) # 注意:此字段可能返回 null,表示取不到有效值。 # @type Comparemsg: String # @param Sim: 本次流程活体一比一的分数,取值范围 [0.00, 100.00]。相似度大于等于70时才判断为同一人,也可根据具体场景自行调整阈值(阈值70的误通过率为千分之一,阈值80的误通过率是万分之一) # 注意:此字段可能返回 null,表示取不到有效值。 # @type Sim: String # @param Location: 地理位置经纬度。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Location: String # @param Extra: Auth接口带入额外信息。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Extra: String # @param LivenessDetail: 本次流程进行的活体一比一流水。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type LivenessDetail: Array # @param Mobile: 手机号码。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Mobile: String # @param CompareLibType: 本次流程最终比对库源类型。包括: # 权威库; # 业务方自有库(用户上传照片、客户的混合库、混合部署库); # 二次验证库; # 人工审核库; # 注意:此字段可能返回 null,表示取不到有效值。 # @type CompareLibType: String attr_accessor :ErrCode, :ErrMsg, :IdCard, :Name, :OcrNation, :OcrAddress, :OcrBirth, :OcrAuthority, :OcrValidDate, :OcrName, :OcrIdCard, :OcrGender, :LiveStatus, :LiveMsg, :Comparestatus, :Comparemsg, :Sim, :Location, :Extra, :LivenessDetail, :Mobile, :CompareLibType def initialize(errcode=nil, errmsg=nil, idcard=nil, name=nil, ocrnation=nil, ocraddress=nil, ocrbirth=nil, ocrauthority=nil, ocrvaliddate=nil, ocrname=nil, ocridcard=nil, ocrgender=nil, livestatus=nil, livemsg=nil, comparestatus=nil, comparemsg=nil, sim=nil, location=nil, extra=nil, livenessdetail=nil, mobile=nil, comparelibtype=nil) @ErrCode = errcode @ErrMsg = errmsg @IdCard = idcard @Name = name @OcrNation = ocrnation @OcrAddress = ocraddress @OcrBirth = ocrbirth @OcrAuthority = ocrauthority @OcrValidDate = ocrvaliddate @OcrName = ocrname @OcrIdCard = ocridcard @OcrGender = ocrgender @LiveStatus = livestatus @LiveMsg = livemsg @Comparestatus = comparestatus @Comparemsg = comparemsg @Sim = sim @Location = location @Extra = extra @LivenessDetail = livenessdetail @Mobile = mobile @CompareLibType = comparelibtype end def deserialize(params) @ErrCode = params['ErrCode'] @ErrMsg = params['ErrMsg'] @IdCard = params['IdCard'] @Name = params['Name'] @OcrNation = params['OcrNation'] @OcrAddress = params['OcrAddress'] @OcrBirth = params['OcrBirth'] @OcrAuthority = params['OcrAuthority'] @OcrValidDate = params['OcrValidDate'] @OcrName = params['OcrName'] @OcrIdCard = params['OcrIdCard'] @OcrGender = params['OcrGender'] @LiveStatus = params['LiveStatus'] @LiveMsg = params['LiveMsg'] @Comparestatus = params['Comparestatus'] @Comparemsg = params['Comparemsg'] @Sim = params['Sim'] @Location = params['Location'] @Extra = params['Extra'] unless params['LivenessDetail'].nil? @LivenessDetail = [] params['LivenessDetail'].each do |i| @LivenessDetail << DetectDetail.new.deserialize(i) end end @Mobile = params['Mobile'] @CompareLibType = params['CompareLibType'] end end # 核身视频信息 class DetectInfoVideoData < TencentCloud::Common::AbstractModel # @param LivenessVideo: 活体视频的base64编码 # 注意:此字段可能返回 null,表示取不到有效值。 # @type LivenessVideo: String attr_accessor :LivenessVideo def initialize(livenessvideo=nil) @LivenessVideo = livenessvideo end def deserialize(params) @LivenessVideo = params['LivenessVideo'] end end # Eid出参 class EidInfo < TencentCloud::Common::AbstractModel # @param EidCode: 商户方 appeIDcode 的数字证书 # @type EidCode: String # @param EidSign: eID 中心针对商户方EidCode的电子签名 # @type EidSign: String attr_accessor :EidCode, :EidSign def initialize(eidcode=nil, eidsign=nil) @EidCode = eidcode @EidSign = eidsign end def deserialize(params) @EidCode = params['EidCode'] @EidSign = params['EidSign'] end end # EncryptedPhoneVerification请求参数结构体 class EncryptedPhoneVerificationRequest < TencentCloud::Common::AbstractModel # @param IdCard: 身份证号,加密方式以EncryptionMode为准 # @type IdCard: String # @param Name: 姓名,加密方式以EncryptionMode为准 # @type Name: String # @param Phone: 手机号,加密方式以EncryptionMode为准 # @type Phone: String # @param EncryptionMode: 敏感信息的加密方式,目前只支持MD5加密传输,参数取值: # 0:明文,不加密 # 1:使用MD5加密 # @type EncryptionMode: String attr_accessor :IdCard, :Name, :Phone, :EncryptionMode def initialize(idcard=nil, name=nil, phone=nil, encryptionmode=nil) @IdCard = idcard @Name = name @Phone = phone @EncryptionMode = encryptionmode end def deserialize(params) @IdCard = params['IdCard'] @Name = params['Name'] @Phone = params['Phone'] @EncryptionMode = params['EncryptionMode'] end end # EncryptedPhoneVerification返回参数结构体 class EncryptedPhoneVerificationResponse < TencentCloud::Common::AbstractModel # @param Result: 认证结果码: # 【收费结果码】 # 0: 认证通过 # -4: 信息不一致 # 【不收费结果码】 # -7: 身份证号码有误 # -9: 没有记录 # -11: 验证中心服务繁忙 # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Result, :Description, :RequestId def initialize(result=nil, description=nil, requestid=nil) @Result = result @Description = description @RequestId = requestid end def deserialize(params) @Result = params['Result'] @Description = params['Description'] @RequestId = params['RequestId'] end end # 敏感数据加密 class Encryption < TencentCloud::Common::AbstractModel # @param CiphertextBlob: 有加密需求的用户,接入传入kms的CiphertextBlob,关于数据加密可查阅<a href="https://cloud.tencent.com/document/product/1007/47180">数据加密</a> 文档。 # @type CiphertextBlob: String # @param EncryptList: 在使用加密服务时,填入要被加密的字段。本接口中可填入加密后的一个或多个字段 # @type EncryptList: Array # @param Iv: 有加密需求的用户,传入CBC加密的初始向量 # @type Iv: String attr_accessor :CiphertextBlob, :EncryptList, :Iv def initialize(ciphertextblob=nil, encryptlist=nil, iv=nil) @CiphertextBlob = ciphertextblob @EncryptList = encryptlist @Iv = iv end def deserialize(params) @CiphertextBlob = params['CiphertextBlob'] @EncryptList = params['EncryptList'] @Iv = params['Iv'] end end # GetActionSequence请求参数结构体 class GetActionSequenceRequest < TencentCloud::Common::AbstractModel # @param ActionType: 默认不需要使用 # @type ActionType: String attr_accessor :ActionType def initialize(actiontype=nil) @ActionType = actiontype end def deserialize(params) @ActionType = params['ActionType'] end end # GetActionSequence返回参数结构体 class GetActionSequenceResponse < TencentCloud::Common::AbstractModel # @param ActionSequence: 动作顺序(2,1 or 1,2) 。1代表张嘴,2代表闭眼。 # @type ActionSequence: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :ActionSequence, :RequestId def initialize(actionsequence=nil, requestid=nil) @ActionSequence = actionsequence @RequestId = requestid end def deserialize(params) @ActionSequence = params['ActionSequence'] @RequestId = params['RequestId'] end end # GetDetectInfoEnhanced请求参数结构体 class GetDetectInfoEnhancedRequest < TencentCloud::Common::AbstractModel # @param BizToken: 人脸核身流程的标识,调用DetectAuth接口时生成。 # @type BizToken: String # @param RuleId: 用于细分客户使用场景,由腾讯侧在线下对接时分配。 # @type RuleId: String # @param InfoType: 指定拉取的结果信息,取值(0:全部;1:文本类;2:身份证信息;3:视频最佳截图信息)。 # 如 13表示拉取文本类、视频最佳截图信息。 # 默认值:0 # @type InfoType: String # @param BestFramesCount: 从活体视频中截取一定张数的最佳帧(仅部分服务支持,若需使用请与慧眼小助手沟通)。默认为0,最大为10,超出10的最多只给10张。(InfoType需要包含3) # @type BestFramesCount: Integer # @param IsCutIdCardImage: 是否对身份证照片进行裁边。默认为false。(InfoType需要包含2) # @type IsCutIdCardImage: Boolean # @param IsNeedIdCardAvatar: 是否需要从身份证中抠出头像。默认为false。(InfoType需要包含2) # @type IsNeedIdCardAvatar: Boolean # @param IsEncrypt: 是否需要对返回中的敏感信息进行加密。其中敏感信息包括:Response.Text.IdCard、Response.Text.Name、Response.Text.OcrIdCard、Response.Text.OcrName # @type IsEncrypt: Boolean attr_accessor :BizToken, :RuleId, :InfoType, :BestFramesCount, :IsCutIdCardImage, :IsNeedIdCardAvatar, :IsEncrypt def initialize(biztoken=nil, ruleid=nil, infotype=nil, bestframescount=nil, iscutidcardimage=nil, isneedidcardavatar=nil, isencrypt=nil) @BizToken = biztoken @RuleId = ruleid @InfoType = infotype @BestFramesCount = bestframescount @IsCutIdCardImage = iscutidcardimage @IsNeedIdCardAvatar = isneedidcardavatar @IsEncrypt = isencrypt end def deserialize(params) @BizToken = params['BizToken'] @RuleId = params['RuleId'] @InfoType = params['InfoType'] @BestFramesCount = params['BestFramesCount'] @IsCutIdCardImage = params['IsCutIdCardImage'] @IsNeedIdCardAvatar = params['IsNeedIdCardAvatar'] @IsEncrypt = params['IsEncrypt'] end end # GetDetectInfoEnhanced返回参数结构体 class GetDetectInfoEnhancedResponse < TencentCloud::Common::AbstractModel # @param Text: 文本类信息。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Text: :class:`Tencentcloud::Faceid.v20180301.models.DetectInfoText` # @param IdCardData: 身份证照片信息。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type IdCardData: :class:`Tencentcloud::Faceid.v20180301.models.DetectInfoIdCardData` # @param BestFrame: 最佳帧信息。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type BestFrame: :class:`Tencentcloud::Faceid.v20180301.models.DetectInfoBestFrame` # @param VideoData: 视频信息。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type VideoData: :class:`Tencentcloud::Faceid.v20180301.models.DetectInfoVideoData` # @param Encryption: 敏感数据加密信息。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Encryption: :class:`Tencentcloud::Faceid.v20180301.models.Encryption` # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Text, :IdCardData, :BestFrame, :VideoData, :Encryption, :RequestId def initialize(text=nil, idcarddata=nil, bestframe=nil, videodata=nil, encryption=nil, requestid=nil) @Text = text @IdCardData = idcarddata @BestFrame = bestframe @VideoData = videodata @Encryption = encryption @RequestId = requestid end def deserialize(params) unless params['Text'].nil? @Text = DetectInfoText.new.deserialize(params['Text']) end unless params['IdCardData'].nil? @IdCardData = DetectInfoIdCardData.new.deserialize(params['IdCardData']) end unless params['BestFrame'].nil? @BestFrame = DetectInfoBestFrame.new.deserialize(params['BestFrame']) end unless params['VideoData'].nil? @VideoData = DetectInfoVideoData.new.deserialize(params['VideoData']) end unless params['Encryption'].nil? @Encryption = Encryption.new.deserialize(params['Encryption']) end @RequestId = params['RequestId'] end end # GetDetectInfo请求参数结构体 class GetDetectInfoRequest < TencentCloud::Common::AbstractModel # @param BizToken: 人脸核身流程的标识,调用DetectAuth接口时生成。 # @type BizToken: String # @param RuleId: 用于细分客户使用场景,申请开通服务后,可以在腾讯云慧眼人脸核身控制台(https://console.cloud.tencent.com/faceid) 自助接入里面创建,审核通过后即可调用。如有疑问,请加慧眼小助手微信(faceid001)进行咨询。 # @type RuleId: String # @param InfoType: 指定拉取的结果信息,取值(0:全部;1:文本类;2:身份证正反面;3:视频最佳截图照片;4:视频)。 # 如 134表示拉取文本类、视频最佳截图照片、视频。 # 默认值:0 # @type InfoType: String attr_accessor :BizToken, :RuleId, :InfoType def initialize(biztoken=nil, ruleid=nil, infotype=nil) @BizToken = biztoken @RuleId = ruleid @InfoType = infotype end def deserialize(params) @BizToken = params['BizToken'] @RuleId = params['RuleId'] @InfoType = params['InfoType'] end end # GetDetectInfo返回参数结构体 class GetDetectInfoResponse < TencentCloud::Common::AbstractModel # @param DetectInfo: JSON字符串。 # { # // 文本类信息 # "Text": { # "ErrCode": null, // 本次核身最终结果。0为成功 # "ErrMsg": null, // 本次核身最终结果信息描述。 # "IdCard": "", // 本次核身最终获得的身份证号。 # "Name": "", // 本次核身最终获得的姓名。 # "OcrNation": null, // ocr阶段获取的民族 # "OcrAddress": null, // ocr阶段获取的地址 # "OcrBirth": null, // ocr阶段获取的出生信息 # "OcrAuthority": null, // ocr阶段获取的证件签发机关 # "OcrValidDate": null, // ocr阶段获取的证件有效期 # "OcrName": null, // ocr阶段获取的姓名 # "OcrIdCard": null, // ocr阶段获取的身份证号 # "OcrGender": null, // ocr阶段获取的性别 # "LiveStatus": null, // 活体检测阶段的错误码。0为成功 # "LiveMsg": null, // 活体检测阶段的错误信息 # "Comparestatus": null,// 一比一阶段的错误码。0为成功 # "Comparemsg": null, // 一比一阶段的错误信息 # "Sim": null, // 比对相似度 # "Location": null, // 地理位置信息 # "Extra": "", // DetectAuth结果传进来的Extra信息 # "Detail": { // 活体一比一信息详情 # "LivenessData": [ # { # ErrCode: null, // 活体比对验证错误码 # ErrMsg: null, // 活体比对验证错误描述 # ReqTime: null, // 活体验证时间戳 # IdCard: null, // 验证身份证号 # Name: null // 验证姓名 # } # ] # } # }, # // 身份证正反面照片Base64 # "IdCardData": { # "OcrFront": null, # "OcrBack": null # }, # // 视频最佳帧截图Base64 # "BestFrame": { # "BestFrame": null # }, # // 活体视频Base64 # "VideoData": { # "LivenessVideo": null # } # } # @type DetectInfo: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :DetectInfo, :RequestId def initialize(detectinfo=nil, requestid=nil) @DetectInfo = detectinfo @RequestId = requestid end def deserialize(params) @DetectInfo = params['DetectInfo'] @RequestId = params['RequestId'] end end # GetEidResult请求参数结构体 class GetEidResultRequest < TencentCloud::Common::AbstractModel # @param EidToken: 人脸核身流程的标识,调用GetEidToken接口时生成的。 # @type EidToken: String # @param InfoType: 指定拉取的结果信息,取值(0:全部;1:文本类;2:身份证信息;3:最佳截图信息)。 # 如 13表示拉取文本类、最佳截图信息。 # 默认值:0 # @type InfoType: String # @param BestFramesCount: 从活体视频中截取一定张数的最佳帧。默认为0,最大为3,超出3的最多只给3张。(InfoType需要包含3) # @type BestFramesCount: Integer attr_accessor :EidToken, :InfoType, :BestFramesCount def initialize(eidtoken=nil, infotype=nil, bestframescount=nil) @EidToken = eidtoken @InfoType = infotype @BestFramesCount = bestframescount end def deserialize(params) @EidToken = params['EidToken'] @InfoType = params['InfoType'] @BestFramesCount = params['BestFramesCount'] end end # GetEidResult返回参数结构体 class GetEidResultResponse < TencentCloud::Common::AbstractModel # @param Text: 文本类信息。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Text: :class:`Tencentcloud::Faceid.v20180301.models.DetectInfoText` # @param IdCardData: 身份证照片信息。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type IdCardData: :class:`Tencentcloud::Faceid.v20180301.models.DetectInfoIdCardData` # @param BestFrame: 最佳帧信息。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type BestFrame: :class:`Tencentcloud::Faceid.v20180301.models.DetectInfoBestFrame` # @param EidInfo: Eid信息 # 注意:此字段可能返回 null,表示取不到有效值。 # @type EidInfo: :class:`Tencentcloud::Faceid.v20180301.models.EidInfo` # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Text, :IdCardData, :BestFrame, :EidInfo, :RequestId def initialize(text=nil, idcarddata=nil, bestframe=nil, eidinfo=nil, requestid=nil) @Text = text @IdCardData = idcarddata @BestFrame = bestframe @EidInfo = eidinfo @RequestId = requestid end def deserialize(params) unless params['Text'].nil? @Text = DetectInfoText.new.deserialize(params['Text']) end unless params['IdCardData'].nil? @IdCardData = DetectInfoIdCardData.new.deserialize(params['IdCardData']) end unless params['BestFrame'].nil? @BestFrame = DetectInfoBestFrame.new.deserialize(params['BestFrame']) end unless params['EidInfo'].nil? @EidInfo = EidInfo.new.deserialize(params['EidInfo']) end @RequestId = params['RequestId'] end end # 获取token时的的配置 class GetEidTokenConfig < TencentCloud::Common::AbstractModel # @param InputType: 姓名身份证输入方式。 # 1:传身份证正反面OCR # 2:传身份证正面OCR # 3:用户手动输入 # 4:客户后台传入 # 默认1 # 注:使用OCR时仅支持用户修改结果中的姓名 # @type InputType: String attr_accessor :InputType def initialize(inputtype=nil) @InputType = inputtype end def deserialize(params) @InputType = params['InputType'] end end # GetEidToken请求参数结构体 class GetEidTokenRequest < TencentCloud::Common::AbstractModel # @param MerchantId: EID商户id # @type MerchantId: String # @param IdCard: 身份标识(未使用OCR服务时,必须传入)。 # 规则:a-zA-Z0-9组合。最长长度32位。 # @type IdCard: String # @param Name: 姓名。(未使用OCR服务时,必须传入)最长长度32位。中文请使用UTF-8编码。 # @type Name: String # @param Extra: 透传字段,在获取验证结果时返回。 # @type Extra: String # @param Config: 小程序模式配置,包括如何传入姓名身份证的配置。 # @type Config: :class:`Tencentcloud::Faceid.v20180301.models.GetEidTokenConfig` attr_accessor :MerchantId, :IdCard, :Name, :Extra, :Config def initialize(merchantid=nil, idcard=nil, name=nil, extra=nil, config=nil) @MerchantId = merchantid @IdCard = idcard @Name = name @Extra = extra @Config = config end def deserialize(params) @MerchantId = params['MerchantId'] @IdCard = params['IdCard'] @Name = params['Name'] @Extra = params['Extra'] unless params['Config'].nil? @Config = GetEidTokenConfig.new.deserialize(params['Config']) end end end # GetEidToken返回参数结构体 class GetEidTokenResponse < TencentCloud::Common::AbstractModel # @param EidToken: 一次核身流程的标识,有效时间为7,200秒; # 完成核身后,可用该标识获取验证结果信息。 # @type EidToken: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :EidToken, :RequestId def initialize(eidtoken=nil, requestid=nil) @EidToken = eidtoken @RequestId = requestid end def deserialize(params) @EidToken = params['EidToken'] @RequestId = params['RequestId'] end end # GetFaceIdResult请求参数结构体 class GetFaceIdResultRequest < TencentCloud::Common::AbstractModel # @param FaceIdToken: SDK人脸核身流程的标识,调用GetFaceIdToken接口时生成。 # @type FaceIdToken: String # @param IsNeedVideo: 是否需要拉取视频,默认false不需要 # @type IsNeedVideo: Boolean # @param IsNeedBestFrame: 是否需要拉取截帧,默认false不需要 # @type IsNeedBestFrame: Boolean attr_accessor :FaceIdToken, :IsNeedVideo, :IsNeedBestFrame def initialize(faceidtoken=nil, isneedvideo=nil, isneedbestframe=nil) @FaceIdToken = faceidtoken @IsNeedVideo = isneedvideo @IsNeedBestFrame = isneedbestframe end def deserialize(params) @FaceIdToken = params['FaceIdToken'] @IsNeedVideo = params['IsNeedVideo'] @IsNeedBestFrame = params['IsNeedBestFrame'] end end # GetFaceIdResult返回参数结构体 class GetFaceIdResultResponse < TencentCloud::Common::AbstractModel # @param IdCard: 身份证 # @type IdCard: String # @param Name: 姓名 # @type Name: String # @param Result: 业务核验结果,参考https://cloud.tencent.com/document/product/1007/47912 # @type Result: String # @param Description: 业务核验描述 # @type Description: String # @param Similarity: 相似度,0-100,数值越大相似度越高 # @type Similarity: Float # @param VideoBase64: 用户核验的视频 # 注意:此字段可能返回 null,表示取不到有效值。 # @type VideoBase64: String # @param BestFrameBase64: 用户核验视频的截帧 # 注意:此字段可能返回 null,表示取不到有效值。 # @type BestFrameBase64: String # @param Extra: 获取token时透传的信息 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Extra: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :IdCard, :Name, :Result, :Description, :Similarity, :VideoBase64, :BestFrameBase64, :Extra, :RequestId def initialize(idcard=nil, name=nil, result=nil, description=nil, similarity=nil, videobase64=nil, bestframebase64=nil, extra=nil, requestid=nil) @IdCard = idcard @Name = name @Result = result @Description = description @Similarity = similarity @VideoBase64 = videobase64 @BestFrameBase64 = bestframebase64 @Extra = extra @RequestId = requestid end def deserialize(params) @IdCard = params['IdCard'] @Name = params['Name'] @Result = params['Result'] @Description = params['Description'] @Similarity = params['Similarity'] @VideoBase64 = params['VideoBase64'] @BestFrameBase64 = params['BestFrameBase64'] @Extra = params['Extra'] @RequestId = params['RequestId'] end end # GetFaceIdToken请求参数结构体 class GetFaceIdTokenRequest < TencentCloud::Common::AbstractModel # @param CompareLib: 本地上传照片(LOCAL)、商业库(BUSINESS) # @type CompareLib: String # @param IdCard: CompareLib为商业库时必传。 # @type IdCard: String # @param Name: CompareLib为商业库库时必传。 # @type Name: String # @param ImageBase64: CompareLib为上传照片比对时必传,Base64后图片最大8MB。 # 请使用标准的Base64编码方式(带=补位),编码规范参考RFC4648。 # @type ImageBase64: String # @param Meta: SDK中生成的Meta字符串 # @type Meta: String # @param Extra: 透传参数 1000长度字符串 # @type Extra: String attr_accessor :CompareLib, :IdCard, :Name, :ImageBase64, :Meta, :Extra def initialize(comparelib=nil, idcard=nil, name=nil, imagebase64=nil, meta=nil, extra=nil) @CompareLib = comparelib @IdCard = idcard @Name = name @ImageBase64 = imagebase64 @Meta = meta @Extra = extra end def deserialize(params) @CompareLib = params['CompareLib'] @IdCard = params['IdCard'] @Name = params['Name'] @ImageBase64 = params['ImageBase64'] @Meta = params['Meta'] @Extra = params['Extra'] end end # GetFaceIdToken返回参数结构体 class GetFaceIdTokenResponse < TencentCloud::Common::AbstractModel # @param FaceIdToken: 有效期 10分钟。只能完成1次核身。 # @type FaceIdToken: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :FaceIdToken, :RequestId def initialize(faceidtoken=nil, requestid=nil) @FaceIdToken = faceidtoken @RequestId = requestid end def deserialize(params) @FaceIdToken = params['FaceIdToken'] @RequestId = params['RequestId'] end end # GetLiveCode请求参数结构体 class GetLiveCodeRequest < TencentCloud::Common::AbstractModel def initialize() end def deserialize(params) end end # GetLiveCode返回参数结构体 class GetLiveCodeResponse < TencentCloud::Common::AbstractModel # @param LiveCode: 数字验证码,如:1234 # @type LiveCode: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :LiveCode, :RequestId def initialize(livecode=nil, requestid=nil) @LiveCode = livecode @RequestId = requestid end def deserialize(params) @LiveCode = params['LiveCode'] @RequestId = params['RequestId'] end end # GetRealNameAuthResult请求参数结构体 class GetRealNameAuthResultRequest < TencentCloud::Common::AbstractModel # @param AuthToken: 实名认证凭证 # @type AuthToken: String attr_accessor :AuthToken def initialize(authtoken=nil) @AuthToken = authtoken end def deserialize(params) @AuthToken = params['AuthToken'] end end # GetRealNameAuthResult返回参数结构体 class GetRealNameAuthResultResponse < TencentCloud::Common::AbstractModel # @param ResultType: 认证结果码,收费情况如下: # 收费码: # 0: 姓名和身份证号一致 # -1: 姓名和身份证号不一致 # -2: 姓名和微信实名姓名不一致 # 不收费码: # -3: 微信号未实名 # @type ResultType: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :ResultType, :RequestId def initialize(resulttype=nil, requestid=nil) @ResultType = resulttype @RequestId = requestid end def deserialize(params) @ResultType = params['ResultType'] @RequestId = params['RequestId'] end end # GetRealNameAuthToken请求参数结构体 class GetRealNameAuthTokenRequest < TencentCloud::Common::AbstractModel # @param Name: 姓名 # @type Name: String # @param IDCard: 身份证号 # @type IDCard: String # @param CallbackURL: 回调地址。实名认证完成后,将会重定向到这个地址通知认证发起方。仅支持http或https协议。 # @type CallbackURL: String attr_accessor :Name, :IDCard, :CallbackURL def initialize(name=nil, idcard=nil, callbackurl=nil) @Name = name @IDCard = idcard @CallbackURL = callbackurl end def deserialize(params) @Name = params['Name'] @IDCard = params['IDCard'] @CallbackURL = params['CallbackURL'] end end # GetRealNameAuthToken返回参数结构体 class GetRealNameAuthTokenResponse < TencentCloud::Common::AbstractModel # @param AuthToken: 查询实名认证结果的唯一凭证 # @type AuthToken: String # @param RedirectURL: 实名认证授权地址,认证发起方需要重定向到这个地址获取认证用户的授权,仅能在微信环境下打开。 # @type RedirectURL: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :AuthToken, :RedirectURL, :RequestId def initialize(authtoken=nil, redirecturl=nil, requestid=nil) @AuthToken = authtoken @RedirectURL = redirecturl @RequestId = requestid end def deserialize(params) @AuthToken = params['AuthToken'] @RedirectURL = params['RedirectURL'] @RequestId = params['RequestId'] end end # IdCardOCRVerification请求参数结构体 class IdCardOCRVerificationRequest < TencentCloud::Common::AbstractModel # @param IdCard: 身份证号 # 姓名和身份证号、ImageBase64、ImageUrl三者必须提供其中之一。若都提供了,则按照姓名和身份证号>ImageBase64>ImageUrl的优先级使用参数。 # @type IdCard: String # @param Name: 姓名 # @type Name: String # @param ImageBase64: 身份证人像面的 Base64 值 # 支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。 # 支持的图片大小:所下载图片经Base64编码后不超过 3M。请使用标准的Base64编码方式(带=补位),编码规范参考RFC4648。 # @type ImageBase64: String # @param ImageUrl: 身份证人像面的 Url 地址 # 支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。 # 支持的图片大小:所下载图片经 Base64 编码后不超过 3M。图片下载时间不超过 3 秒。 # 图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。 # 非腾讯云存储的 Url 速度和稳定性可能受一定影响。 # @type ImageUrl: String # @param Encryption: 敏感数据加密信息。对传入信息(姓名、身份证号)有加密需求的用户可使用此参数,详情请点击左侧链接。 # @type Encryption: :class:`Tencentcloud::Faceid.v20180301.models.Encryption` attr_accessor :IdCard, :Name, :ImageBase64, :ImageUrl, :Encryption def initialize(idcard=nil, name=nil, imagebase64=nil, imageurl=nil, encryption=nil) @IdCard = idcard @Name = name @ImageBase64 = imagebase64 @ImageUrl = imageurl @Encryption = encryption end def deserialize(params) @IdCard = params['IdCard'] @Name = params['Name'] @ImageBase64 = params['ImageBase64'] @ImageUrl = params['ImageUrl'] unless params['Encryption'].nil? @Encryption = Encryption.new.deserialize(params['Encryption']) end end end # IdCardOCRVerification返回参数结构体 class IdCardOCRVerificationResponse < TencentCloud::Common::AbstractModel # @param Result: 认证结果码,收费情况如下。 # 收费结果码: # 0: 姓名和身份证号一致 # -1: 姓名和身份证号不一致 # 不收费结果码: # -2: 非法身份证号(长度、校验位等不正确) # -3: 非法姓名(长度、格式等不正确) # -4: 证件库服务异常 # -5: 证件库中无此身份证记录 # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param Name: 用于验证的姓名 # @type Name: String # @param IdCard: 用于验证的身份证号 # @type IdCard: String # @param Sex: OCR得到的性别 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Sex: String # @param Nation: OCR得到的民族 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Nation: String # @param Birth: OCR得到的生日 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Birth: String # @param Address: OCR得到的地址 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Address: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Result, :Description, :Name, :IdCard, :Sex, :Nation, :Birth, :Address, :RequestId def initialize(result=nil, description=nil, name=nil, idcard=nil, sex=nil, nation=nil, birth=nil, address=nil, requestid=nil) @Result = result @Description = description @Name = name @IdCard = idcard @Sex = sex @Nation = nation @Birth = birth @Address = address @RequestId = requestid end def deserialize(params) @Result = params['Result'] @Description = params['Description'] @Name = params['Name'] @IdCard = params['IdCard'] @Sex = params['Sex'] @Nation = params['Nation'] @Birth = params['Birth'] @Address = params['Address'] @RequestId = params['RequestId'] end end # IdCardVerification请求参数结构体 class IdCardVerificationRequest < TencentCloud::Common::AbstractModel # @param IdCard: 身份证号 # @type IdCard: String # @param Name: 姓名 # @type Name: String attr_accessor :IdCard, :Name def initialize(idcard=nil, name=nil) @IdCard = idcard @Name = name end def deserialize(params) @IdCard = params['IdCard'] @Name = params['Name'] end end # IdCardVerification返回参数结构体 class IdCardVerificationResponse < TencentCloud::Common::AbstractModel # @param Result: 认证结果码,收费情况如下。 # 收费结果码: # 0: 姓名和身份证号一致 # -1: 姓名和身份证号不一致 # 不收费结果码: # -2: 非法身份证号(长度、校验位等不正确) # -3: 非法姓名(长度、格式等不正确) # -4: 证件库服务异常 # -5: 证件库中无此身份证记录 # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Result, :Description, :RequestId def initialize(result=nil, description=nil, requestid=nil) @Result = result @Description = description @RequestId = requestid end def deserialize(params) @Result = params['Result'] @Description = params['Description'] @RequestId = params['RequestId'] end end # ImageRecognition请求参数结构体 class ImageRecognitionRequest < TencentCloud::Common::AbstractModel # @param IdCard: 身份证号 # @type IdCard: String # @param Name: 姓名。中文请使用UTF-8编码。 # @type Name: String # @param ImageBase64: 用于人脸比对的照片,图片的Base64值; # Base64编码后的图片数据大小不超过3M,仅支持jpg、png格式。 # 请使用标准的Base64编码方式(带=补位),编码规范参考RFC4648。 # @type ImageBase64: String # @param Optional: 本接口不需要传递此参数。 # @type Optional: String attr_accessor :IdCard, :Name, :ImageBase64, :Optional def initialize(idcard=nil, name=nil, imagebase64=nil, optional=nil) @IdCard = idcard @Name = name @ImageBase64 = imagebase64 @Optional = optional end def deserialize(params) @IdCard = params['IdCard'] @Name = params['Name'] @ImageBase64 = params['ImageBase64'] @Optional = params['Optional'] end end # ImageRecognition返回参数结构体 class ImageRecognitionResponse < TencentCloud::Common::AbstractModel # @param Sim: 相似度,取值范围 [0.00, 100.00]。推荐相似度大于等于70时可判断为同一人,可根据具体场景自行调整阈值(阈值70的误通过率为千分之一,阈值80的误通过率是万分之一) # @type Sim: Float # @param Result: 业务错误码,成功情况返回Success, 错误情况请参考下方错误码 列表中FailedOperation部分 # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Sim, :Result, :Description, :RequestId def initialize(sim=nil, result=nil, description=nil, requestid=nil) @Sim = sim @Result = result @Description = description @RequestId = requestid end def deserialize(params) @Sim = params['Sim'] @Result = params['Result'] @Description = params['Description'] @RequestId = params['RequestId'] end end # LivenessCompare请求参数结构体 class LivenessCompareRequest < TencentCloud::Common::AbstractModel # @param ImageBase64: 用于人脸比对的照片,图片的Base64值; # Base64编码后的图片数据大小不超过3M,仅支持jpg、png格式。 # 请使用标准的Base64编码方式(带=补位),编码规范参考RFC4648。 # @type ImageBase64: String # @param VideoBase64: 用于活体检测的视频,视频的Base64值; # Base64编码后的大小不超过8M,支持mp4、avi、flv格式。 # 请使用标准的Base64编码方式(带=补位),编码规范参考RFC4648。 # @type VideoBase64: String # @param LivenessType: 活体检测类型,取值:LIP/ACTION/SILENT。 # LIP为数字模式,ACTION为动作模式,SILENT为静默模式,三种模式选择一种传入。 # @type LivenessType: String # @param ValidateData: 数字模式传参:数字验证码(1234),需先调用接口获取数字验证码; # 动作模式传参:传动作顺序(2,1 or 1,2),需先调用接口获取动作顺序; # 静默模式传参:空。 # @type ValidateData: String # @param Optional: 额外配置,传入JSON字符串。 # { # "BestFrameNum": 2 //需要返回多张最佳截图,取值范围1-10 # } # @type Optional: String attr_accessor :ImageBase64, :VideoBase64, :LivenessType, :ValidateData, :Optional def initialize(imagebase64=nil, videobase64=nil, livenesstype=nil, validatedata=nil, optional=nil) @ImageBase64 = imagebase64 @VideoBase64 = videobase64 @LivenessType = livenesstype @ValidateData = validatedata @Optional = optional end def deserialize(params) @ImageBase64 = params['ImageBase64'] @VideoBase64 = params['VideoBase64'] @LivenessType = params['LivenessType'] @ValidateData = params['ValidateData'] @Optional = params['Optional'] end end # LivenessCompare返回参数结构体 class LivenessCompareResponse < TencentCloud::Common::AbstractModel # @param BestFrameBase64: 验证通过后的视频最佳截图照片,照片为BASE64编码后的值,jpg格式。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type BestFrameBase64: String # @param Sim: 相似度,取值范围 [0.00, 100.00]。推荐相似度大于等于70时可判断为同一人,可根据具体场景自行调整阈值(阈值70的误通过率为千分之一,阈值80的误通过率是万分之一)。 # @type Sim: Float # @param Result: 业务错误码,成功情况返回Success, 错误情况请参考下方错误码 列表中FailedOperation部分 # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param BestFrameList: 最佳截图列表,仅在配置了返回多张最佳截图时返回。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type BestFrameList: Array # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :BestFrameBase64, :Sim, :Result, :Description, :BestFrameList, :RequestId def initialize(bestframebase64=nil, sim=nil, result=nil, description=nil, bestframelist=nil, requestid=nil) @BestFrameBase64 = bestframebase64 @Sim = sim @Result = result @Description = description @BestFrameList = bestframelist @RequestId = requestid end def deserialize(params) @BestFrameBase64 = params['BestFrameBase64'] @Sim = params['Sim'] @Result = params['Result'] @Description = params['Description'] @BestFrameList = params['BestFrameList'] @RequestId = params['RequestId'] end end # LivenessRecognition请求参数结构体 class LivenessRecognitionRequest < TencentCloud::Common::AbstractModel # @param IdCard: 身份证号 # @type IdCard: String # @param Name: 姓名。中文请使用UTF-8编码。 # @type Name: String # @param VideoBase64: 用于活体检测的视频,视频的BASE64值; # BASE64编码后的大小不超过8M,支持mp4、avi、flv格式。 # @type VideoBase64: String # @param LivenessType: 活体检测类型,取值:LIP/ACTION/SILENT。 # LIP为数字模式,ACTION为动作模式,SILENT为静默模式,三种模式选择一种传入。 # @type LivenessType: String # @param ValidateData: 数字模式传参:数字验证码(1234),需先调用接口获取数字验证码; # 动作模式传参:传动作顺序(2,1 or 1,2),需先调用接口获取动作顺序; # 静默模式传参:空。 # @type ValidateData: String # @param Optional: 额外配置,传入JSON字符串。 # { # "BestFrameNum": 2 //需要返回多张最佳截图,取值范围1-10 # } # @type Optional: String attr_accessor :IdCard, :Name, :VideoBase64, :LivenessType, :ValidateData, :Optional def initialize(idcard=nil, name=nil, videobase64=nil, livenesstype=nil, validatedata=nil, optional=nil) @IdCard = idcard @Name = name @VideoBase64 = videobase64 @LivenessType = livenesstype @ValidateData = validatedata @Optional = optional end def deserialize(params) @IdCard = params['IdCard'] @Name = params['Name'] @VideoBase64 = params['VideoBase64'] @LivenessType = params['LivenessType'] @ValidateData = params['ValidateData'] @Optional = params['Optional'] end end # LivenessRecognition返回参数结构体 class LivenessRecognitionResponse < TencentCloud::Common::AbstractModel # @param BestFrameBase64: 验证通过后的视频最佳截图照片,照片为BASE64编码后的值,jpg格式。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type BestFrameBase64: String # @param Sim: 相似度,取值范围 [0.00, 100.00]。推荐相似度大于等于70时可判断为同一人,可根据具体场景自行调整阈值(阈值70的误通过率为千分之一,阈值80的误通过率是万分之一) # @type Sim: Float # @param Result: 业务错误码,成功情况返回Success, 错误情况请参考下方错误码 列表中FailedOperation部分 # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param BestFrameList: 最佳截图列表,仅在配置了返回多张最佳截图时返回。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type BestFrameList: Array # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :BestFrameBase64, :Sim, :Result, :Description, :BestFrameList, :RequestId def initialize(bestframebase64=nil, sim=nil, result=nil, description=nil, bestframelist=nil, requestid=nil) @BestFrameBase64 = bestframebase64 @Sim = sim @Result = result @Description = description @BestFrameList = bestframelist @RequestId = requestid end def deserialize(params) @BestFrameBase64 = params['BestFrameBase64'] @Sim = params['Sim'] @Result = params['Result'] @Description = params['Description'] @BestFrameList = params['BestFrameList'] @RequestId = params['RequestId'] end end # Liveness请求参数结构体 class LivenessRequest < TencentCloud::Common::AbstractModel # @param VideoBase64: 用于活体检测的视频,视频的BASE64值; # BASE64编码后的大小不超过8M,支持mp4、avi、flv格式。 # @type VideoBase64: String # @param LivenessType: 活体检测类型,取值:LIP/ACTION/SILENT。 # LIP为数字模式,ACTION为动作模式,SILENT为静默模式,三种模式选择一种传入。 # @type LivenessType: String # @param ValidateData: 数字模式传参:数字验证码(1234),需先调用接口获取数字验证码; # 动作模式传参:传动作顺序(2,1 or 1,2),需先调用接口获取动作顺序; # 静默模式传参:不需要传递此参数。 # @type ValidateData: String # @param Optional: 额外配置,传入JSON字符串。 # { # "BestFrameNum": 2 //需要返回多张最佳截图,取值范围1-10 # } # @type Optional: String attr_accessor :VideoBase64, :LivenessType, :ValidateData, :Optional def initialize(videobase64=nil, livenesstype=nil, validatedata=nil, optional=nil) @VideoBase64 = videobase64 @LivenessType = livenesstype @ValidateData = validatedata @Optional = optional end def deserialize(params) @VideoBase64 = params['VideoBase64'] @LivenessType = params['LivenessType'] @ValidateData = params['ValidateData'] @Optional = params['Optional'] end end # Liveness返回参数结构体 class LivenessResponse < TencentCloud::Common::AbstractModel # @param BestFrameBase64: 验证通过后的视频最佳截图照片,照片为BASE64编码后的值,jpg格式。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type BestFrameBase64: String # @param Result: 业务错误码,成功情况返回Success, 错误情况请参考下方错误码 列表中FailedOperation部分 # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param BestFrameList: 最佳最佳截图列表,仅在配置了返回多张最佳截图时有效。 # 注意:此字段可能返回 null,表示取不到有效值。 # @type BestFrameList: Array # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :BestFrameBase64, :Result, :Description, :BestFrameList, :RequestId def initialize(bestframebase64=nil, result=nil, description=nil, bestframelist=nil, requestid=nil) @BestFrameBase64 = bestframebase64 @Result = result @Description = description @BestFrameList = bestframelist @RequestId = requestid end def deserialize(params) @BestFrameBase64 = params['BestFrameBase64'] @Result = params['Result'] @Description = params['Description'] @BestFrameList = params['BestFrameList'] @RequestId = params['RequestId'] end end # MinorsVerification请求参数结构体 class MinorsVerificationRequest < TencentCloud::Common::AbstractModel # @param Type: 参与校验的参数类型。 # 0:使用手机号进行校验; # 1:使用姓名与身份证号进行校验。 # @type Type: String # @param Mobile: 手机号,11位数字, # 特别提示: # 手机号验证只限制在腾讯健康守护可信模型覆盖的数据范围内,与手机号本身在运营商是否实名无关联,不在范围会提示“手机号未实名”,建议客户与传入姓名和身份证号信息组合使用。 # @type Mobile: String # @param IdCard: 身份证号码。 # @type IdCard: String # @param Name: 姓名。 # @type Name: String # @param Encryption: 敏感数据加密信息。对传入信息(姓名、身份证号、手机号)有加密需求的用户可使用此参数,详情请点击左侧链接。 # @type Encryption: :class:`Tencentcloud::Faceid.v20180301.models.Encryption` attr_accessor :Type, :Mobile, :IdCard, :Name, :Encryption def initialize(type=nil, mobile=nil, idcard=nil, name=nil, encryption=nil) @Type = type @Mobile = mobile @IdCard = idcard @Name = name @Encryption = encryption end def deserialize(params) @Type = params['Type'] @Mobile = params['Mobile'] @IdCard = params['IdCard'] @Name = params['Name'] unless params['Encryption'].nil? @Encryption = Encryption.new.deserialize(params['Encryption']) end end end # MinorsVerification返回参数结构体 class MinorsVerificationResponse < TencentCloud::Common::AbstractModel # @param Result: 结果码,收费情况如下。 # 收费结果码: # 0: 成年 # -1: 未成年 # -3: 姓名和身份证号不一致 # 不收费结果码: # -2: 未查询到手机号信息 # -4: 非法身份证号(长度、校验位等不正确) # -5: 非法姓名(长度、格式等不正确) # -6: 权威数据源服务异常 # -7: 未查询到身份信息 # -8: 权威数据源升级中,请稍后再试 # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param AgeRange: 该字段的值为年龄区间。格式为[a,b), # [0,8)表示年龄小于8周岁区间,不包括8岁; # [8,16)表示年龄8-16周岁区间,不包括16岁; # [16,18)表示年龄16-18周岁区间,不包括18岁; # [18,+)表示年龄大于18周岁。 # @type AgeRange: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Result, :Description, :AgeRange, :RequestId def initialize(result=nil, description=nil, agerange=nil, requestid=nil) @Result = result @Description = description @AgeRange = agerange @RequestId = requestid end def deserialize(params) @Result = params['Result'] @Description = params['Description'] @AgeRange = params['AgeRange'] @RequestId = params['RequestId'] end end # MobileNetworkTimeVerification请求参数结构体 class MobileNetworkTimeVerificationRequest < TencentCloud::Common::AbstractModel # @param Mobile: 手机号码 # @type Mobile: String # @param Encryption: 敏感数据加密信息。对传入信息(手机号)有加密需求的用户可使用此参数,详情请点击左侧链接。 # @type Encryption: :class:`Tencentcloud::Faceid.v20180301.models.Encryption` attr_accessor :Mobile, :Encryption def initialize(mobile=nil, encryption=nil) @Mobile = mobile @Encryption = encryption end def deserialize(params) @Mobile = params['Mobile'] unless params['Encryption'].nil? @Encryption = Encryption.new.deserialize(params['Encryption']) end end end # MobileNetworkTimeVerification返回参数结构体 class MobileNetworkTimeVerificationResponse < TencentCloud::Common::AbstractModel # @param Result: 认证结果码,收费情况如下。 # 收费结果码: # 0: 成功 # -2: 手机号不存在 # -3: 手机号存在,但无法查询到在网时长 # 不收费结果码: # -1: 手机号格式不正确 # -4: 验证中心服务繁忙 # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param Range: 在网时长区间。 # 格式为(a,b],表示在网时长在a个月以上,b个月以下。若b为+时表示没有上限。 # @type Range: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Result, :Description, :Range, :RequestId def initialize(result=nil, description=nil, range=nil, requestid=nil) @Result = result @Description = description @Range = range @RequestId = requestid end def deserialize(params) @Result = params['Result'] @Description = params['Description'] @Range = params['Range'] @RequestId = params['RequestId'] end end # MobileStatus请求参数结构体 class MobileStatusRequest < TencentCloud::Common::AbstractModel # @param Mobile: 手机号码 # @type Mobile: String # @param Encryption: 敏感数据加密信息。对传入信息(手机号)有加密需求的用户可使用此参数,详情请点击左侧链接。 # @type Encryption: :class:`Tencentcloud::Faceid.v20180301.models.Encryption` attr_accessor :Mobile, :Encryption def initialize(mobile=nil, encryption=nil) @Mobile = mobile @Encryption = encryption end def deserialize(params) @Mobile = params['Mobile'] unless params['Encryption'].nil? @Encryption = Encryption.new.deserialize(params['Encryption']) end end end # MobileStatus返回参数结构体 class MobileStatusResponse < TencentCloud::Common::AbstractModel # @param Result: 认证结果码,收费情况如下。 # 收费结果码: # 0:成功 # 不收费结果码: # -1:未查询到结果 # -2:手机号格式不正确 # -3:验证中心服务繁忙 # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param StatusCode: 状态码: # 0:正常 # 1:停机 # 2:销号 # 3:空号 # 4:不在网 # 99:未知状态 # @type StatusCode: Integer # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Result, :Description, :StatusCode, :RequestId def initialize(result=nil, description=nil, statuscode=nil, requestid=nil) @Result = result @Description = description @StatusCode = statuscode @RequestId = requestid end def deserialize(params) @Result = params['Result'] @Description = params['Description'] @StatusCode = params['StatusCode'] @RequestId = params['RequestId'] end end # PhoneVerification请求参数结构体 class PhoneVerificationRequest < TencentCloud::Common::AbstractModel # @param IdCard: 身份证号 # @type IdCard: String # @param Name: 姓名 # @type Name: String # @param Phone: 手机号 # @type Phone: String # @param CiphertextBlob: 有加密需求的用户,接入传入kms的CiphertextBlob,关于数据加密可查阅 <a href="https://cloud.tencent.com/document/product/1007/47180">数据加密</a> 文档。 # @type CiphertextBlob: String # @param EncryptList: 在使用加密服务时,填入要被加密的字段。本接口中可填入加密后的IdCard,Name,Phone中的一个或多个 # @type EncryptList: Array # @param Iv: 有加密需求的用户,传入CBC加密的初试向量 # @type Iv: String attr_accessor :IdCard, :Name, :Phone, :CiphertextBlob, :EncryptList, :Iv def initialize(idcard=nil, name=nil, phone=nil, ciphertextblob=nil, encryptlist=nil, iv=nil) @IdCard = idcard @Name = name @Phone = phone @CiphertextBlob = ciphertextblob @EncryptList = encryptlist @Iv = iv end def deserialize(params) @IdCard = params['IdCard'] @Name = params['Name'] @Phone = params['Phone'] @CiphertextBlob = params['CiphertextBlob'] @EncryptList = params['EncryptList'] @Iv = params['Iv'] end end # PhoneVerification返回参数结构体 class PhoneVerificationResponse < TencentCloud::Common::AbstractModel # @param Result: 认证结果码: # 收费结果码 # 0: 认证通过 # -4: 信息不一致(手机号已实名,但姓名和身份证号与实名信息不一致) # -5: 手机号未实名 # 不收费结果码 # -6: 手机号码不合法 # -7: 身份证号码有误 # -8: 姓名校验不通过 # -9: 没有记录 # -10: 认证未通过 # -11: 验证中心服务繁忙 # @type Result: String # @param Description: 业务结果描述。 # @type Description: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Result, :Description, :RequestId def initialize(result=nil, description=nil, requestid=nil) @Result = result @Description = description @RequestId = requestid end def deserialize(params) @Result = params['Result'] @Description = params['Description'] @RequestId = params['RequestId'] end end end end end
34.757789
343
0.590661
bb4bb8e8ae544b1fac3cfbc1d3073d6fed993897
163
Factory.define :user do |f| f.name { 'Mr XY' } f.sequence(:email) { |n| "mrxy#{n}@example.com" } f.password "secret" f.confirmed_at { Time.zone.now } end
20.375
51
0.619632
bb0789d0c41d0ae3c3a7c75c7a226a82a02e7617
1,787
# frozen_string_literal: true require "spec_helper" describe "Get alliance information" do context "when etag not set" do let(:options) { {alliance_id: 99_005_443} } before { VCR.insert_cassette "esi/alliances/99005443" } after { VCR.eject_cassette } subject { EveOnline::ESI::Alliance.new(options) } specify { expect(subject.not_modified?).to eq(false) } specify { expect(subject.scope).to eq(nil) } specify do expect(subject.as_json).to eq(name: "Kids With Guns Alliance", creator_id: 94_195_096, creator_corporation_id: 98_306_624, ticker: "-KWG-", date_founded: "2015-05-03T19:45:17Z", executor_corporation_id: 98_306_624, faction_id: nil) end specify { expect(subject.etag).to eq("6780e53a01c7d9715b5f445126c4f2c137da4be79e4debe541ce3ab2") } specify { expect(subject.error_limit_remain).to eq(100) } specify { expect(subject.error_limit_reset).to eq(29) } end context "when etag is set" do let(:options) do { alliance_id: 99_005_443, etag: "6780e53a01c7d9715b5f445126c4f2c137da4be79e4debe541ce3ab2" } end before { VCR.insert_cassette "esi/alliances/99005443_with_etag" } after { VCR.eject_cassette } subject { EveOnline::ESI::Alliance.new(options) } specify { expect(subject.not_modified?).to eq(true) } specify { expect(subject.etag).to eq("6780e53a01c7d9715b5f445126c4f2c137da4be79e4debe541ce3ab2") } specify { expect(subject.error_limit_remain).to eq(100) } specify { expect(subject.error_limit_reset).to eq(28) } end end
30.288136
102
0.628987
e8955ac734bed28d6b0c05f952d0943ff763cdf3
1,417
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE require 'aws-sdk-core' require 'aws-sigv4' require_relative 'aws-sdk-imagebuilder/types' require_relative 'aws-sdk-imagebuilder/client_api' require_relative 'aws-sdk-imagebuilder/client' require_relative 'aws-sdk-imagebuilder/errors' require_relative 'aws-sdk-imagebuilder/resource' require_relative 'aws-sdk-imagebuilder/customizations' # This module provides support for EC2 Image Builder. This module is available in the # `aws-sdk-imagebuilder` gem. # # # Client # # The {Client} class provides one method for each API operation. Operation # methods each accept a hash of request parameters and return a response # structure. # # imagebuilder = Aws::Imagebuilder::Client.new # resp = imagebuilder.cancel_image_creation(params) # # See {Client} for more information. # # # Errors # # Errors returned from EC2 Image Builder are defined in the # {Errors} module and all extend {Errors::ServiceError}. # # begin # # do stuff # rescue Aws::Imagebuilder::Errors::ServiceError # # rescues all EC2 Image Builder API errors # end # # See {Errors} for more information. # # @!group service module Aws::Imagebuilder GEM_VERSION = '1.21.0' end
26.240741
85
0.750882
39ce8db386913350a8fccc5aafb20b99ac80efba
13,480
require 'spec_helper' # examples at https://github.com/sethvargo/chefspec/tree/master/examples describe 'apache2::default' do before do allow(::File).to receive(:symlink?).and_return(false) end # Test all defaults on all platforms supported_platforms.each do |platform, versions| versions.each do |version| context "on #{platform.capitalize} #{version}" do property = load_platform_properties(:platform => platform, :platform_version => version) let(:chef_run) do @chef_run end context 'with valid apache configuration' do before(:context) do @chef_run = ChefSpec::SoloRunner.new(:platform => platform, :version => version) stub_command("#{property[:apache][:binary]} -t").and_return(true) @chef_run.converge(described_recipe) end it "installs package #{property[:apache][:package]}" do case platform when 'freebsd' expect(chef_run).to install_freebsd_package(property[:apache][:package]) when 'amazon', 'fedora', 'redhat', 'centos' expect(chef_run).to install_yum_package(property[:apache][:package]) else expect(chef_run).to install_package(property[:apache][:package]) end end it "creates #{property[:apache][:log_dir]} directory" do expect(chef_run).to create_directory(property[:apache][:log_dir]).with( :mode => '0755' ) expect(chef_run).to_not create_directory(property[:apache][:log_dir]).with( :mode => '0777' ) end it "deletes #{property[:apache][:dir]}/conf.d" do expect(chef_run).to delete_directory("#{property[:apache][:dir]}/conf.d").with(:recursive => true) expect(chef_run).to_not delete_file("#{property[:apache][:dir]}/conf.d").with(:recursive => false) end %w(sites-available sites-enabled mods-available mods-enabled conf-enabled conf-available).each do |dir| it "creates #{property[:apache][:dir]}/#{dir} directory" do expect(chef_run).to create_directory("#{property[:apache][:dir]}/#{dir}").with( :mode => '0755', :owner => 'root', :group => property[:apache][:root_group] ) expect(chef_run).to_not create_directory("#{property[:apache][:dir]}/#{dir}").with( :mode => '0777' ) end end it "installs package #{property[:apache][:perl_pkg]}" do expect(chef_run).to install_package(property[:apache][:perl_pkg]) end %w(a2ensite a2dissite a2enmod a2dismod a2enconf a2disconf).each do |modscript| it "creates /usr/sbin/#{modscript}" do expect(chef_run).to create_template("/usr/sbin/#{modscript}") end end if %w(amazon redhat centos fedora arch suse freebsd).include?(platform) it 'creates /usr/local/bin/apache2_module_conf_generate.pl' do expect(chef_run).to create_cookbook_file('/usr/local/bin/apache2_module_conf_generate.pl').with( :mode => '0755', :owner => 'root', :group => property[:apache][:root_group] ) expect(chef_run).to_not create_cookbook_file('/usr/bin/apache2_module_conf_generate.pl') end it 'runs a execute[generate-module-list] with :nothing action' do # .with( # command: "/usr/local/bin/apache2_module_conf_generate.pl #{property[:apache][:lib_dir]} #{property[:apache][:dir]}/mods-available" # ) execute = chef_run.execute('generate-module-list') expect(execute).to do_nothing end it 'includes the `apache2::mod_deflate` recipe' do expect(chef_run).to include_recipe('apache2::mod_deflate') end end it "creates #{property[:apache][:conf]}" do expect(chef_run).to create_template(property[:apache][:conf]).with( :source => 'apache2.conf.erb', :owner => 'root', :group => property[:apache][:root_group], :mode => '0644' ) end subject(:apacheconf) { chef_run.template(property[:apache][:conf]) } it "notification is triggered by #{property[:apache][:conf]} template to reload service[apache2]" do expect(apacheconf).to notify('service[apache2]').to(:reload).delayed expect(apacheconf).to_not notify('service[apache2]').to(:reload).immediately end if %w(debian ubuntu).include?(platform) it "creates #{property[:apache][:dir]}/envvars" do expect(chef_run).to create_template("#{property[:apache][:dir]}/envvars").with( :source => 'envvars.erb', :owner => 'root', :group => property[:apache][:root_group], :mode => '0644' ) end subject(:envvars) { chef_run.template("#{property[:apache][:dir]}/envvars") } it "notification is triggered by #{property[:apache][:dir]}/envvars template to reload service[apache2]" do expect(envvars).to notify('service[apache2]').to(:reload).delayed expect(envvars).to_not notify('service[apache2]').to(:reload).immediately end else it "does not create #{property[:apache][:dir]}/envvars" do expect(chef_run).to_not create_template("#{property[:apache][:dir]}/envvars").with( :source => 'envvars.erb', :owner => 'root', :group => property[:apache][:root_group], :mode => '0644' ) end end %w(security charset).each do |config| it "deletes #{property[:apache][:dir]}/conf-available/#{config}" do expect(chef_run).to delete_file("#{property[:apache][:dir]}/conf-available/#{config}") end it "creates #{property[:apache][:dir]}/conf-available/#{config}.conf" do expect(chef_run).to create_template("#{property[:apache][:dir]}/conf-available/#{config}.conf").with( :source => "#{config}.conf.erb", :owner => 'root', :group => property[:apache][:root_group], :mode => '0644', :backup => false ) end it " runs a2enconf #{config}.conf" do stub_command("/usr/sbin/a2enconf #{config}.conf").and_return(false) expect(chef_run).to run_execute("/usr/sbin/a2enconf #{config}.conf") end subject(:confd) { chef_run.template("#{property[:apache][:dir]}/conf-available/#{config}.conf") } it "notification is triggered by #{property[:apache][:dir]}/conf-available/#{config}.conf template to reload service[apache2]" do expect(confd).to notify('service[apache2]').to(:reload).delayed expect(confd).to_not notify('service[apache2]').to(:reload).immediately end end it "deletes #{property[:apache][:dir]}/ports" do expect(chef_run).to delete_file("#{property[:apache][:dir]}/ports") end it "creates #{property[:apache][:dir]}/ports.conf" do expect(chef_run).to create_template("#{property[:apache][:dir]}/ports.conf").with( :source => 'ports.conf.erb', :owner => 'root', :group => property[:apache][:root_group], :mode => '0644' ) end subject(:portsconf) { chef_run.template("#{property[:apache][:dir]}/ports.conf") } it "notification is triggered by #{property[:apache][:dir]}/ports.conf template to reload service[apache2]" do expect(portsconf).to notify('service[apache2]').to(:reload).delayed expect(portsconf).to_not notify('service[apache2]').to(:reload).immediately end it "does not create #{property[:apache][:dir]}/sites-available/#{property[:apache][:default_site_name]}.conf" do expect(chef_run).to_not create_template("#{property[:apache][:dir]}/sites-available/#{property[:apache][:default_site_name]}.conf") end if %w(amazon redhat centos fedora suse opensuse).include?(platform) it "creates /etc/sysconfig/#{property[:apache][:package]}" do expect(chef_run).to create_template("/etc/sysconfig/#{property[:apache][:package]}").with( :source => 'etc-sysconfig-httpd.erb', :owner => 'root', :group => property[:apache][:root_group], :mode => '0644' ) expect(chef_run).to render_file("/etc/sysconfig/#{property[:apache][:package]}").with_content( /HTTPD=#{property[:apache][:binary]}/ ) end subject(:sysconfig) { chef_run.template("/etc/sysconfig/#{property[:apache][:package]}") } it "notification is triggered by /etc/sysconfig/#{property[:apache][:package]} template to restart service[apache2]" do expect(sysconfig).to notify('service[apache2]').to(:restart).delayed expect(sysconfig).to_not notify('service[apache2]').to(:restart).immediately end else it "does not create /etc/sysconfig/#{property[:apache][:package]}" do expect(chef_run).to_not create_template("/etc/sysconfig/#{property[:apache][:package]}").with( :source => 'etc-sysconfig-httpd.erb', :owner => 'root', :group => property[:apache][:root_group], :mode => '0644' ) expect(chef_run).to_not render_file("/etc/sysconfig/#{property[:apache][:package]}").with_content( /#HTTPD_LANG=C/ ) end end if platform == 'freebsd' it "deletes #{property[:apache][:dir]}/Includes" do expect(chef_run).to delete_directory("#{property[:apache][:dir]}/Includes") end it "deletes #{property[:apache][:dir]}/extra" do expect(chef_run).to delete_directory("#{property[:apache][:dir]}/extra") end end %W( #{property[:apache][:dir]}/ssl #{property[:apache][:cache_dir]} ).each do |path| it "creates #{path} directory" do expect(chef_run).to create_directory(path).with( :mode => '0755', :owner => 'root', :group => property[:apache][:root_group] ) end end property[:apache][:default_modules].each do |mod| module_recipe_name = mod =~ /^mod_/ ? mod : "mod_#{mod}" it "includes the `apache2::#{module_recipe_name}` recipe" do expect(chef_run).to include_recipe("apache2::#{module_recipe_name}") end end it "deletes #{property[:apache][:dir]}/sites-available/default" do expect(chef_run).to delete_file("#{property[:apache][:dir]}/sites-available/default") end it "deletes #{property[:apache][:dir]}/sites-available/default.conf" do expect(chef_run).to delete_file("#{property[:apache][:dir]}/sites-available/default.conf") end it "deletes #{property[:apache][:dir]}/sites-enabled/000-default" do expect(chef_run).to delete_link("#{property[:apache][:dir]}/sites-enabled/000-default") end it "deletes #{property[:apache][:dir]}/sites-enabled/000-default.conf" do expect(chef_run).to delete_link("#{property[:apache][:dir]}/sites-enabled/000-default.conf") end it 'enables and starts the apache2 service' do expect(chef_run).to enable_service('apache2').with( :service_name => property[:apache][:service_name], :restart_command => property[:apache][:service_restart_command], :reload_command => property[:apache][:service_reload_command], :supports => { :start => true, :restart => true, :reload => true, :status => true }, :action => [:enable, :start] ) end end context 'with invalid apache configuration' do before(:context) do @chef_run = ChefSpec::SoloRunner.new(:platform => platform, :version => version) stub_command("#{property[:apache][:binary]} -t").and_return(false) @chef_run.converge(described_recipe) end it 'does not enable/start apache2 service' do expect(chef_run).to_not enable_service('apache2').with( :service_name => property[:apache][:service_name], :restart_command => property[:apache][:service_restart_command], :reload_command => property[:apache][:service_reload_command], :supports => { :start => true, :restart => true, :reload => true, :status => true }, :action => [:enable, :start] ) end end end end end end
44.784053
147
0.560905
1d8c492b5eee0f0f9c7a53a3d1efdaaa72f25644
3,593
# frozen_string_literal: true RSpec.describe GraphQL::DSL::Formatter do let(:formatter) { described_class.new } context '#format_value' do def format_value(value, is_const: false) formatter.send(:format_value, value, is_const) end context 'integer value' do it { expect(format_value(42)).to eq('42') } it { expect(format_value(0)).to eq('0') } it { expect(format_value(-42)).to eq('-42') } end context 'float value' do it { expect(format_value(42.42)).to eq('42.42') } it { expect(format_value(0.0)).to eq('0.0') } it { expect(format_value(-42.42)).to eq('-42.42') } end context 'string value' do it { expect(format_value('')).to eq('""') } it { expect(format_value('string')).to eq('"string"') } it { expect(format_value('"')).to eq('"\""') } it { expect(format_value("'")).to eq('"\'"') } it { expect(format_value('/')).to eq('"/"') } it { expect(format_value("\u2014")).to eq('"\u2014"') } it { expect(format_value('"')).to eq('"\\""') } it { expect(format_value('\\')).to eq('"\\\\"') } it { expect(format_value("\b")).to eq('"\b"') } it { expect(format_value("\f")).to eq('"\f"') } it { expect(format_value("\n")).to eq('"\n"') } it { expect(format_value("\r")).to eq('"\r"') } it { expect(format_value("\t")).to eq('"\t"') } end context 'boolean value' do it { expect(format_value(true)).to eq('true') } it { expect(format_value(false)).to eq('false') } end context 'null value' do it { expect(format_value(nil)).to eq('null') } end context 'variable value' do it { expect(format_value(:$variable)).to eq('$variable') } it do expect { format_value(:$variable, is_const: true) }.to raise_error GraphQL::DSL::Error, /Value must be constant/ end end context 'enum value' do it { expect(format_value(:Type1)).to eq('Type1') } end context 'list value' do it { expect(format_value([])).to eq('[]') } it { expect(format_value([1])).to eq('[1]') } it { expect(format_value([1, 2])).to eq('[1, 2]') } it { expect(format_value([1.1])).to eq('[1.1]') } it { expect(format_value(['string'])).to eq('["string"]') } it { expect(format_value([true])).to eq('[true]') } it { expect(format_value([false])).to eq('[false]') } it { expect(format_value([nil])).to eq('[null]') } it { expect(format_value([:Type1])).to eq('[Type1]') } it { expect(format_value([[1]])).to eq('[[1]]') } it { expect(format_value([{ a: 1 }])).to eq('[{a: 1}]') } end context 'object value' do it { expect(format_value({})).to eq('{}') } it { expect(format_value({ a: 1 })).to eq('{a: 1}') } it { expect(format_value({ a: 1, b: 2 })).to eq('{a: 1, b: 2}') } it { expect(format_value({ a: 1.1 })).to eq('{a: 1.1}') } it { expect(format_value({ a: 'string' })).to eq('{a: "string"}') } it { expect(format_value({ a: true })).to eq('{a: true}') } it { expect(format_value({ a: false })).to eq('{a: false}') } it { expect(format_value({ a: nil })).to eq('{a: null}') } it { expect(format_value({ a: :Type1 })).to eq('{a: Type1}') } it { expect(format_value({ a: [1] })).to eq('{a: [1]}') } it { expect(format_value({ a: { b: 2 } })).to eq('{a: {b: 2}}') } end context 'unknown value' do it { expect { format_value(Object.new) }.to raise_error GraphQL::DSL::Error, /Unsupported value type/ } end end end
36.292929
109
0.543279
1da851bc70be4ec7d17c620073be5427b26a369c
1,214
#! /usr/local/bin/ruby -w require 'RMagick' imgl = Magick::ImageList.new imgl.new_image(400, 300, Magick::HatchFill.new('white','lightcyan2')) gc = Magick::Draw.new # Draw Bezier curve gc.stroke('red') gc.stroke_width(2) gc.fill_opacity(0) gc.bezier(50,150, 50,50, 200,50, 200,150, 200,250, 350,250, 350,150) # Draw filled circles for the control points gc.fill('gray50') gc.stroke('gray50') gc.fill_opacity(1) gc.circle(50,50, 53,53) gc.circle(200,50, 203,53) gc.circle(200,250, 203,253) gc.circle(350,250, 353,253) # Draw circles on the points the curve passes through gc.fill_opacity(0) gc.circle(50,150, 53,153) gc.circle(200,150, 203,153) gc.circle(350,150, 353,153) # Draw the gray lines between points and control points gc.line(50,50, 50,150) gc.line(200,50, 200,250) gc.line(350,150, 350,250) # Annotate gc.font_weight(Magick::NormalWeight) gc.font_style(Magick::NormalStyle) gc.fill('black') gc.stroke('transparent') gc.text(30,170, "'50,150'") gc.text(30, 40, "'50,50'") gc.text(180,40, "'200,50'") gc.text(210,155,"'200,150'") gc.text(180,270,"'200,250'") gc.text(330,270,"'350,250'") gc.text(330,140,"'350,150'") gc.draw(imgl) imgl.border!(1,1, 'lightcyan2') imgl.write("cbezier6.gif") exit
22.481481
69
0.704283
e9111f5bcc187083a541a0dbe32b0bea5c2b195c
5,804
require 'spec_helper' require 'tempfile' module Seahorse module Client describe Request do let(:handlers) { HandlerList.new } let(:context) { RequestContext.new } let(:request) { Request.new(handlers, context) } it 'is a HandlerBuilder' do expect(request).to be_kind_of(HandlerBuilder) end describe '#handlers' do it 'returns the handler list' do handlers = HandlerList.new request = Request.new(handlers, context) expect(request.handlers).to be(handlers) end end describe '#context' do it 'returns the request context given the constructor' do context = RequestContext.new request = Request.new(handlers, context) expect(request.context).to be(context) end end describe '#send_request' do it 'contructs a stack from the handler list' do expect(handlers).to receive(:to_stack).and_return(->(context) {}) request.send_request end it 'returns the response from the handler stack #call method' do response = double('response') allow(handlers).to receive(:to_stack).and_return(->(_) { response }) expect(request.send_request).to be(response) end it 'passes the request context to the handler stack' do passed = nil allow(handlers).to receive(:to_stack). and_return(->(context) { passed = context }) request.send_request expect(passed).to be(context) end it 'returns the response from the handler stack' do resp = Response.new allow(handlers).to receive(:to_stack).and_return(->(context) { resp }) expect(Request.new(handlers, context).send_request).to be(resp) end end describe '#send_request with a target' do let(:handler) do Proc.new do context.http_response.signal_headers(200, {}) context.http_response.signal_data('part1') context.http_response.signal_data('part2') context.http_response.signal_data('part3') context.http_response.signal_done Response.new(context: context) end end before(:each) do handlers.add(Plugins::ResponseTarget::Handler, step: :initialize) handlers.add(double('send-handler-class', new: handler)) end describe 'String target' do it 'writes to the file named' do tmpfile = Tempfile.new('tempfile') tmpfile.close request.send_request(target: tmpfile.path) expect(File.read(tmpfile.path)).to eq("part1part2part3") end it 'closes the file before returning the response' do tmpfile = Tempfile.new('tempfile') tmpfile.close resp = request.send_request(target: tmpfile.path) expect(resp.context.http_response.body).to be_closed end end describe 'Pathname target' do it 'writes to the file named' do tmpfile = Tempfile.new('tempfile') tmpfile.close request.send_request(target: Pathname.new(tmpfile.path)) expect(File.read(tmpfile.path)).to eq("part1part2part3") end it 'closes the file before returning the response' do tmpfile = Tempfile.new('tempfile') tmpfile.close resp = request.send_request(target: Pathname.new(tmpfile.path)) expect(resp.context.http_response.body).to be_closed end end describe 'IO object target' do it 'writes to the given object' do buffer = StringIO.new('') request.send_request(target: buffer) expect(buffer.string).to eq("part1part2part3") end end describe 'target from params' do it 'writes the response to the optional :response_target param' do tempfile = Tempfile.new('response-target') tempfile.close context.params[:response_target] = tempfile.path request.send_request expect(File.read(tempfile.path)).to eq('part1part2part3') end end describe 'Block target' do it 'streams data from the handler to the #send_request block' do data = [] request.send_request { |chunk| data << chunk } expect(data).to eq(['part1', 'part2', 'part3']) end it 'counts the bytes yielded' do resp = request.send_request { |chunk| } expect(resp.context.http_response.body.size).to eq(15) end it 'does not buffer the response chunks' do response = request.send_request { |chunk| } body = response.context.http_response.body expect(body.read).to eq('') expect(body).not_to respond_to(:truncate) end describe '2xx responses, not 200' do let(:handler) do Proc.new do context.http_response.signal_headers(206, {}) context.http_response.signal_data('part1') context.http_response.signal_data('part2') context.http_response.signal_data('part3') context.http_response.signal_done Response.new(context: context) end end it 'streams data from the handler to the #send_request block' do data = [] request.send_request { |chunk| data << chunk } expect(data).to eq(['part1', 'part2', 'part3']) end end end end end end end
30.87234
80
0.581496
87473f955edcf96a11c486f3588ec52655b3789e
272
require_relative './app' require 'test/unit' require 'rack/test' set :environment, :test class MyAppTest < Test::Unit::TestCase include Rack::Test::Methods def app Sinatra::Application end def test_get_request get '/' assert last_response.ok? end
16
38
0.705882
bf0415200935fd24b5dd815a65c00559d3fc8e31
274
class Users < ActiveRecord::Migration def change create_table :users do |t| t.string :username t.string :email t.string :password_digest t.datetime "created_at", null: false t.datetime "updated_at", null: false end end end
24.909091
47
0.635036
08aca7380fdc5fa41b1ef9ca54535bf98ae40f3c
6,445
class Httpd < Formula desc "Apache HTTP server" homepage "https://httpd.apache.org/" url "https://www.apache.org/dyn/closer.lua?path=httpd/httpd-2.4.46.tar.bz2" mirror "https://archive.apache.org/dist/httpd/httpd-2.4.46.tar.bz2" sha256 "740eddf6e1c641992b22359cabc66e6325868c3c5e2e3f98faf349b61ecf41ea" license "Apache-2.0" livecheck do url :stable end bottle do sha256 "8c6b348427bd5c43d784dd5ae6261304e4218607cace3f264e016819c3118527" => :catalina sha256 "e561f825dc044083a10d85d0faa4f785d95466e827d20264702078c58fd900ac" => :mojave sha256 "aede7239a3d25119c493644cac072fc953f3b1d5a4c490558781ad9ac5000504" => :high_sierra end depends_on "apr" depends_on "apr-util" depends_on "brotli" depends_on "nghttp2" depends_on "[email protected]" depends_on "pcre" uses_from_macos "zlib" def install # fixup prefix references in favour of opt_prefix references inreplace "Makefile.in", '#@@ServerRoot@@#$(prefix)#', '#@@ServerRoot@@'"##{opt_prefix}#" inreplace "docs/conf/extra/httpd-autoindex.conf.in", "@exp_iconsdir@", "#{opt_pkgshare}/icons" inreplace "docs/conf/extra/httpd-multilang-errordoc.conf.in", "@exp_errordir@", "#{opt_pkgshare}/error" # fix default user/group when running as root inreplace "docs/conf/httpd.conf.in", /(User|Group) daemon/, "\\1 _www" # use Slackware-FHS layout as it's closest to what we want. # these values cannot be passed directly to configure, unfortunately. inreplace "config.layout" do |s| s.gsub! "${datadir}/htdocs", "${datadir}" s.gsub! "${htdocsdir}/manual", "#{pkgshare}/manual" s.gsub! "${datadir}/error", "#{pkgshare}/error" s.gsub! "${datadir}/icons", "#{pkgshare}/icons" end system "./configure", "--enable-layout=Slackware-FHS", "--prefix=#{prefix}", "--sbindir=#{bin}", "--mandir=#{man}", "--sysconfdir=#{etc}/httpd", "--datadir=#{var}/www", "--localstatedir=#{var}", "--enable-mpms-shared=all", "--enable-mods-shared=all", "--enable-authnz-fcgi", "--enable-cgi", "--enable-pie", "--enable-suexec", "--with-suexec-bin=#{opt_bin}/suexec", "--with-suexec-caller=_www", "--with-port=8080", "--with-sslport=8443", "--with-apr=#{Formula["apr"].opt_prefix}", "--with-apr-util=#{Formula["apr-util"].opt_prefix}", "--with-brotli=#{Formula["brotli"].opt_prefix}", "--with-libxml2=#{MacOS.sdk_path_if_needed}/usr", "--with-mpm=prefork", "--with-nghttp2=#{Formula["nghttp2"].opt_prefix}", "--with-ssl=#{Formula["[email protected]"].opt_prefix}", "--with-pcre=#{Formula["pcre"].opt_prefix}", "--with-z=#{MacOS.sdk_path_if_needed}/usr", "--disable-lua", "--disable-luajit" system "make" system "make", "install" # suexec does not install without root bin.install "support/suexec" # remove non-executable files in bin dir (for brew audit) rm bin/"envvars" rm bin/"envvars-std" # avoid using Cellar paths inreplace %W[ #{include}/httpd/ap_config_layout.h #{lib}/httpd/build/config_vars.mk ] do |s| s.gsub! "#{lib}/httpd/modules", "#{HOMEBREW_PREFIX}/lib/httpd/modules" end inreplace %W[ #{bin}/apachectl #{bin}/apxs #{include}/httpd/ap_config_auto.h #{include}/httpd/ap_config_layout.h #{lib}/httpd/build/config_vars.mk #{lib}/httpd/build/config.nice ] do |s| s.gsub! prefix, opt_prefix end inreplace "#{lib}/httpd/build/config_vars.mk" do |s| pcre = Formula["pcre"] s.gsub! pcre.prefix.realpath, pcre.opt_prefix s.gsub! "${prefix}/lib/httpd/modules", "#{HOMEBREW_PREFIX}/lib/httpd/modules" end end def post_install (var/"cache/httpd").mkpath (var/"www").mkpath end def caveats <<~EOS DocumentRoot is #{var}/www. The default ports have been set in #{etc}/httpd/httpd.conf to 8080 and in #{etc}/httpd/extra/httpd-ssl.conf to 8443 so that httpd can run without sudo. EOS end plist_options manual: "apachectl start" def plist <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/httpd</string> <string>-D</string> <string>FOREGROUND</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> EOS end test do # Ensure modules depending on zlib and xml2 have been compiled assert_predicate lib/"httpd/modules/mod_deflate.so", :exist? assert_predicate lib/"httpd/modules/mod_proxy_html.so", :exist? assert_predicate lib/"httpd/modules/mod_xml2enc.so", :exist? begin port = free_port expected_output = "Hello world!" (testpath/"index.html").write expected_output (testpath/"httpd.conf").write <<~EOS Listen #{port} ServerName localhost:#{port} DocumentRoot "#{testpath}" ErrorLog "#{testpath}/httpd-error.log" PidFile "#{testpath}/httpd.pid" LoadModule authz_core_module #{lib}/httpd/modules/mod_authz_core.so LoadModule unixd_module #{lib}/httpd/modules/mod_unixd.so LoadModule dir_module #{lib}/httpd/modules/mod_dir.so LoadModule mpm_prefork_module #{lib}/httpd/modules/mod_mpm_prefork.so EOS pid = fork do exec bin/"httpd", "-X", "-f", "#{testpath}/httpd.conf" end sleep 3 assert_match expected_output, shell_output("curl -s 127.0.0.1:#{port}") ensure Process.kill("TERM", pid) Process.wait(pid) end end end
34.650538
117
0.577502
611b8451282914f2d9fc48aed74204a3681b6bbf
2,031
require "pathname" require "drb/drb" require "akephalos/client" # In ruby-1.8.7 and later, the message for a NameError exception is lazily # evaluated. There are, however, different implementations of this between ruby # and jruby, so we realize these messages when sending over DRb. class NameError::Message # @note This method is called by DRb before sending the error to the remote # connection. # @return [String] the inner message. def _dump to_s end end [ Akephalos::Page, Akephalos::Node, Akephalos::Client::Cookies, Akephalos::Client::Cookies::Cookie ].each { |klass| klass.send(:include, DRbUndumped) } module Akephalos # The ClientManager is shared over DRb with the remote process, and # facilitates communication between the processes. # # @api private class ClientManager include DRbUndumped # @return [Akephalos::Client] a new client instance def self.new_client(options = {}) # Store the client to ensure it isn't prematurely garbage collected. @client = Client.new(options) end # Set the global configuration settings for Akephalos. # # @param [Hash] config the configuration settings # @return [Hash] the configuration def self.configuration=(config) Akephalos.configuration = config end end # Akephalos::Server is used by `akephalos --server` to start a DRb server # serving Akephalos::ClientManager. class Server # Start DRb service for Akephalos::ClientManager. # # @param [String] port attach server to def self.start!(port) abort_on_parent_exit! DRb.start_service("druby://127.0.0.1:#{port}", ClientManager) DRb.thread.join end private # Exit if STDIN is no longer readable, which corresponds to the process # which started the server exiting prematurely. # # @api private def self.abort_on_parent_exit! Thread.new do begin STDIN.read rescue IOError exit end end end end end
25.3875
79
0.687839
28369f79adb20a0e6ac664b0aeb09a30ca18da1d
529
# frozen_string_literal: true require 'rails_helper' RSpec.describe Contract, type: :model do let(:c) { build(:contract) } describe 'ActiveModel validations' do # basic validations %i[agency_id effective_date].each do |attr| it { expect(c).to validate_presence_of(attr) } end it { expect(c).to_not allow_value(nil).for(:agency_id) } it { expect(c).to allow_value(nil).for(:termination_date) } end describe 'ActiveRecord associations' do it { expect(c).to belong_to(:agency) } end end
24.045455
63
0.693762
bba5104888bef8e78380eb7aab3b754ff3dfe1ac
2,778
# Flow.io (2017) # helper class to manage product sync scheduling require 'json' require 'logger' require 'pathname' module FolwApiRefresh extend self SYNC_INTERVAL_IN_MINUTES = 60 unless defined?(SYNC_INTERVAL_IN_MINUTES) # CHECK_FILE = Pathname.new './tmp/last-flow-refresh.txt' unless defined?(CHECK_FILE) LOGGER = Logger.new('./log/sync.log', 3, 1024000) unless defined?(LOGGER) ### def now Time.now.to_i end def settings FlowSettings.fetch 'rake-products-refresh' end def data # CHECK_FILE.exist? ? JSON.parse(CHECK_FILE.read) : {} @data ||= JSON.load(settings.data || '{}') end def duration return '? (unknown)' if !data['start'] || !data['end'] || data['start'] > data['end'] (data['end'] - data['start'])/60 end def write yield data settings.update_attribute :data, data.to_json data end def log message $stdout.puts message LOGGER.info '%s (pid/ppid: %d/%d)' % [message, Process.pid, Process.ppid] end def schedule_refresh! write do |data| data['force_refresh'] = true end end def needs_refresh? data['end'] ||= now - 10_000 # needs refresh if last refresh started more than treshold ago if data['end'] < (now - (60 * SYNC_INTERVAL_IN_MINUTES)) puts 'Last refresh ended long time ago, needs refresh.' return true elsif data['force_refresh'] puts 'Force refresh schecduled, refreshing.' true else puts 'No need for refresh, ended before %d seconds.' % (now - data['end']) false end end # for start just call log_refresh! and end it with true statement def log_refresh! has_ended=false data.delete('force_refresh') write do |data| if has_ended data['start'] ||= now - 60 data['end'] = now data.delete('in_progress') else data['in_progress'] = true data['start'] = now end end end def refresh_info return 'No last sync data' unless data['end'] helper = Class.new helper.extend ActionView::Helpers::DateHelper info = [] info.push 'Sync started %d seconds ago (it is in progress).' % (Time.now.to_i - data['start'].to_i) if data['started'] info.push 'Last sync finished %{finished} ago and lasted for %{duration}. We sync every %{every} minutes.' % { finished: helper.distance_of_time_in_words(Time.now, data['end'].to_i), duration: helper.distance_of_time_in_words(duration), every: SYNC_INTERVAL_IN_MINUTES } info.join(' ') end def sync_products_if_needed return unless needs_refresh? log_refresh! log 'Sync needed, running ...' system 'bundle exec rake flow:sync_localized_items' log_refresh end end
23.948276
122
0.642909
b9bad565d9351cacd850a85304b00b1d51328616
439
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception after_filter :store_return_to def redirect_back_or_default(default=nil) redirect_to(session[:return_to] || default) session.delete(:return_to) end def store_return_to session[:return_to] = request.fullpath end end
25.823529
56
0.765376
edc85e67c708c70ef7d9c0891af4137f409a7bd0
171
class CreateSpreeTireSerials < ActiveRecord::Migration def change create_table :spree_tire_serials do |t| t.string :name t.timestamps end end end
17.1
54
0.707602
613d78958615f308ecb1acce59ef896e14d0585b
477
cask :v1 => 'qldds' do version '1.20' sha256 '684633521706544774c4a0e2f4c87bb5a0e6da01fa4c70c1b2e81bdd93cd770f' url "https://github.com/Marginal/QLdds/releases/download/rel-#{version.delete('.')}/QLdds_#{version.delete('.')}.pkg" appcast 'https://github.com/Marginal/QLdds/releases.atom' name 'QuickLook DDS' homepage 'https://github.com/Marginal/QLdds' license :gpl pkg "QLdds_#{version.delete('.')}.pkg" uninstall :pkgutil => 'uk.org.marginal.qldds' end
31.8
119
0.725367
794d7e7e19328978e30cc958c24d8a36316e151f
2,653
# frozen_string_literal: true require 'spec_helper' RSpec.describe Mutations::Pipelines::RunDastScan do let(:group) { create(:group) } let(:project) { create(:project, :repository, group: group) } let(:user) { create(:user) } let(:project_path) { project.full_path } let(:target_url) { generate(:url) } let(:branch) { project.default_branch } let(:scan_type) { Types::DastScanTypeEnum.enum[:passive] } subject(:mutation) { described_class.new(object: nil, context: { current_user: user }, field: nil) } before do stub_licensed_features(security_on_demand_scans: true) end describe '#resolve' do subject do mutation.resolve( branch: branch, project_path: project_path, target_url: target_url, scan_type: scan_type ) end context 'when on demand scan feature is not enabled' do it 'raises an exception' do expect { subject }.to raise_error(Gitlab::Graphql::Errors::ResourceNotAvailable) end end context 'when on demand scan feature is enabled' do before do stub_feature_flags(security_on_demand_scans_feature_flag: true) end context 'when the project does not exist' do let(:project_path) { SecureRandom.hex } it 'raises an exception' do expect { subject }.to raise_error(Gitlab::Graphql::Errors::ResourceNotAvailable) end end context 'when the user is not associated with the project' do it 'raises an exception' do expect { subject }.to raise_error(Gitlab::Graphql::Errors::ResourceNotAvailable) end end context 'when the user is an owner' do it 'has no errors' do group.add_owner(user) expect(subject[:errors]).to be_empty end end context 'when the user is a maintainer' do it 'has no errors' do project.add_maintainer(user) expect(subject[:errors]).to be_empty end end context 'when the user is a developer' do it 'has no errors' do project.add_developer(user) expect(subject[:errors]).to be_empty end end context 'when the user can run a dast scan' do it 'returns a pipeline_url containing the correct path' do project.add_developer(user) actual_url = subject[:pipeline_url] pipeline = Ci::Pipeline.last expected_url = Rails.application.routes.url_helpers.project_pipeline_url( project, pipeline ) expect(actual_url).to eq(expected_url) end end end end end
27.926316
102
0.636261
f7e0e5cd367c1e10056449a02add75368a38358b
1,238
class Notifier < ApplicationMailer helper :application def contact_message(name,mail,subject,message) @message = message.gsub(/\n/, '<br>') @name = name @email = mail mail(content_type: "text/html", subject: subject, to: CONTACT_US_EMAIL, from: NO_REPLY_EMAIL_ADDRESS) end def user_verification(user, url) @user = user @verification_url = url mail(content_type: "text/html", subject: I18n.t('notifier.user_verification.subject'), to: user.email, from: NO_REPLY_EMAIL_ADDRESS ) end def user_reset_password_verification(user, url) @user = user @reset_password_url = url @username = user.username mail(content_type: "text/html", subject: I18n.t(:subject, :scope => [:notifier, :user_recover_account]), to: user.email, from: NO_REPLY_EMAIL_ADDRESS) end def user_activated(user) @user = user mail(content_type: "text/html", subject: I18n.t('notifier.user_activated.subject'), to: user.email, from: NO_REPLY_EMAIL_ADDRESS) end def user_change_password_notification(user) @user = user mail(content_type: "text/html", subject: I18n.t('notifier.user_change_password.subject'), to: user.email, from: NO_REPLY_EMAIL_ADDRESS) end end
34.388889
154
0.706785
0829bb720245cef1c24b1bc5be4dc244d0ea0f95
148
require 'csv' ruby_version_is "" ... "1.9" do describe "CSV::Reader#initialize" do it "needs to be reviewed for spec completeness" end end
18.5
51
0.689189
616816bcfcec6ca29145f0781ac407b43fb7fdfb
3,670
require 'test_helper' class StandardTest < ActiveSupport::TestCase setup :initialize_resource # Make sure our users have the necessary attributes test "standard should respond to attributes" do assert_respond_to @standard, :slug, "Standard missing slug." assert_respond_to @standard, :name, "Standard missing name." assert_respond_to @standard, :text, "Standard missing text." assert_respond_to @standard, :domain, "Standard missing domain." assert_respond_to @standard, :sub_subject, "Standard missing sub subject." assert_respond_to @standard, :standard_type, "Standard missing standard type" assert_respond_to @standard, :parent_standard, "Standard missing parent standard." assert_respond_to @standard, :children_standards, "Standard missing childrent standards." assert_respond_to @standard, :is_parent_standard, "Standard missing is a parent standard." assert_respond_to @standard, :course_subject, "Standard missing course subject." assert_respond_to @standard, :course_grades, "Standard missing course grades." end # Basic checks for name existence and length test "standard must valid name" do @standard.name = nil assert !(@standard.valid?), "Standard created without name." @standard.name = '' assert !(@standard.valid?), "Standard created with empty name." @standard.name = 'a' assert !(@standard.valid?), "Standard created with two short of a name." @standard.name = 'aa' assert (@standard.valid?), "Standard created with incorrect error." @standard.name = "a" * 250 assert (@standard.valid?), "Standard created with incorrect error." @standard.name = "a" * 251 assert !(@standard.valid?), "Standard created with two long of a name." end # Basic checks for text existence and length test "standard must valid text" do @standard.text = nil assert !(@standard.valid?), "Standard created without text." @standard.text = "a" assert !(@standard.valid?), "Standard created with invalid text." @standard.text = "a " assert !(@standard.valid?), "Standard created with invalid text." @standard.text = " a" assert !(@standard.valid?), "Standard created with invalid text." @standard.text = "\ta" assert !(@standard.valid?), "Standard created with invalid text." @standard.text = "a\t" assert !(@standard.valid?), "Standard created with invalid text." @standard.text = "a"*3501 assert !(@standard.valid?), "Standard created with to long of a text." @standard.text = "a"*2 assert @standard.valid?, "Standard not created with valid text." @standard.text = "a"*3 assert @standard.valid?, "Standard not created with valid text." @standard.text = "a"*3499 assert @standard.valid?, "Standard not created with valid text." end # Checks for course grade manipulation test "standard must valid course grade" do @standard.course_grades = [] assert_equal @standard.course_grades, [], "Standard created with a course grade." @standard.course_grades << [course_grades(:one), course_grades(:two)] assert_equal @standard.course_grades.length, 2, 'Standard has incorrect number of course grades' @standard.course_grades = [] assert_equal @standard.course_grades.length, 0, 'Standard has did not delete course grades' end private def initialize_resource @standard = standards(:standard_8051b7d8d2cc77b2e3a73b0d7428454a71f1c011) assert @standard.valid?, 'Initialized Standard was not valid.' assert @standard.save, 'Initialized Standard was not saved.' end end
36.336634
99
0.70109
ab660deae88c4622c431b7c722e540e2994ed41e
153
# http://www.codewars.com/kata/5412509bd436bd33920011bc # --- iteration 1 --- def maskify(cc) cc.length > 4 ? cc[-4,4].rjust(cc.length, "#") : cc end
21.857143
55
0.647059
e81d70736461ddf9d86a864bc1b87bc6235841ac
21,331
# encoding: utf-8 #:stopdoc: # this file was autogenerated on 2011-07-21 07:15:33 +0100 # using amqp-0.8.json (mtime: 2011-07-20 19:11:32 +0100) # # DO NOT EDIT! (edit ext/qparser.rb and config.yml instead, and run 'ruby qparser.rb') module Qrack module Protocol HEADER = "AMQP".freeze VERSION_MAJOR = 8 VERSION_MINOR = 0 REVISION = 0 PORT = 5672 RESPONSES = { 200 => :REPLY_SUCCESS, 310 => :NOT_DELIVERED, 311 => :CONTENT_TOO_LARGE, 312 => :NO_ROUTE, 313 => :NO_CONSUMERS, 320 => :CONNECTION_FORCED, 402 => :INVALID_PATH, 403 => :ACCESS_REFUSED, 404 => :NOT_FOUND, 405 => :RESOURCE_LOCKED, 406 => :PRECONDITION_FAILED, 502 => :SYNTAX_ERROR, 503 => :COMMAND_INVALID, 504 => :CHANNEL_ERROR, 506 => :RESOURCE_ERROR, 530 => :NOT_ALLOWED, 540 => :NOT_IMPLEMENTED, 541 => :INTERNAL_ERROR, } FIELDS = [ :bit, :long, :longlong, :longstr, :octet, :short, :shortstr, :table, :timestamp, ] class Class class << self FIELDS.each do |f| class_eval %[ def #{f} name properties << [ :#{f}, name ] unless properties.include?([:#{f}, name]) attr_accessor name end ] end def properties() @properties ||= [] end def id() self::ID end def name() self::NAME.to_s end end class Method class << self FIELDS.each do |f| class_eval %[ def #{f} name arguments << [ :#{f}, name ] unless arguments.include?([:#{f}, name]) attr_accessor name end ] end def arguments() @arguments ||= [] end def parent() Protocol.const_get(self.to_s[/Protocol::(.+?)::/,1]) end def id() self::ID end def name() self::NAME.to_s end end def == b self.class.arguments.inject(true) do |eql, (type, name)| eql and __send__("#{name}") == b.__send__("#{name}") end end end def self.methods() @methods ||= {} end def self.Method(id, name) @_base_methods ||= {} @_base_methods[id] ||= ::Class.new(Method) do class_eval %[ def self.inherited klass klass.const_set(:ID, #{id}) klass.const_set(:NAME, :#{name.to_s}) klass.parent.methods[#{id}] = klass klass.parent.methods[klass::NAME] = klass end ] end end end def self.classes() @classes ||= {} end def self.Class(id, name) @_base_classes ||= {} @_base_classes[id] ||= ::Class.new(Class) do class_eval %[ def self.inherited klass klass.const_set(:ID, #{id}) klass.const_set(:NAME, :#{name.to_s}) Protocol.classes[#{id}] = klass Protocol.classes[klass::NAME] = klass end ] end end end end module Qrack module Protocol class Connection < Class( 10, :connection ); end class Channel < Class( 20, :channel ); end class Access < Class( 30, :access ); end class Exchange < Class( 40, :exchange ); end class Queue < Class( 50, :queue ); end class Basic < Class( 60, :basic ); end class File < Class( 70, :file ); end class Stream < Class( 80, :stream ); end class Tx < Class( 90, :tx ); end class Dtx < Class( 100, :dtx ); end class Tunnel < Class( 110, :tunnel ); end class Test < Class( 120, :test ); end class Connection class Start < Method( 10, :start ); end class StartOk < Method( 11, :start_ok ); end class Secure < Method( 20, :secure ); end class SecureOk < Method( 21, :secure_ok ); end class Tune < Method( 30, :tune ); end class TuneOk < Method( 31, :tune_ok ); end class Open < Method( 40, :open ); end class OpenOk < Method( 41, :open_ok ); end class Redirect < Method( 50, :redirect ); end class Close < Method( 60, :close ); end class CloseOk < Method( 61, :close_ok ); end class Start octet :version_major octet :version_minor table :server_properties longstr :mechanisms longstr :locales end class StartOk table :client_properties shortstr :mechanism longstr :response shortstr :locale end class Secure longstr :challenge end class SecureOk longstr :response end class Tune short :channel_max long :frame_max short :heartbeat end class TuneOk short :channel_max long :frame_max short :heartbeat end class Open shortstr :virtual_host shortstr :capabilities bit :insist end class OpenOk shortstr :known_hosts end class Redirect shortstr :host shortstr :known_hosts end class Close short :reply_code shortstr :reply_text short :class_id short :method_id end class CloseOk end end class Channel class Open < Method( 10, :open ); end class OpenOk < Method( 11, :open_ok ); end class Flow < Method( 20, :flow ); end class FlowOk < Method( 21, :flow_ok ); end class Alert < Method( 30, :alert ); end class Close < Method( 40, :close ); end class CloseOk < Method( 41, :close_ok ); end class Open shortstr :out_of_band end class OpenOk end class Flow bit :active end class FlowOk bit :active end class Alert short :reply_code shortstr :reply_text table :details end class Close short :reply_code shortstr :reply_text short :class_id short :method_id end class CloseOk end end class Access class Request < Method( 10, :request ); end class RequestOk < Method( 11, :request_ok ); end class Request shortstr :realm bit :exclusive bit :passive bit :active bit :write bit :read end class RequestOk short :ticket end end class Exchange class Declare < Method( 10, :declare ); end class DeclareOk < Method( 11, :declare_ok ); end class Delete < Method( 20, :delete ); end class DeleteOk < Method( 21, :delete_ok ); end class Declare short :ticket shortstr :exchange shortstr :type bit :passive bit :durable bit :auto_delete bit :internal bit :nowait table :arguments end class DeclareOk end class Delete short :ticket shortstr :exchange bit :if_unused bit :nowait end class DeleteOk end end class Queue class Declare < Method( 10, :declare ); end class DeclareOk < Method( 11, :declare_ok ); end class Bind < Method( 20, :bind ); end class BindOk < Method( 21, :bind_ok ); end class Purge < Method( 30, :purge ); end class PurgeOk < Method( 31, :purge_ok ); end class Delete < Method( 40, :delete ); end class DeleteOk < Method( 41, :delete_ok ); end class Unbind < Method( 50, :unbind ); end class UnbindOk < Method( 51, :unbind_ok ); end class Declare short :ticket shortstr :queue bit :passive bit :durable bit :exclusive bit :auto_delete bit :nowait table :arguments end class DeclareOk shortstr :queue long :message_count long :consumer_count end class Bind short :ticket shortstr :queue shortstr :exchange shortstr :routing_key bit :nowait table :arguments end class BindOk end class Purge short :ticket shortstr :queue bit :nowait end class PurgeOk long :message_count end class Delete short :ticket shortstr :queue bit :if_unused bit :if_empty bit :nowait end class DeleteOk long :message_count end class Unbind short :ticket shortstr :queue shortstr :exchange shortstr :routing_key table :arguments end class UnbindOk end end class Basic shortstr :content_type shortstr :content_encoding table :headers octet :delivery_mode octet :priority shortstr :correlation_id shortstr :reply_to shortstr :expiration shortstr :message_id timestamp :timestamp shortstr :type shortstr :user_id shortstr :app_id shortstr :cluster_id class Qos < Method( 10, :qos ); end class QosOk < Method( 11, :qos_ok ); end class Consume < Method( 20, :consume ); end class ConsumeOk < Method( 21, :consume_ok ); end class Cancel < Method( 30, :cancel ); end class CancelOk < Method( 31, :cancel_ok ); end class Publish < Method( 40, :publish ); end class Return < Method( 50, :return ); end class Deliver < Method( 60, :deliver ); end class Get < Method( 70, :get ); end class GetOk < Method( 71, :get_ok ); end class GetEmpty < Method( 72, :get_empty ); end class Ack < Method( 80, :ack ); end class Reject < Method( 90, :reject ); end class Recover < Method( 100, :recover ); end class Qos long :prefetch_size short :prefetch_count bit :global end class QosOk end class Consume short :ticket shortstr :queue shortstr :consumer_tag bit :no_local bit :no_ack bit :exclusive bit :nowait end class ConsumeOk shortstr :consumer_tag end class Cancel shortstr :consumer_tag bit :nowait end class CancelOk shortstr :consumer_tag end class Publish short :ticket shortstr :exchange shortstr :routing_key bit :mandatory bit :immediate end class Return short :reply_code shortstr :reply_text shortstr :exchange shortstr :routing_key end class Deliver shortstr :consumer_tag longlong :delivery_tag bit :redelivered shortstr :exchange shortstr :routing_key end class Get short :ticket shortstr :queue bit :no_ack end class GetOk longlong :delivery_tag bit :redelivered shortstr :exchange shortstr :routing_key long :message_count end class GetEmpty shortstr :cluster_id end class Ack longlong :delivery_tag bit :multiple end class Reject longlong :delivery_tag bit :requeue end class Recover bit :requeue end end class File shortstr :content_type shortstr :content_encoding table :headers octet :priority shortstr :reply_to shortstr :message_id shortstr :filename timestamp :timestamp shortstr :cluster_id class Qos < Method( 10, :qos ); end class QosOk < Method( 11, :qos_ok ); end class Consume < Method( 20, :consume ); end class ConsumeOk < Method( 21, :consume_ok ); end class Cancel < Method( 30, :cancel ); end class CancelOk < Method( 31, :cancel_ok ); end class Open < Method( 40, :open ); end class OpenOk < Method( 41, :open_ok ); end class Stage < Method( 50, :stage ); end class Publish < Method( 60, :publish ); end class Return < Method( 70, :return ); end class Deliver < Method( 80, :deliver ); end class Ack < Method( 90, :ack ); end class Reject < Method( 100, :reject ); end class Qos long :prefetch_size short :prefetch_count bit :global end class QosOk end class Consume short :ticket shortstr :queue shortstr :consumer_tag bit :no_local bit :no_ack bit :exclusive bit :nowait end class ConsumeOk shortstr :consumer_tag end class Cancel shortstr :consumer_tag bit :nowait end class CancelOk shortstr :consumer_tag end class Open shortstr :identifier longlong :content_size end class OpenOk longlong :staged_size end class Stage end class Publish short :ticket shortstr :exchange shortstr :routing_key bit :mandatory bit :immediate shortstr :identifier end class Return short :reply_code shortstr :reply_text shortstr :exchange shortstr :routing_key end class Deliver shortstr :consumer_tag longlong :delivery_tag bit :redelivered shortstr :exchange shortstr :routing_key shortstr :identifier end class Ack longlong :delivery_tag bit :multiple end class Reject longlong :delivery_tag bit :requeue end end class Stream shortstr :content_type shortstr :content_encoding table :headers octet :priority timestamp :timestamp class Qos < Method( 10, :qos ); end class QosOk < Method( 11, :qos_ok ); end class Consume < Method( 20, :consume ); end class ConsumeOk < Method( 21, :consume_ok ); end class Cancel < Method( 30, :cancel ); end class CancelOk < Method( 31, :cancel_ok ); end class Publish < Method( 40, :publish ); end class Return < Method( 50, :return ); end class Deliver < Method( 60, :deliver ); end class Qos long :prefetch_size short :prefetch_count long :consume_rate bit :global end class QosOk end class Consume short :ticket shortstr :queue shortstr :consumer_tag bit :no_local bit :exclusive bit :nowait end class ConsumeOk shortstr :consumer_tag end class Cancel shortstr :consumer_tag bit :nowait end class CancelOk shortstr :consumer_tag end class Publish short :ticket shortstr :exchange shortstr :routing_key bit :mandatory bit :immediate end class Return short :reply_code shortstr :reply_text shortstr :exchange shortstr :routing_key end class Deliver shortstr :consumer_tag longlong :delivery_tag shortstr :exchange shortstr :queue end end class Tx class Select < Method( 10, :select ); end class SelectOk < Method( 11, :select_ok ); end class Commit < Method( 20, :commit ); end class CommitOk < Method( 21, :commit_ok ); end class Rollback < Method( 30, :rollback ); end class RollbackOk < Method( 31, :rollback_ok ); end class Select end class SelectOk end class Commit end class CommitOk end class Rollback end class RollbackOk end end class Dtx class Select < Method( 10, :select ); end class SelectOk < Method( 11, :select_ok ); end class Start < Method( 20, :start ); end class StartOk < Method( 21, :start_ok ); end class Select end class SelectOk end class Start shortstr :dtx_identifier end class StartOk end end class Tunnel table :headers shortstr :proxy_name shortstr :data_name octet :durable octet :broadcast class Request < Method( 10, :request ); end class Request table :meta_data end end class Test class Integer < Method( 10, :integer ); end class IntegerOk < Method( 11, :integer_ok ); end class String < Method( 20, :string ); end class StringOk < Method( 21, :string_ok ); end class Table < Method( 30, :table ); end class TableOk < Method( 31, :table_ok ); end class Content < Method( 40, :content ); end class ContentOk < Method( 41, :content_ok ); end class Integer octet :integer_1 short :integer_2 long :integer_3 longlong :integer_4 octet :operation end class IntegerOk longlong :result end class String shortstr :string_1 longstr :string_2 octet :operation end class StringOk longstr :result end class Table table :table octet :integer_op octet :string_op end class TableOk longlong :integer_result longstr :string_result end class Content end class ContentOk long :content_checksum end end end end
25.731001
86
0.455675
e86607209c137c2d5e433c93e9a56406b8109699
495
require 'spec_helper' RSpec.describe "Nested Attribute", :type => :request do describe "datetime picker" do context 'when we have a schedule that belongs to a person' do let!(:person) { create(:person) } let!(:schedule) { create(:schedule, person: person) } it "generates the correct input fields to update the schedule" do visit edit_person_path(person) expect(page).to have_selector("input[name='person[schedules_attributes][0][apocalypse]']") end end end end
33
95
0.711111
bf517f6825a2d9493cd587624944d5f666167ec9
22,519
# frozen_string_literal: true # Copyright 2018 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. require "google/cloud/bigtable/errors" require "google/cloud/bigtable/longrunning_job" require "google/cloud/bigtable/convert" require "google/cloud/bigtable/service" require "google/cloud/bigtable/instance" require "google/cloud/bigtable/cluster" require "google/cloud/bigtable/table" module Google module Cloud module Bigtable # # Project # # Projects are top-level containers in Google Cloud Platform. They store # information about billing and authorized users, and they contain # Cloud Bigtable data. Each project has a friendly name and a unique ID. # # Google::Cloud::Bigtable::Project is the main object for interacting with # Cloud Bigtable. # # {Google::Cloud::Bigtable::Cluster} and {Google::Cloud::Bigtable::Instance} # objects are created, accessed, and managed by Google::Cloud::Bigtable::Project. # # To create an instance, use {Google::Cloud::Bigtable.new} or # {Google::Cloud#bigtable}. # # @example Obtaining an instance and the clusters from a project. # require "google/cloud" # # bigtable = Google::Cloud::Bigtable.new # # instance = bigtable.instance("my-instance") # clusters = bigtable.clusters # All clusters in the project # class Project # @private # The Service object attr_accessor :service # @private # Creates a new Bigtable Project instance. # @param service [Google::Cloud::Bigtable::Service] def initialize service @service = service end # The identifier for the Cloud Bigtable project. # # @return [String] Project ID. # # @example # require "google/cloud" # # bigtable = Google::Cloud::Bigtable.new( # project_id: "my-project", # credentials: "/path/to/keyfile.json" # ) # # bigtable.project_id #=> "my-project" def project_id ensure_service! service.project_id end # Retrieves the list of Bigtable instances for the project. # # @param token [String] The `token` value returned by the last call to # `instances`; indicates that this is a continuation of a call # and that the system should return the next page of data. # @return [Array<Google::Cloud::Bigtable::Instance>] The list of instances. # (See {Google::Cloud::Bigtable::Instance::List}) # # @example # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # instances = bigtable.instances # instances.all do |instance| # puts instance.instance_id # end def instances token: nil ensure_service! grpc = service.list_instances(token: token) Instance::List.from_grpc(grpc, service) end # Get an existing Bigtable instance. # # @param instance_id [String] Existing instance id. # @return [Google::Cloud::Bigtable::Instance, nil] # # @example # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # instance = bigtable.instance("my-instance") # # if instance # puts instance.instance_id # end def instance instance_id ensure_service! grpc = service.get_instance(instance_id) Instance.from_grpc(grpc, service) rescue Google::Cloud::NotFoundError nil end # Create a Bigtable instance. # # @see https://cloud.google.com/compute/docs/regions-zones Cluster zone locations # # @param instance_id [String] The unique identifier for the instance, # which cannot be changed after the instance is created. Values are of # the form `[a-z][-a-z0-9]*[a-z0-9]` and must be between 6 and 30 # characters. Required. # @param display_name [String] The descriptive name for this instance as it # appears in UIs. Must be unique per project and between 4 and 30 # characters. # @param type [Symbol] The type of the instance. # Valid values are `:DEVELOPMENT` or `:PRODUCTION`. # Default `:PRODUCTION` instance will created if left blank. # @param labels [Hash{String=>String}] labels Cloud Labels are a flexible and lightweight # mechanism for organizing cloud resources into groups that reflect a # customer's organizational needs and deployment strategies. Cloud # Labels can be used to filter collections of resources. They can be # used to control how resource metrics are aggregated. Cloud Labels can be # used as arguments to policy management rules (e.g., route, firewall, or # load balancing). # # * Label keys must be between 1 and 63 characters and must # conform to the following regular expression: # `[a-z]([-a-z0-9]*[a-z0-9])?`. # * Label values must be between 0 and 63 characters and must # conform to the regular expression `([a-z]([-a-z0-9]*[a-z0-9])?)?`. # * No more than 64 labels can be associated with a given resource. # @param clusters [Hash{String => Google::Cloud::Bigtable::Cluster}] # (See {Google::Cloud::Bigtable::Instance::ClusterMap}) # If unspecified, you may use a code block to add clusters. # Minimum of one cluster must be specified. # @yield [clusters] A block for adding clusters. # @yieldparam [Hash{String => Google::Cloud::Bigtable::Cluster}] # Cluster map of cluster name and cluster object. # (See {Google::Cloud::Bigtable::Instance::ClusterMap}) # @return [Google::Cloud::Bigtable::Instance::Job] # The job representing the long-running, asynchronous processing of # an instance create operation. # # @example Create development instance. # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # job = bigtable.create_instance( # "my-instance", # display_name: "Instance for user data", # type: :DEVELOPMENT, # labels: { "env" => "dev"} # ) do |clusters| # clusters.add("test-cluster", "us-east1-b", nodes: 1) # end # # job.done? #=> false # # # Reload job until completion. # job.wait_until_done # job.done? #=> true # # if job.error? # status = job.error # else # instance = job.instance # end # # @example Create production instance. # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # job = bigtable.create_instance( # "my-instance", # display_name: "Instance for user data", # labels: { "env" => "dev"} # ) do |clusters| # clusters.add("test-cluster", "us-east1-b", nodes: 3, storage_type: :SSD) # end # # job.done? #=> false # # # To block until the operation completes. # job.wait_until_done # job.done? #=> true # # if job.error? # status = job.error # else # instance = job.instance # end def create_instance \ instance_id, display_name: nil, type: nil, labels: nil, clusters: nil labels = Hash[labels.map { |k, v| [String(k), String(v)] }] if labels instance_attrs = { display_name: display_name, type: type, labels: labels }.delete_if { |_, v| v.nil? } instance = Google::Bigtable::Admin::V2::Instance.new(instance_attrs) clusters ||= Instance::ClusterMap.new yield clusters if block_given? clusters.each_value do |cluster| unless cluster.location == "".freeze cluster.location = service.location_path(cluster.location) end end grpc = service.create_instance( instance_id, instance, clusters.to_h ) Instance::Job.from_grpc(grpc, service) end # List all clusters in project. # # @param token [String] The `token` value returned by the last call to # `clusters` indicates that this is a continuation of a call # and the system should return the next page of data. # @return [Array<Google::Cloud::Bigtable::Cluster>] # (See {Google::Cloud::Bigtable::Cluster::List}) # @example # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # bigtable.clusters.all do |cluster| # puts cluster.cluster_id # puts cluster.ready? # end def clusters token: nil ensure_service! grpc = service.list_clusters("-", token: token) Cluster::List.from_grpc(grpc, service, instance_id: "-") end # List all tables for given instance. # # @param instance_id [String] Existing instance Id. # @return [Array<Google::Cloud::Bigtable::Table>] # (See {Google::Cloud::Bigtable::Table::List}) # # @example Get tables # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # bigtable.tables("my-instance").all do |table| # puts table.name # puts table.column_families # end def tables instance_id ensure_service! grpc = service.list_tables(instance_id) Table::List.from_grpc(grpc, service) end # Get table information. # # # @param instance_id [String] Existing instance Id. # @param table_id [String] Existing table Id. # @param view [Symbol] Optional. Table view type. Default `:SCHEMA_VIEW` # Valid view types are the following: # * `:NAME_ONLY` - Only populates `name` # * `:SCHEMA_VIEW` - Only populates `name` and fields related to the table's schema # * `:REPLICATION_VIEW` - Only populates `name` and fields related to the table's replication state. # * `:FULL` - Populates all fields # @param perform_lookup [Boolean] # Get table object without verifying that the table resource exists. # Calls made on this object will raise errors if the table does not exist. # Default value is `false`. Optional. # Helps to reduce admin API calls. # @param app_profile_id [String] The unique identifier for the app profile. Optional. # Used only in data operations. # This value specifies routing for replication. If not specified, the # "default" application profile will be used. # @return [Google::Cloud::Bigtable::Table, nil] # # @example Get table with schema only view # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # table = bigtable.table("my-instance", "my-table", perform_lookup: true, view: :SCHEMA_VIEW) # if table # p table.name # p table.column_families # end # # @example Get table object without calling get table admin api. # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # table = bigtable.table("my-instance", "my-table") # # @example Get table with all fields, cluster states, and column families. # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # table = bigtable.table("my-instance", "my-table", view: :FULL, perform_lookup: true) # if table # puts table.name # p table.column_families # p table.cluster_states # end # # @example Mutate rows # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # table = bigtable.table("my-instance", "my-table") # # entry = table.new_mutation_entry("user-1") # entry.set_cell( # "cf-1", # "field-1", # "XYZ" # timestamp: Time.now.to_i * 1000 # Timestamp in milliseconds. # ).delete_from_column("cf2", "field02") # # table.mutate_row(entry) # @example Read rows using app profile routing # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # table = bigtable.table("my-instance", "my-table", app_profile_id: "my-app-profile") # # table.read_rows(limit: 5).each do |row| # p row # end def table \ instance_id, table_id, view: nil, perform_lookup: nil, app_profile_id: nil ensure_service! table = if perform_lookup grpc = service.get_table(instance_id, table_id, view: view) Table.from_grpc(grpc, service, view: view) else Table.from_path( service.table_path(instance_id, table_id), service ) end table.app_profile_id = app_profile_id table rescue Google::Cloud::NotFoundError nil end # Creates a new table in the specified instance. # The table can be created with a full set of initial column families, # specified in the request. # # @param instance_id [String] # The unique ID of the instance in which to create the table. # @param table_id [String] # The ID by which the new table should be referred to within the # instance, e.g., `foobar`. # @param column_families [Hash{String => Google::Cloud::Bigtable::ColumnFamily}] # (See {Google::Cloud::Bigtable::Table::ColumnFamilyMap}) # If unspecified, you may use a code block to add column families. # @param granularity [Symbol] # The granularity at which timestamps are stored in this table. # Timestamps not matching the granularity will be rejected. # Valid value is `:MILLIS`. # If unspecified, the value will be set to `:MILLIS`. # @param initial_splits [Array<String>] # The optional list of row keys that will be used to initially split the # table into several tablets (tablets are similar to HBase regions). # Given two split keys, `s1` and `s2`, three tablets will be created, # spanning the key ranges: `[, s1), [s1, s2), [s2, )`. # # Example: # # * Row keys := `["a", "apple", "custom", "customer_1", "customer_2", "other", "zz"]` # * initial_split_keys := `["apple", "customer_1", "customer_2", "other"]` # * Key assignment: # * Tablet 1 : `[, apple) => {"a"}` # * Tablet 2 : `[apple, customer_1) => {"apple", "custom"}` # * Tablet 3 : `[customer_1, customer_2) => {"customer_1"}` # * Tablet 4 : `[customer_2, other) => {"customer_2"}` # * Tablet 5 : `[other, ) => {"other", "zz"}` # A hash in the form of `Google::Bigtable::Admin::V2::CreateTableRequest::Split` # can also be provided. # @yield [column_families] A block for adding column_families. # @yieldparam [Hash{String => Google::Cloud::Bigtable::ColumnFamily}] # Map of family name and column family object. # (See {Google::Cloud::Bigtable::Instance::ColumnFamilyMap}) # (Read the GC Rules for column families at {Google::Cloud::Bigtable::GcRule}) # # @return [Google::Cloud::Bigtable::Table] # # @example Create a table without a column family # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # table = bigtable.create_table("my-instance", "my-table") # puts table.name # # @example Create table with column families and initial splits. # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # initial_splits = ["user-00001", "user-100000", "others"] # table = bigtable.create_table("my-instance", "my-table", initial_splits: initial_splits) do |column_families| # column_families.add('cf1', Google::Cloud::Bigtable::GcRule.max_versions(5)) # column_families.add('cf2', Google::Cloud::Bigtable::GcRule.max_age(600)) # # gc_rule = Google::Cloud::Bigtable::GcRule.union( # Google::Cloud::Bigtable::GcRule.max_age(1800), # Google::Cloud::Bigtable::GcRule.max_versions(3) # ) # column_families.add('cf3', gc_rule) # end # # p table def create_table \ instance_id, table_id, column_families: nil, granularity: nil, initial_splits: nil, &block ensure_service! Table.create( service, instance_id, table_id, column_families: column_families, granularity: granularity, initial_splits: initial_splits, &block ) end # Permanently deletes a specified table and all of its data. # # @param instance_id [String] # The unique ID of the instance the table is in. # @param table_id [String] # The unique ID of the table to be deleted, # e.g., `foobar` # # @example Create table with column families and initial splits. # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # bigtable.delete_table("my-instance", "my-table") # def delete_table instance_id, table_id service.delete_table(instance_id, table_id) true end # Performs a series of column family modifications on the specified table. # Either all or none of the modifications will occur before this method # returns, but data requests received prior to that point may see a table # where only some modifications have taken effect. # # @param instance_id [String] # The unique ID of the instance the table is in. # @param table_id [String] # The unique Id of the table whose families should be modified. # @param modifications [Array<Google::Bigtable::Admin::V2::ModifyColumnFamiliesRequest::Modification> | Google::Bigtable::Admin::V2::ModifyColumnFamiliesRequest::Modification] # Modifications to be atomically applied to the specified table's families. # Entries are applied in order, meaning that earlier modifications can be # masked by later ones (in the case of repeated updates to the same family, # for example). # @return [Google::Cloud::Bigtable::Table] Table with updated column families. # # @example # require "google/cloud/bigtable" # # bigtable = Google::Cloud::Bigtable.new # # modifications = [] # modifications << Google::Cloud::Bigtable::ColumnFamily.create_modification( # "cf1", Google::Cloud::Bigtable::GcRule.max_age(600)) # ) # # modifications << Google::Cloud::Bigtable::ColumnFamily.update_modification( # "cf2", Google::Cloud::Bigtable::GcRule.max_versions(5) # ) # # gc_rule_1 = Google::Cloud::Bigtable::GcRule.max_versions(3) # gc_rule_2 = Google::Cloud::Bigtable::GcRule.max_age(600) # modifications << Google::Cloud::Bigtable::ColumnFamily.update_modification( # "cf3", Google::Cloud::Bigtable::GcRule.union(gc_rule_1, gc_rule_2) # ) # # max_age_gc_rule = Google::Cloud::Bigtable::GcRule.max_age(300) # modifications << Google::Cloud::Bigtable::ColumnFamily.update_modification( # "cf4", Google::Cloud::Bigtable::GcRule.union(max_version_gc_rule) # ) # # modifications << Google::Cloud::Bigtable::ColumnFamily.drop_modification("cf5") # # table = bigtable.modify_column_families("my-instance", "my-table", modifications) # # p table.column_families def modify_column_families instance_id, table_id, modifications ensure_service! Table.modify_column_families( service, instance_id, table_id, modifications ) end protected # @private # # Raise an error unless an active connection to the service is # available. def ensure_service! raise "Must have active connection to service" unless service end end end end end
38.759036
183
0.571917
873a97d50560e93475ee1a526e6365ce88565357
2,870
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe "Bundler DSL" do it "supports only blocks" do install_manifest <<-Gemfile clear_sources source "file://#{gem_repo1}" gem "activerecord" only :test do gem "rspec", :require_as => "spec" gem "very-simple" end Gemfile "default".should have_const("ACTIVERECORD") "default".should_not have_const("SPEC") "default".should_not have_const("VERYSIMPLE") "test".should have_const("ACTIVERECORD") "test".should have_const("SPEC") "test".should have_const("VERYSIMPLE") end it "supports only blocks with multiple args" do install_manifest <<-Gemfile clear_sources source "file://#{gem_repo1}" only :test, :production do gem "rack" end Gemfile "default".should_not have_const("RACK") "test".should have_const("RACK") "production".should have_const("RACK") end it "supports nesting only blocks" do install_manifest <<-Gemfile clear_sources source "file://#{gem_repo1}" only [:test, :staging] do gem "very-simple" only :test do gem "rspec", :require_as => "spec" end end Gemfile "test".should have_const("VERYSIMPLE") "test".should have_const("SPEC") "staging".should have_const("VERYSIMPLE") "staging".should_not have_const("SPEC") end it "supports except blocks" do install_manifest <<-Gemfile clear_sources source "file://#{gem_repo1}" gem "activerecord" except :test do gem "rspec", :require_as => "spec" gem "very-simple" end Gemfile "default".should have_const("ACTIVERECORD") "default".should have_const("SPEC") "default".should have_const("VERYSIMPLE") "test".should have_const("ACTIVERECORD") "test".should_not have_const("SPEC") "test".should_not have_const("VERYSIMPLE") end it "supports except blocks with multiple args" do install_manifest <<-Gemfile clear_sources source "file://#{gem_repo1}" except :test, :production do gem "rack" end Gemfile "default".should have_const("RACK") "test".should_not have_const("RACK") "production".should_not have_const("RACK") end it "supports nesting except blocks" do install_manifest <<-Gemfile clear_sources source "file://#{gem_repo1}" except [:test] do gem "very-simple" except :omg do gem "rspec", :require_as => "spec" end end Gemfile "default".should have_const("SPEC") "default".should have_const("VERYSIMPLE") "test".should_not have_const("VERYSIMPLE") "test".should_not have_const("SPEC") "omg".should have_const("VERYSIMPLE") "omg".should_not have_const("SPEC") end end
24.741379
68
0.633798
628a0d0cbb0469dd34f3c9e1b198e7d692e95dd8
1,411
class Barcode < ApplicationRecord belongs_to :product, dependent: :destroy has_many :barcode_options has_many :product_options, through: :barcode_options belongs_to :cart_item, optional: true, counter_cache: :barcode_count scope :alive, -> { where(cart_item_id: nil) } scope :finished, -> { where.not(cart_item_id: nil) } scope :options_with, ->(*option_ids) { where(id: BarcodeOption.barcode_ids_for(*option_ids)) } scope :cart_with, ->(cart_id) { includes(:cart_item).where(cart_item: CartItem.where(cart_id: cart_id)) } scope :not_cancelled, -> { where(cancelled_at: nil) } scope :ordered_at, ->(range) { includes(:cart_item).where( cart_item: CartItem.includes(:cart).where( cart: Cart.includes(:order_info).where( order_info: OrderInfo.sold.where(ordered_at: range) ) ) ) } scope :price_sum, -> { includes(:product, :product_options).map(&:price).sum } delegate :order_info, to: :cart_item, allow_nil: true delegate :ordered_at, to: :order_info, allow_nil: true after_save :update_product_cache def price product.price + product_options.sum(&:additional_price) end def cancel! update(cancelled_at: Time.zone.now) end def remove! barcode_options.each(&:delete) delete if barcode_options.reload.count.zero? end protected def update_product_cache product.update_barcode_cache end end
28.22
107
0.708717
626e71293585306d79e7d026617dfe0579ce7128
3,497
# frozen_string_literal: true require_relative 'icons' module Lita module Handlers class Zerocater < Handler config :locations, type: Hash, required: true route( /^zerocater\s(?<date>today|tomorrow|yesterday)$/, :menu, command: true, help: { t('help.menu.syntax') => t('help.menu.desc') } ) route( /^(breakfast|brunch|lunch|dinner)$/i, :alias, command: true, help: { t('help.alias.syntax') => t('help.alias.desc') } ) # rubocop:disable Metrics/MethodLength def menu(response) search_date = case response.match_data['date'] when 'tomorrow' Date.today + 1 when 'yesterday' Date.today - 1 else Date.today end config.locations.each_key do |location| response.reply(fetch_menu(location, search_date)) end end # rubocop:enable Metrics/MethodLength def alias(response) config.locations.each_key do |location| response.reply(fetch_menu(location, Date.today)) end end private def fetch_meal(id) JSON.parse(http.get("https://api.zerocater.com/v3/meals/#{id}").body) end def fetch_meals(location) JSON.parse( http.get("https://api.zerocater.com/v3/companies/#{location}/meals") .body ) end def fetch_menu(location, search_date) cache_key = "#{location}_#{search_date}" return redis.get(cache_key) if redis.exists(cache_key) menu = render_menu(location, search_date) redis.set(cache_key, menu, ex: 300) menu end def find_meals(meals, search_date) results = [] meals.each do |item| results << item['id'] if Time.at(item['time']).to_date == search_date end results end def find_menu(location, search_date) results = find_meals(fetch_meals(location), search_date) meals = [] results.each do |result| m = fetch_meal(result) meals << m end meals end # append emoji icons based on item labels def append_icons(item) labels = get_label_icons(item) # if it's vegan, it's necessarily vegetarian. Remove redundant icon. if labels.include?(ICONS['vegetarian']) && labels.include?(ICONS['vegan']) labels.delete_at(labels.index(ICONS['vegetarian'])) end labels.empty? ? item['name'] : item['name'] << ' | ' << labels.join(' ') end def get_label_icons(item) labels = item['labels'].select do |label, value| value['value'] == true && ICONS.key?(label) end labels.map { |label, _| ICONS[label] } end def render_menu(location, search_date) menu = find_menu(config.locations[location], search_date) return t('error.empty') if menu.empty? items = menu.map { |m| m['items'].map { |item| append_icons(item) } } render_template('menu', menu: menu, items: items, locale: t('menu.locale', location: location)) rescue StandardError t('error.retrieve') end end Lita.register_handler(Zerocater) end end
26.694656
80
0.545611
18a5a5cbcb11338c6057a9b2ba75bbae4f41da5b
2,445
require 'test_helper' class MonerisRemoteTest < Test::Unit::TestCase def setup Base.mode = :test @gateway = MonerisGateway.new(fixtures(:moneris)) @amount = 100 @credit_card = credit_card('4242424242424242') @options = { :order_id => generate_unique_id, :billing_address => address, :description => 'Store Purchase' } end def test_successful_purchase assert response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_equal 'Approved', response.message assert_false response.authorization.blank? end def test_successful_authorization response = @gateway.authorize(@amount, @credit_card, @options) assert_success response assert_false response.authorization.blank? end def test_failed_authorization response = @gateway.authorize(105, @credit_card, @options) assert_failure response end def test_successful_authorization_and_capture response = @gateway.authorize(@amount, @credit_card, @options) assert_success response assert response.authorization response = @gateway.capture(@amount, response.authorization) assert_success response end def test_successful_authorization_and_void response = @gateway.authorize(@amount, @credit_card, @options) assert_success response assert response.authorization # Moneris cannot void a preauthorization # You must capture the auth transaction with an amount of $0.00 void = @gateway.capture(0, response.authorization) assert_success void end def test_successful_purchase_and_void purchase = @gateway.purchase(@amount, @credit_card, @options) assert_success purchase void = @gateway.void(purchase.authorization) assert_success void end def test_failed_purchase_and_void purchase = @gateway.purchase(101, @credit_card, @options) assert_failure purchase void = @gateway.void(purchase.authorization) assert_failure void end def test_successful_purchase_and_credit purchase = @gateway.purchase(@amount, @credit_card, @options) assert_success purchase credit = @gateway.credit(@amount, purchase.authorization) assert_success credit end def test_failed_purchase_from_error assert response = @gateway.purchase(150, @credit_card, @options) assert_failure response assert_equal 'Declined', response.message end end
28.764706
72
0.736196
280c6014ae101425ab4aff69ec452a0aa08c34b0
826
module Jaconda class API::Room < API def id jid end def presences API::Presence.prefix = "/api/v2/rooms/:room_id/" API::Presence.find(:all, :params => {:room_id => id}) end def add_presence(user_id) API::Presence.prefix = "/api/v2/rooms/:room_id/" API::Presence.create(:room_id => id, :user_id => user_id) end def uploads API::Upload.prefix = "/api/v2/rooms/:room_id/" API::Upload.find(:all, :params => {:room_id => id}) end def messages(options = {}) API::Message.find(:all, :params => options.update(:room_id => id)) end def search(options = {}) API::Message.search(options.update(:room_id => id)) end def transcript(options = {}) API::Message.transcript(options.update(:room_id => id)) end end end
24.294118
72
0.59322
87482a8f0c4a92d05057328f9e7ae0391ff59080
416
# frozen_string_literal: true require "rack/ecg" log_check_results = proc do |success, checks| next if success checks.each do |check_name, check_status| next unless check_status[:status] == "error" puts "Check #{check_name} failed: #{check_status[:value]}" end end use(Rack::ECG, checks: [:git_revision, :migration_version], hook: log_check_results) run(->(_env) { [200, {}, ["Hello, World"]] })
23.111111
84
0.694712
edd4a44cdf126a76d8a0d0992de4a5fbf553046e
968
class Rgxg < Formula desc "C library and command-line tool to generate (extended) regular expressions" homepage "https://rgxg.github.io" url "https://github.com/rgxg/rgxg/releases/download/v0.1.2/rgxg-0.1.2.tar.gz" sha256 "554741f95dcc320459875c248e2cc347b99f809d9555c957d763d3d844e917c6" license "Zlib" bottle do cellar :any sha256 "37ed8cafce126a6ab77b1e367dbe2a72a68c6556569694366e16844b18071dce" => :big_sur sha256 "4a07550d93bedfa3b2ac3cb77a8484951321697ca9384d2c2a0301ea261aa954" => :catalina sha256 "b410fe9ea150e0fb52326e4f7ce6642f946098b0713c5741c64699de3f55f762" => :mojave sha256 "286318be76fc55c094da739c44176d5babd814df1e4f0462711aea283db042f5" => :high_sierra sha256 "ce534f086b07694e981db59a833fbf360004a5a1a01143d6e4231890c3f2ba18" => :x86_64_linux end def install system "./configure", "--prefix=#{prefix}" system "make", "install" end test do system bin/"rgxg", "range", "1", "10" end end
37.230769
94
0.77376
0373dff8756cc928a6d4062ee4fcfb22f3cb7635
6,324
# filename mui/control.rb #──────────────────────────────────────────────────────────────────────────── # ▶ MUI::Control # -------------------------------------------------------------------------- # Author 뮤 ([email protected]), jubin # Date 2014 # -------------------------------------------------------------------------- # Description # # 컨트롤을 담당하는 클래스입니다. #──────────────────────────────────────────────────────────────────────────── class MUI class Control def initialize(x, y, w, h) @realX = x @realY = y @x = x @y = y @width = w @height = h @enable = true @visible = true @opacity = 255 @toolTip = "" end def setParent(form) @parent = form @baseSprite = Sprite.new(form.getViewport) @baseSprite.bitmap = Bitmap.new(@width, @height) @baseSprite.x = @x @baseSprite.y = @y @realX = @x + form.getViewport.rect.x @realY = @y + form.getViewport.rect.y refresh end def setTitleParent(form) @parent = form @baseSprite = Sprite.new(form.getTitleViewport) @baseSprite.bitmap = Bitmap.new(@width, @height) @baseSprite.x = @x @baseSprite.y = @y @realX = @x + form.getTitleViewport.rect.x @realY = @y + form.getTitleViewport.rect.y refresh end # 실제 x def realX; @realX end def realX=(value) @realX = value end # 실제 y def realY; @realY end def realY=(value) @realY = value end # x def x; @x end def x=(value) @x = value @baseSprite.x = @x @realX = @parent.getViewport.rect.x + @x end # y def y; @y end def y=(value) @y = value @baseSprite.y = @y @realY = @parent.getViewport.rect.y + @y end # 너비 def width; @width end def width=(value) return if @width == value or value <= 0 @width = value return if @baseSprite.nil? @baseSprite.bitmap.dispose @baseSprite.bitmap = Bitmap.new(@width, @height) refresh end # 높이 def height; @height end def height=(value) return if @height == value or value <= 0 @height = value return if @baseSprite.nil? @baseSprite.bitmap.dispose @baseSprite.bitmap = Bitmap.new(@width, @height) refresh end # 활성화 def enable; @enable end def enable=(value) return if @enable == value return unless value.is_a?(TrueClass) or value.is_a?(FalseClass) @enable = value return if @baseSprite.nil? if @enable @baseSprite.tone.set(0, 0, 0) if @baseSprite.tone != Tone.new(0, 0, 0) else @baseSprite.tone.set(-20, -20, -20, 100) if @baseSprite.tone != Tone.new(-20, -20, -20, 100) end end # 표시 def visible; @visible end def visible=(value) return if @visible == value return unless value.is_a?(TrueClass) or value.is_a?(FalseClass) @visible = value return if @baseSprite.nil? @baseSprite.visible = value end # 투명도 def opacity; @opacity end def opacity=(value) return if @opacity == value return unless value.between?(0, 255) @opacity = value return if @baseSprite.nil? @baseSprite.opacity = value refresh end # 텍스트 라인 수 리턴 def line(width, str) return if @baseSprite.nil? return @baseSprite.bitmap.line(width, str) end def toolTip; @toolTip end def toolTip=(value) return if @toolTip == value return if @baseSprite.nil? @toolTip = value end def baseSprite; @baseSprite end # 컨트롤을 한 번 누를 때 def click(id = 0) id = 0 if not id.between?(0,2) if isSelected && Mouse.trigger?(id) && @visible Game.system.se_play(Config::DECISION_SE) return true else return false end end # 컨트롤을 꾹 누를 때 def press(id = 0) id = 0 if not id.between?(0,2) if isSelected && Mouse.press?(id) && @visible return true else return false end end # 컨트롤을 꾹 누를 때 def repeat(id) return if not @enable or not @visible end # 마우스가 컨트롤의 범위에 들어올 때 def isMouseOver x, y = Mouse.x, Mouse.y return false if (not x or not y) if @realX <= x && @realX + @width > x && @realY <= y && @realY + @height > y return true else return false end end # 컨트롤에 마우스가 올려질 때 def isSelected if isMouseOver && MUI.getFocus == @parent viewport1 = @parent.getViewport.rect viewport2 = @parent.getTitleViewport.rect # 베이스 ((x >= viewport1.x and x <= viewport1.x + viewport1.width and y >= viewport1.y and y <= viewport1.y + viewport1.height) or # 타이틀 (x >= viewport2.x and x <= viewport2.x + viewport2.width and y >= viewport2.y and y <= viewport2.y + viewport2.height)) return true end return false end # 업데이트 def update return if not @enable or not @visible return if @baseSprite.nil? end # 삭제 def dispose if not @baseSprite.nil? and @baseSprite.is_a?(Sprite) self.instance_variables.each do |v| if instance_variable_get(v).is_a?(Sprite) instance_variable_get(v).dispose instance_variable_set(v, nil) end end end end # Recter def realTimeEdit(form) if $DEBUG if Key.press?(KEY_CTRL) form.drag = false if Mouse.trigger? self.x = Mouse.x - form.x self.y = Mouse.y - form.y - form.getTitleViewport.rect.height puts "#{self.x}, #{self.y}, #{self.width}, #{self.height}" end if Key.trigger?(KEY_C) File.setClipboard(", ", self.x, self.y, self.width, self.height) end elsif Key.press?(KEY_SHIFT) form.drag = false if Mouse.trigger? x = Mouse.x - form.x - @x y = Mouse.y - form.y - form.getTitleViewport.rect.height - @y self.width = (x <= 0 ? 1 : x) self.height = (y <= 0 ? 1 : y) end else form.drag = true end end end end end
25.603239
100
0.520557
1ab882bde166a0cfd0ab27fab4351ff1b7ab017d
269
# frozen_string_literal: true require 'spec_helper' describe Gitlab::Geo::Logger do it 'uses the same log_level defined in Rails' do allow(Rails.logger).to receive(:level) { 99 } logger = described_class.build expect(logger.level).to eq(99) end end
19.214286
50
0.717472
914764a55f150bf3e107f3489a037b81820921f0
39
module Foswipe VERSION = "0.0.1" end
9.75
19
0.666667
338b1cfedcddf01834d79552a9afd4b42b85d839
3,626
# encoding: UTF-8 require 'prometheus/client' require 'prometheus/client/counter' require 'examples/metric_example' describe Prometheus::Client::Counter do # Reset the data store before do Prometheus::Client.config.data_store = Prometheus::Client::DataStores::Synchronized.new end let(:expected_labels) { [] } let(:counter) do Prometheus::Client::Counter.new(:foo, docstring: 'foo description', labels: expected_labels) end it_behaves_like Prometheus::Client::Metric do let(:type) { Float } end describe '#increment' do it 'increments the counter' do expect do counter.increment end.to change { counter.get }.by(1.0) end it 'raises an InvalidLabelSetError if sending unexpected labels' do expect do counter.increment(labels: { test: 'label' }) end.to raise_error Prometheus::Client::LabelSetValidator::InvalidLabelSetError end context "with a an expected label set" do let(:expected_labels) { [:test] } it 'increments the counter for a given label set' do expect do expect do counter.increment(labels: { test: 'label' }) end.to change { counter.get(labels: { test: 'label' }) }.by(1.0) end.to_not change { counter.get(labels: { test: 'other' }) } end it 'can pre-set labels using `with_labels`' do expect { counter.increment } .to raise_error(Prometheus::Client::LabelSetValidator::InvalidLabelSetError) expect { counter.with_labels(test: 'label').increment }.not_to raise_error end end it 'increments the counter by a given value' do expect do counter.increment(by: 5) end.to change { counter.get }.by(5.0) end it 'raises an ArgumentError on negative increments' do expect do counter.increment(by: -1) end.to raise_error ArgumentError end it 'returns the new counter value' do expect(counter.increment).to eql(1.0) end it 'is thread safe' do expect do Array.new(10) do Thread.new do 10.times { counter.increment } end end.each(&:join) end.to change { counter.get }.by(100.0) end context "with non-string label values" do subject { described_class.new(:foo, docstring: 'Labels', labels: [:foo]) } it "converts labels to strings for consistent storage" do subject.increment(labels: { foo: :label }) expect(subject.get(labels: { foo: 'label' })).to eq(1.0) end context "and some labels preset" do subject do described_class.new(:foo, docstring: 'Labels', labels: [:foo, :bar], preset_labels: { foo: :label }) end it "converts labels to strings for consistent storage" do subject.increment(labels: { bar: :label }) expect(subject.get(labels: { foo: 'label', bar: 'label' })).to eq(1.0) end end end end describe '#init_label_set' do context "with labels" do let(:expected_labels) { [:test] } it 'initializes the metric for a given label set' do expect(counter.values).to eql({}) counter.init_label_set(test: 'value') expect(counter.values).to eql({test: 'value'} => 0.0) end end context "without labels" do it 'automatically initializes the metric' do expect(counter.values).to eql({} => 0.0) end end end end
28.777778
91
0.60011
abca69da27c0fb667e2d6b9aef5cd472b78e8457
4,130
require "tmpdir" require File.expand_path("#{File.dirname(__FILE__)}/../helper") describe GChart::Base do it "can be initialized with a hash" do GChart::Base.new(:title => "foo").title.should == "foo" end it "complains about being initialized with unknown attributes" do lambda { GChart::Base.new(:monkey => :chimchim) }.should raise_error(NoMethodError) end it "can be initialized with a block" do chart = GChart::Base.new do |c| c.title = "foo" end chart.title.should == "foo" end end describe GChart::Base, "#data" do it "is an empty array by default" do GChart::Base.new.data.should == [] end end describe GChart::Base, "#size" do before(:each) { @chart = GChart::Base.new } it "can be accessed as width and height" do @chart.width.should_not be_zero @chart.height.should_not be_zero end it "can be accessed as a combined size" do @chart.size.should == "#{@chart.width}x#{@chart.height}" end it "can be specified as a combined size" do @chart.size = "11x13" @chart.width.should == 11 @chart.height.should == 13 end it "has a reasonable default value" do @chart.size.should == "300x200" end it "complains about negative numbers" do lambda { @chart.size = "-15x13" }.should raise_error(ArgumentError) lambda { @chart.width = -1 }.should raise_error(ArgumentError) lambda { @chart.height= -1 }.should raise_error(ArgumentError) end it "complains about sizes that are out of bounds (300,000 pixel graph limit, 1000 pixel side limit)" do lambda { @chart.size = "491x611" }.should raise_error(ArgumentError) lambda { @chart.size = "1001x300" }.should raise_error(ArgumentError) lambda { @chart.size = "300x1001" }.should raise_error(ArgumentError) end end describe GChart::Base, "#render_chart_type" do it "raises; subclasses must implement" do lambda { GChart::Base.new.render_chart_type }.should raise_error(NotImplementedError) end end describe GChart::Base, "#query_params" do before(:each) do @chart = GChart::Base.new @chart.stub!(:render_chart_type).and_return("TEST") end it "contains the chart's type" do @chart.query_params["cht"].should == "TEST" end it "contains the chart's data" do @chart.data = [[1, 2, 3], [3, 2, 1]] @chart.query_params["chd"].should == "e:VVqq..,..qqVV" end it "contains the chart's size" do @chart.query_params["chs"].should == "300x200" end it "contains the chart's title" do @chart.title = "foo" @chart.query_params["chtt"].should == "foo" end it "escapes the chart's title" do @chart.title = "foo bar" @chart.query_params["chtt"].should == "foo+bar" @chart.title = "foo\nbar" @chart.query_params["chtt"].should == "foo|bar" end it "contains the chart's colors" do @chart.colors = ["cccccc", "eeeeee"] @chart.query_params["chco"].should == "cccccc,eeeeee" end end describe GChart::Base, "#to_url" do before(:each) do @chart = GChart::Base.new @chart.stub!(:render_chart_type).and_return("TEST") end it "generates a URL that points at Google" do @chart.to_url.should =~ %r(http://chart.apis.google.com/chart) end end describe GChart::Base, "#fetch" do # THIS EXPECTATION HITS THE CLOUD! Comment it out for a faster cycle. :) it "fetches a blob from Google" do blob = GChart.line(:data => [1, 2]).fetch blob.should_not be_nil blob.should =~ /PNG/ end end describe GChart::Base, "#write" do before(:each) do @chart = GChart::Base.new @chart.stub!(:fetch).and_return("PAYLOAD") end it "writes to chart.png by default" do Dir.chdir(Dir.tmpdir) do @chart.write File.file?("chart.png").should == true end end it "writes to a specified file" do Dir.chdir(Dir.tmpdir) do @chart.write("foo.png") File.file?("foo.png").should == true end end it "writes to anything that quacks like IO" do result = "" StringIO.open(result, "w+") do |io| @chart.write(io) end result.should == "PAYLOAD" end end
26.305732
105
0.651574
d55eec377b176f38dae30610e81e4c95031537cf
137
# # Cookbook Name:: compression # Recipe:: default # # Copyright 2016, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute #
15.222222
43
0.729927
e2eb5b40e250efa9c4eabaaa304bf83add1b6a7b
100
require "omniauth-ldap/version" require "omniauth-ldap/adaptor" require 'omniauth/strategies/ldap'
20
34
0.81
878fd34cbe072aa0dbdbeaf55100223906d6a28b
983
# frozen_string_literal: true require "event_source/protocols/http/contracts/publish_operation_bindings_contract" require "event_source/protocols/amqp/contracts/publish_operation_binding_contract" module EventSource module AsyncApi module Contracts # Schema and validation rules for publish bindings class PublishOperationBindingsContract < Contract params do optional(:http).hash optional(:amqp).hash end rule(:http) do if key? && value validation_result = ::EventSource::Protocols::Http::Contracts::PublishOperationBindingsContract.new.call(value) if validation_result&.failure? key.failure( text: 'invalid operation bindings', error: validation_result.errors.to_h ) else values.data.merge({ http: validation_result.values }) end end end end end end end
29.787879
123
0.639878
b999335dd65f865ad271b6793afc5924afd09c08
1,774
require 'watirspec_helper' describe 'TableFooters' do before :each do browser.goto(WatirSpec.url_for('tables.html')) end describe 'with selectors' do it 'returns the matching elements' do expect(browser.tfoots(id: 'tax_totals').to_a).to eq [browser.tfoot(id: 'tax_totals')] end end describe '#length' do it 'returns the correct number of table tfoots (page context)' do expect(browser.tfoots.length).to eq 1 end it 'returns the correct number of table tfoots (table context)' do expect(browser.table(index: 0).tfoots.length).to eq 1 end end describe '#[]' do it 'returns the row at the given index (page context)' do expect(browser.tfoots[0].id).to eq 'tax_totals' end it 'returns the row at the given index (table context)' do expect(browser.table(index: 0).tfoots[0].id).to eq 'tax_totals' end end describe '#each' do it 'iterates through table tfoots correctly (page context)' do browser.tfoots.each_with_index do |tfoot, index| expect(tfoot.id).to eq browser.tfoot(index: index).id end end describe '#each' do it 'iterates through table tfoots correctly (page context)' do count = 0 browser.tfoots.each_with_index do |tfoot, index| expect(tfoot.id).to eq browser.tfoot(index: index).id count += 1 end expect(count).to be > 0 end it 'iterates through table tfoots correctly (table context)' do table = browser.table(index: 0) count = 0 table.tfoots.each_with_index do |tfoot, index| expect(tfoot.id).to eq table.tfoot(index: index).id count += 1 end expect(count).to be > 0 end end end end
25.710145
91
0.637542
ed350f016dbfa6d325ddc0eb329bb5a951952eaf
482
Pod::Spec.new do |s| s.name = "pugixml" s.version = "1.11" s.summary = "C++ XML parser library." s.homepage = "https://pugixml.org" s.license = "MIT" s.author = { "Arseny Kapoulkine" => "[email protected]" } s.platform = :ios, "7.0" s.source = { :git => "https://github.com/zeux/pugixml.git", :tag => "v" + s.version.to_s } s.source_files = "src/**/*.{hpp,cpp}" s.header_mappings_dir = "src" end
32.133333
93
0.537344
f78842de6fba869fc29931bdc7e3907844d09beb
259
module Nurego class InvalidRequestError < NuregoError attr_accessor :param def initialize(message, param, http_status=nil, http_body=nil, json_body=nil) super(message, http_status, http_body, json_body) @param = param end end end
23.545455
81
0.725869
389f0125d2cbc940d43b35607a68d4a7c4c1b22e
5,904
# encoding: ASCII-8BIT require 'common' require 'net/ssh/transport/state' module Transport class TestState < NetSSHTest def setup @socket = @state = @deflater = @inflater = nil end def teardown if @deflater @deflater.finish if [email protected]? @deflater.close end if @inflater @inflater.finish if [email protected]? @inflater.close end state.cleanup end def test_constructor_should_initialize_all_values assert_equal 0, state.sequence_number assert_equal 0, state.packets assert_equal 0, state.blocks assert_nil state.compression assert_nil state.compression_level assert_nil state.max_packets assert_nil state.max_blocks assert_nil state.rekey_limit assert_equal "identity", state.cipher.name assert_instance_of Net::SSH::Transport::HMAC::None, state.hmac end def test_increment_should_increment_counters state.increment(24) assert_equal 1, state.sequence_number assert_equal 1, state.packets assert_equal 3, state.blocks end def test_reset_should_reset_counters_and_fix_defaults_for_maximums state.increment(24) state.reset! assert_equal 1, state.sequence_number assert_equal 0, state.packets assert_equal 0, state.blocks assert_equal 2147483648, state.max_packets assert_equal 134217728, state.max_blocks end def test_set_should_set_variables_and_reset_counters state.expects(:reset!) state.set cipher: :a, hmac: :b, compression: :c, compression_level: :d, max_packets: 500, max_blocks: 1000, rekey_limit: 1500 assert_equal :a, state.cipher assert_equal :b, state.hmac assert_equal :c, state.compression assert_equal :d, state.compression_level assert_equal 500, state.max_packets assert_equal 1000, state.max_blocks assert_equal 1500, state.rekey_limit end def test_set_with_max_packets_should_respect_max_packets_setting state.set max_packets: 500 assert_equal 500, state.max_packets end def test_set_with_max_blocks_should_respect_max_blocks_setting state.set max_blocks: 1000 assert_equal 1000, state.max_blocks end def test_set_with_rekey_limit_should_include_rekey_limit_in_computation_of_max_blocks state.set rekey_limit: 4000 assert_equal 500, state.max_blocks end def test_compressor_defaults_to_default_zlib_compression expect = deflater.deflate("hello world") assert_equal expect, state.compressor.deflate("hello world") end def test_compressor_uses_compression_level_when_given state.set compression_level: 1 expect = deflater(1).deflate("hello world") assert_equal expect, state.compressor.deflate("hello world") end def test_compress_when_no_compression_is_active_returns_text assert_equal "hello everybody", state.compress("hello everybody") end def test_decompress_when_no_compression_is_active_returns_text assert_equal "hello everybody", state.decompress("hello everybody") end def test_compress_when_compression_is_delayed_and_no_auth_hint_is_set_should_return_text state.set compression: :delayed assert_equal "hello everybody", state.compress("hello everybody") end def test_decompress_when_compression_is_delayed_and_no_auth_hint_is_set_should_return_text state.set compression: :delayed assert_equal "hello everybody", state.decompress("hello everybody") end def test_compress_when_compression_is_enabled_should_return_compressed_text state.set compression: :standard # JRuby Zlib implementation (1.4 & 1.5) does not have byte-to-byte compatibility with MRI's. # skip this test under JRuby. return if defined?(JRUBY_VERSION) assert_equal "x\234\312H\315\311\311WH-K-\252L\312O\251\004\000\000\000\377\377", state.compress("hello everybody") end def test_decompress_when_compression_is_enabled_should_return_decompressed_text state.set compression: :standard # JRuby Zlib implementation (1.4 & 1.5) does not have byte-to-byte compatibility with MRI's. # skip this test under JRuby. return if defined?(JRUBY_VERSION) assert_equal "hello everybody", state.decompress("x\234\312H\315\311\311WH-K-\252L\312O\251\004\000\000\000\377\377") end def test_compress_when_compression_is_delayed_and_auth_hint_is_set_should_return_compressed_text socket.hints[:authenticated] = true state.set compression: :delayed assert_equal "x\234\312H\315\311\311WH-K-\252L\312O\251\004\000\000\000\377\377", state.compress("hello everybody") end def test_decompress_when_compression_is_delayed_and_auth_hint_is_set_should_return_decompressed_text socket.hints[:authenticated] = true state.set compression: :delayed assert_equal "hello everybody", state.decompress("x\234\312H\315\311\311WH-K-\252L\312O\251\004\000\000\000\377\377") end def test_needs_rekey_should_be_true_if_packets_exceeds_max_packets state.set max_packets: 2 state.increment(8) state.increment(8) assert !state.needs_rekey? state.increment(8) assert state.needs_rekey? end def test_needs_rekey_should_be_true_if_blocks_exceeds_max_blocks state.set max_blocks: 10 assert !state.needs_rekey? state.increment(88) assert state.needs_rekey? end private def deflater(level=Zlib::DEFAULT_COMPRESSION) @deflater ||= Zlib::Deflate.new(level) end def inflater @inflater ||= Zlib::Inflate.new(nil) end def socket @socket ||= stub("socket", hints: {}) end def state @state ||= Net::SSH::Transport::State.new(socket, :test) end end end
32.618785
123
0.726287
ffd4495abb295b3bb0a415cc0ec781372312ebe8
1,064
class CmakeFormat < Formula include Language::Python::Virtualenv desc 'Source code formatter for cmake listfiles.' homepage 'https://github.com/cheshirekow/cmake_format' url 'https://files.pythonhosted.org/packages/4a/40/0ca7c62dc4b9af58ca32da8e6d87ee222f5bb551c17ef22900b2f81b998e/cmake_format-0.6.13-py3-none-any.whl' sha256 'ec7ed949101e5f0b7bc19317d122b83ccbc28fd766c41c93094845719667c56e' license 'GPL-3.0' livecheck do url :stable end depends_on '[email protected]' def install # FIXME: direct to use virtualenv_install_with_resources # virtualenv_install_with_resources venv = virtualenv_create(libexec, 'python3.9') bin_before = Dir[libexec / 'bin/*'].to_set system libexec / 'bin/pip', 'install', '-v', '--ignore-installed', 'cmake_format-0.6.13-py3-none-any.whl' bin_after = Dir[libexec / 'bin/*'].to_set bin.install_symlink((bin_after - bin_before).to_a) venv end test do output = shell_output("#{bin}/cmake-format --version") assert_equal '0.6.13', output.strip end end
29.555556
151
0.726504
61ba35ce35c0fe7f65e5e56cbc2bc26cdffccdb4
296
$LOAD_PATH.unshift File.expand_path('../lib', __dir__) require 'nothing' require 'something/native_vm/compiled' include Nothing include Something::NativeVM::Compiled include Something::NativeVM::Compiled::Translation each_element(from_proc(FIZZBUZZ)) do |element| puts to_string(element) end
24.666667
54
0.804054
3390addb2e3125eda0c8516e5c95845432fac8a0
221
class AddAttachmentPhotoToMessages < ActiveRecord::Migration[5.1] def self.up change_table :messages do |t| t.attachment :photo end end def self.down remove_attachment :messages, :photo end end
18.416667
65
0.710407
6a7be8c8ed16a583bfdadd89f7efd417b6ee558b
869
$LOAD_PATH.unshift(File.dirname(__FILE__)) unless $LOAD_PATH.include?(File.dirname(__FILE__)) || $LOAD_PATH.include?(File.expand_path(File.dirname(__FILE__))) require 'open-uri' require 'rubygems' require 'nokogiri' module Imdb # akas.imdb.com doesn't return original language anymore. # www.imdb.com returns 'Die Verurteilten' for 'The Shawshank Redemption' in Germany. # This header is needed to disable localizing. # use_it with open-uri's open or `curl` HTTP_HEADER = { 'Accept-Language' => 'en-US;en' }.freeze HTTP_PROTOCOL = 'https'.freeze end require 'imdb/util' require 'imdb/base' require 'imdb/movie' require 'imdb/person' require 'imdb/serie' require 'imdb/season' require 'imdb/episode' require 'imdb/movie_list' require 'imdb/search' require 'imdb/top_250' require 'imdb/box_office' require 'imdb/string_extensions' require 'imdb/version'
28.966667
110
0.757192
28bd3625b02fad9445a8357bf77f852189247e0a
81,120
# Default Ruby Record Separator # Used in this file and by various methods that need to ignore $/ DEFAULT_RECORD_SEPARATOR = "\n" class String include Comparable include Enumerable attr_accessor :data attr_accessor :num_bytes attr_accessor :characters def self.allocate str = super() str.data = Rubinius::ByteArray.new(1) str.num_bytes = 0 str.characters = 0 str end ## # Creates a new string from copying _count_ bytes from the # _start_ of _ba_. def self.from_bytearray(ba, start, count) Ruby.primitive :string_from_bytearray raise PrimitiveFailure, "String.from_bytearray primitive failed" end def initialize(arg = undefined) replace StringValue(arg) unless arg == undefined self end private :initialize # call-seq: # str % arg => new_str # # Format---Uses <i>self</i> as a format specification, and returns the result # of applying it to <i>arg</i>. If the format specification contains more than # one substitution, then <i>arg</i> must be an <code>Array</code> containing # the values to be substituted. See <code>Kernel::sprintf</code> for details # of the format string. # # "%05d" % 123 #=> "00123" # "%-5s: %08x" % [ "ID", self.id ] #=> "ID : 200e14d6" def %(args) if args.is_a? String # Fixes "%s" % "" Rubinius::Sprintf.new(self, args).parse else Rubinius::Sprintf.new(self, *args).parse end end # call-seq: # str * integer => new_str # # Copy --- Returns a new <code>String</code> containing <i>integer</i> copies of # the receiver. # # "Ho! " * 3 #=> "Ho! Ho! Ho! " def *(num) num = Type.coerce_to(num, Integer, :to_int) unless num.is_a? Integer raise RangeError, "bignum too big to convert into `long' (#{num})" if num.is_a? Bignum raise ArgumentError, "unable to multiple negative times (#{num})" if num < 0 str = self.class.pattern num * @num_bytes, self return str end # Concatenation --- Returns a new <code>String</code> containing # <i>other</i> concatenated to <i>string</i>. # # "Hello from " + self.to_s #=> "Hello from main" def +(other) r = "#{self}#{StringValue(other)}" r.taint if self.tainted? or other.tainted? r end # Append --- Concatenates the given object to <i>self</i>. If the object is a # <code>Fixnum</code> between 0 and 255, it is converted to a character before # concatenation. # # a = "hello " # a << "world" #=> "hello world" # a.concat(33) #=> "hello world!" def <<(other) modify! unless other.kind_of? String if other.is_a?(Integer) && other >= 0 && other <= 255 other = other.chr else other = StringValue(other) end end self.taint if other.tainted? self.append(other) end alias_method :concat, :<< # call-seq: # str <=> other_str => -1, 0, +1 # # Comparison --- Returns -1 if <i>other_str</i> is less than, 0 if # <i>other_str</i> is equal to, and +1 if <i>other_str</i> is greater than # <i>self</i>. If the strings are of different lengths, and the strings are # equal when compared up to the shortest length, then the longer string is # considered greater than the shorter one. If the variable <code>$=</code> is # <code>false</code>, the comparison is based on comparing the binary values # of each character in the string. In older versions of Ruby, setting # <code>$=</code> allowed case-insensitive comparisons; this is now deprecated # in favor of using <code>String#casecmp</code>. # # <code><=></code> is the basis for the methods <code><</code>, # <code><=</code>, <code>></code>, <code>>=</code>, and <code>between?</code>, # included from module <code>Comparable</code>. The method # <code>String#==</code> does not use <code>Comparable#==</code>. # # "abcdef" <=> "abcde" #=> 1 # "abcdef" <=> "abcdef" #=> 0 # "abcdef" <=> "abcdefg" #=> -1 # "abcdef" <=> "ABCDEF" #=> 1 def <=>(other) if other.kind_of?(String) @data.compare_bytes(other.data, @num_bytes, other.size) else return unless other.respond_to?(:to_str) && other.respond_to?(:<=>) return unless tmp = (other <=> self) return -tmp # We're not supposed to convert to integer here end end # call-seq: # str == obj => true or false # # Equality---If <i>obj</i> is not a <code>String</code>, returns # <code>false</code>. Otherwise, returns <code>true</code> if <i>self</i> # <code><=></code> <i>obj</i> returns zero. #--- # TODO: MRI does simply use <=> for Strings here, so what's this code about? #+++ def ==(other) Ruby.primitive :string_equal # Use #=== rather than #kind_of? because other might redefine kind_of? unless String === other if other.respond_to?(:to_str) return other == self end return false end return false unless @num_bytes == other.size return @data.compare_bytes(other.data, @num_bytes, other.size) == 0 end # Match --- If <i>pattern</i> is a <code>Regexp</code>, use it as a pattern to match # against <i>self</i>, and return the position the match starts, or # <code>nil</code> if there is no match. Otherwise, invoke # <i>pattern.=~</i>, passing <i>self</i> as an argument. # # The default <code>=~</code> in <code>Object</code> returns <code>false</code>. # # "cat o' 9 tails" =~ /\d/ #=> 7 # "cat o' 9 tails" =~ 9 #=> false def =~(pattern) case pattern when Regexp if m = pattern.match_from(self, 0) Regexp.last_match = m return m.begin(0) end Regexp.last_match = nil return nil when String raise TypeError, "type mismatch: String given" else pattern =~ self end end # call-seq: # str[fixnum] => fixnum or nil # str[fixnum, fixnum] => new_str or nil # str[range] => new_str or nil # str[regexp] => new_str or nil # str[regexp, fixnum] => new_str or nil # str[other_str] => new_str or nil # str.slice(fixnum) => fixnum or nil # str.slice(fixnum, fixnum) => new_str or nil # str.slice(range) => new_str or nil # str.slice(regexp) => new_str or nil # str.slice(regexp, fixnum) => new_str or nil # str.slice(other_str) => new_str or nil # # Element Reference --- If passed a single <code>Fixnum</code>, returns the code # of the character at that position. If passed two <code>Fixnum</code> # objects, returns a substring starting at the offset given by the first, and # a length given by the second. If given a range, a substring containing # characters at offsets given by the range is returned. In all three cases, if # an offset is negative, it is counted from the end of <i>self</i>. Returns # <code>nil</code> if the initial offset falls outside the string, the length # is negative, or the beginning of the range is greater than the end. # # If a <code>Regexp</code> is supplied, the matching portion of <i>self</i> is # returned. If a numeric parameter follows the regular expression, that # component of the <code>MatchData</code> is returned instead. If a # <code>String</code> is given, that string is returned if it occurs in # <i>self</i>. In both cases, <code>nil</code> is returned if there is no # match. # # a = "hello there" # a[1] #=> 101 # a[1,3] #=> "ell" # a[1..3] #=> "ell" # a[-3,2] #=> "er" # a[-4..-2] #=> "her" # a[12..-1] #=> nil # a[-2..-4] #=> "" # a[/[aeiou](.)\1/] #=> "ell" # a[/[aeiou](.)\1/, 0] #=> "ell" # a[/[aeiou](.)\1/, 1] #=> "l" # a[/[aeiou](.)\1/, 2] #=> nil # a["lo"] #=> "lo" # a["bye"] #=> nil def [](index, other = undefined) unless other.equal?(undefined) length = Type.coerce_to(other, Fixnum, :to_int) if index.kind_of? Regexp match, str = subpattern(index, length) Regexp.last_match = match return str else start = Type.coerce_to(index, Fixnum, :to_int) return substring(start, length) end end case index when Regexp match, str = subpattern(index, 0) Regexp.last_match = match return str when String return include?(index) ? index.dup : nil when Range start = Type.coerce_to index.first, Fixnum, :to_int length = Type.coerce_to index.last, Fixnum, :to_int start += @num_bytes if start < 0 length += @num_bytes if length < 0 length += 1 unless index.exclude_end? return "" if start == @num_bytes return nil if start < 0 || start > @num_bytes length = @num_bytes if length > @num_bytes length = length - start length = 0 if length < 0 return substring(start, length) # A really stupid case hit for rails. Either we define this or we define # Symbol#to_int. We removed Symbol#to_int in late 2007 because it's evil, # and do not want to re add it. when Symbol return nil else index = Type.coerce_to index, Fixnum, :to_int index = @num_bytes + index if index < 0 return if index < 0 || @num_bytes <= index return @data[index] end end alias_method :slice, :[] # call-seq: # str[fixnum] = fixnum # str[fixnum] = new_str # str[fixnum, fixnum] = new_str # str[range] = aString # str[regexp] = new_str # str[regexp, fixnum] = new_str # str[other_str] = new_str # # Element Assignment --- Replaces some or all of the content of <i>self</i>. The # portion of the string affected is determined using the same criteria as # <code>String#[]</code>. If the replacement string is not the same length as # the text it is replacing, the string will be adjusted accordingly. If the # regular expression or string is used as the index doesn't match a position # in the string, <code>IndexError</code> is raised. If the regular expression # form is used, the optional second <code>Fixnum</code> allows you to specify # which portion of the match to replace (effectively using the # <code>MatchData</code> indexing rules. The forms that take a # <code>Fixnum</code> will raise an <code>IndexError</code> if the value is # out of range; the <code>Range</code> form will raise a # <code>RangeError</code>, and the <code>Regexp</code> and <code>String</code> # forms will silently ignore the assignment. def []=(one, two, three=undefined) unless three.equal? undefined if one.is_a? Regexp subpattern_set one, Type.coerce_to(two, Integer, :to_int), three else start = Type.coerce_to(one, Integer, :to_int) fin = Type.coerce_to(two, Integer, :to_int) splice! start, fin, three end return three end index = one replacement = two case index when Regexp subpattern_set index, 0, replacement when String unless start = self.index(index) raise IndexError, "string not matched" end splice! start, index.length, replacement when Range start = Type.coerce_to(index.first, Integer, :to_int) length = Type.coerce_to(index.last, Integer, :to_int) start += @num_bytes if start < 0 # TODO: this is wrong return nil if start < 0 || start > @num_bytes length = @num_bytes if length > @num_bytes length += @num_bytes if length < 0 length += 1 unless index.exclude_end? length = length - start length = 0 if length < 0 splice! start, length, replacement else index = Type.coerce_to(index, Integer, :to_int) raise IndexError, "index #{index} out of string" if @num_bytes <= index if index < 0 raise IndexError, "index #{index} out of string" if -index > @num_bytes index += @num_bytes end if replacement.is_a?(Fixnum) modify! @data[index] = replacement else splice! index, 1, replacement end end return replacement end alias_method :bytesize, :length # Returns a copy of <i>self</i> with the first character converted to uppercase # and the remainder to lowercase. # Note: case conversion is effective only in ASCII region. # # "hello".capitalize #=> "Hello" # "HELLO".capitalize #=> "Hello" # "123ABC".capitalize #=> "123abc" def capitalize return dup if @num_bytes == 0 str = transform(CType::Lowered, true) str = self.class.new(str) unless instance_of?(String) str.modify! str.data.first_capitalize! return str end # Modifies <i>self</i> by converting the first character to uppercase and the # remainder to lowercase. Returns <code>nil</code> if no changes are made. # Note: case conversion is effective only in ASCII region. # # a = "hello" # a.capitalize! #=> "Hello" # a #=> "Hello" # a.capitalize! #=> nil def capitalize! Ruby.check_frozen cap = capitalize() return nil if cap == self replace(cap) return self end # Case-insensitive version of <code>String#<=></code>. # # "abcdef".casecmp("abcde") #=> 1 # "aBcDeF".casecmp("abcdef") #=> 0 # "abcdef".casecmp("abcdefg") #=> -1 # "abcdef".casecmp("ABCDEF") #=> 0 def casecmp(to) order = @num_bytes - to.num_bytes size = order < 0 ? @num_bytes : to.num_bytes i = 0 while i < size a = @data[i] b = to.data[i] i += 1 r = a - b next if r == 0 if (a.islower or a.isupper) and (b.islower or b.isupper) r += r < 0 ? ?\s : -?\s end next if r == 0 return -1 if r < 0 return 1 end return 0 if order == 0 return -1 if order < 0 return 1 end # If <i>integer</i> is greater than the length of <i>self</i>, returns a new # <code>String</code> of length <i>integer</i> with <i>self</i> centered and # padded with <i>padstr</i>; otherwise, returns <i>self</i>. # # "hello".center(4) #=> "hello" # "hello".center(20) #=> " hello " # "hello".center(20, '123') #=> "1231231hello12312312" def center(width, padstr = " ") justify(width, :center, padstr) end # Returns a new <code>String</code> with the given record separator removed # from the end of <i>self</i> (if present). If <code>$/</code> has not been # changed from the default Ruby record separator, then <code>chomp</code> also # removes carriage return characters (that is it will remove <code>\n</code>, # <code>\r</code>, and <code>\r\n</code>). # # "hello".chomp #=> "hello" # "hello\n".chomp #=> "hello" # "hello\r\n".chomp #=> "hello" # "hello\n\r".chomp #=> "hello\n" # "hello\r".chomp #=> "hello" # "hello \n there".chomp #=> "hello \n there" # "hello".chomp("llo") #=> "he" def chomp(separator = $/) (str = self.dup).chomp!(separator) || str end # Modifies <i>self</i> in place as described for <code>String#chomp</code>, # returning <i>self</i>, or <code>nil</code> if no modifications were made. #--- # NOTE: TypeError is raised in String#replace and not in String#chomp! when # self is frozen. This is intended behaviour. #+++ def chomp!(sep = $/) return if sep.nil? || @num_bytes == 0 sep = StringValue sep if (sep == $/ && sep == DEFAULT_RECORD_SEPARATOR) || sep == "\n" c = @data[@num_bytes-1] if c == ?\n @num_bytes -= 1 if @num_bytes > 1 && @data[@num_bytes-2] == ?\r elsif c != ?\r return end modify! @num_bytes = @characters = @num_bytes - 1 elsif sep.size == 0 size = @num_bytes while size > 0 && @data[size-1] == ?\n if size > 1 && @data[size-2] == ?\r size -= 2 else size -= 1 end end return if size == @num_bytes modify! @num_bytes = @characters = size else size = sep.size return if size > @num_bytes || sep.compare_substring(self, -size, size) != 0 modify! @num_bytes = @characters = @num_bytes - size end return self end # Returns a new <code>String</code> with the last character removed. If the # string ends with <code>\r\n</code>, both characters are removed. Applying # <code>chop</code> to an empty string returns an empty # string. <code>String#chomp</code> is often a safer alternative, as it leaves # the string unchanged if it doesn't end in a record separator. # # "string\r\n".chop #=> "string" # "string\n\r".chop #=> "string\n" # "string\n".chop #=> "string" # "string".chop #=> "strin" # "x".chop.chop #=> "" def chop (str = self.dup).chop! || str end # Processes <i>self</i> as for <code>String#chop</code>, returning <i>self</i>, # or <code>nil</code> if <i>self</i> is the empty string. See also # <code>String#chomp!</code>. def chop! return if @num_bytes == 0 self.modify! if @num_bytes > 1 and @data[@num_bytes-1] == ?\n and @data[@num_bytes-2] == ?\r then @num_bytes = @characters = @num_bytes - 2 else @num_bytes = @characters = @num_bytes - 1 end self end # Each <i>other_string</i> parameter defines a set of characters to count. The # intersection of these sets defines the characters to count in # <i>self</i>. Any <i>other_str</i> that starts with a caret (^) is # negated. The sequence c1--c2 means all characters between c1 and c2. # # a = "hello world" # a.count "lo" #=> 5 # a.count "lo", "o" #=> 2 # a.count "hello", "^l" #=> 4 # a.count "ej-m" #=> 4 def count(*strings) raise ArgumentError, "wrong number of Arguments" if strings.empty? return 0 if @num_bytes == 0 table = count_table(*strings).data count = i = 0 while i < @num_bytes count += 1 if table[@data[i]] == 1 i += 1 end count end # Applies a one-way cryptographic hash to <i>self</i> by invoking the standard # library function <code>crypt</code>. The argument is the salt string, which # should be two characters long, each character drawn from # <code>[a-zA-Z0-9./]</code>. def crypt(other_str) other_str = StringValue(other_str) raise ArgumentError.new("salt must be at least 2 characters") if other_str.size < 2 hash = __crypt__(other_str) hash.taint if self.tainted? || other_str.tainted? hash end # Returns a copy of <i>self</i> with all characters in the intersection of its # arguments deleted. Uses the same rules for building the set of characters as # <code>String#count</code>. # # "hello".delete "l","lo" #=> "heo" # "hello".delete "lo" #=> "he" # "hello".delete "aeiou", "^e" #=> "hell" # "hello".delete "ej-m" #=> "ho" def delete(*strings) (str = self.dup).delete!(*strings) || str end # Performs a <code>delete</code> operation in place, returning <i>self</i>, or # <code>nil</code> if <i>self</i> was not modified. def delete!(*strings) raise ArgumentError, "wrong number of arguments" if strings.empty? self.modify! table = count_table(*strings).data i, j = 0, -1 while i < @num_bytes c = @data[i] unless table[c] == 1 @data[j+=1] = c end i += 1 end if (j += 1) < @num_bytes @num_bytes = j self else nil end end # Returns a copy of <i>self</i> with all uppercase letters replaced with their # lowercase counterparts. The operation is locale insensitive---only # characters ``A'' to ``Z'' are affected. # # "hEllO".downcase #=> "hello" def downcase return dup if @num_bytes == 0 str = transform(CType::Lowered, true) str = self.class.new(str) unless instance_of?(String) return str end # Downcases the contents of <i>self</i>, returning <code>nil</code> if no # changes were made. def downcase! Ruby.check_frozen return if @num_bytes == 0 str = transform(CType::Lowered, true) return nil if str == self replace(str) return self end def each_char(&block) return to_enum :each_char unless block_given? return scan(/./u, &block) if Rubinius.kcode == :UTF8 i = 0 while i < @num_bytes do yield @data.get_byte(i).chr i += 1 end self end alias_method :chars, :each_char # Passes each byte in <i>self</i> to the given block. # # "hello".each_byte {|c| print c, ' ' } # # <em>produces:</em> # # 104 101 108 108 111 def each_byte return to_enum :each_byte unless block_given? i = 0 while i < @num_bytes do yield @data.get_byte(i) i += 1 end self end alias_method :bytes, :each_byte # Splits <i>self</i> using the supplied parameter as the record separator # (<code>$/</code> by default), passing each substring in turn to the supplied # block. If a zero-length record separator is supplied, the string is split on # <code>\n</code> characters, except that multiple successive newlines are # appended together. # # print "Example one\n" # "hello\nworld".each {|s| p s} # print "Example two\n" # "hello\nworld".each('l') {|s| p s} # print "Example three\n" # "hello\n\n\nworld".each('') {|s| p s} # # <em>produces:</em> # # Example one # "hello\n" # "world" # Example two # "hel" # "l" # "o\nworl" # "d" # Example three # "hello\n\n\n" # "world" def each_line(sep=$/) return to_enum(:each_line, sep) unless block_given? # weird edge case. if sep.nil? yield self return self end sep = StringValue(sep) pos = 0 size = @num_bytes orig_data = @data # If the seperator is empty, we're actually in paragraph mode. This # is used so infrequently, we'll handle it completely seperately from # normal line breaking. if sep.empty? sep = "\n\n" pat_size = 2 while pos < size nxt = find_string(sep, pos) break unless nxt while @data[nxt] == ?\n and nxt < @num_bytes nxt += 1 end match_size = nxt - pos # string ends with \n's break if pos == @num_bytes str = substring(pos, match_size) yield str unless str.empty? # detect mutation within the block if [email protected]?(orig_data) or @num_bytes != size raise RuntimeError, "string modified while iterating" end pos = nxt end # No more seperates, but we need to grab the last part still. fin = substring(pos, @num_bytes - pos) yield fin if fin and !fin.empty? else # This is the normal case. pat_size = sep.size while pos < size nxt = find_string(sep, pos) break unless nxt match_size = nxt - pos str = substring(pos, match_size + pat_size) yield str unless str.empty? # detect mutation within the block if [email protected]?(orig_data) or @num_bytes != size raise RuntimeError, "string modified while iterating" end pos = nxt + pat_size end # No more seperates, but we need to grab the last part still. fin = substring(pos, @num_bytes - pos) yield fin unless fin.empty? end self end alias_method :each, :each_line alias_method :lines, :each_line # Returns <code>true</code> if <i>self</i> has a length of zero. # # "hello".empty? #=> false # "".empty? #=> true def empty? @num_bytes == 0 end def end_with?(*suffixes) suffixes.each do |suffix| next unless suffix.respond_to? :to_str suffix = suffix.to_str return true if self[-suffix.length, suffix.length] == suffix end false end # Two strings are equal if the have the same length and content. def eql?(other) Ruby.primitive :string_equal return false unless other.is_a?(String) && other.size == @num_bytes (@data.fetch_bytes(0, @num_bytes) <=> other.data.fetch_bytes(0, @num_bytes)) == 0 end # Returns a copy of <i>self</i> with <em>all</em> occurrences of <i>pattern</i> # replaced with either <i>replacement</i> or the value of the block. The # <i>pattern</i> will typically be a <code>Regexp</code>; if it is a # <code>String</code> then no regular expression metacharacters will be # interpreted (that is <code>/\d/</code> will match a digit, but # <code>'\d'</code> will match a backslash followed by a 'd'). # # If a string is used as the replacement, special variables from the match # (such as <code>$&</code> and <code>$1</code>) cannot be substituted into it, # as substitution into the string occurs before the pattern match # starts. However, the sequences <code>\1</code>, <code>\2</code>, and so on # may be used to interpolate successive groups in the match. # # In the block form, the current match string is passed in as a parameter, and # variables such as <code>$1</code>, <code>$2</code>, <code>$`</code>, # <code>$&</code>, and <code>$'</code> will be set appropriately. The value # returned by the block will be substituted for the match on each call. # # The result inherits any tainting in the original string or any supplied # replacement string. # # "hello".gsub(/[aeiou]/, '*') #=> "h*ll*" # "hello".gsub(/([aeiou])/, '<\1>') #=> "h<e>ll<o>" # "hello".gsub(/./) {|s| s[0].to_s + ' '} #=> "104 101 108 108 111 " def gsub(pattern, replacement=undefined) unless block_given? or replacement != undefined return to_enum :gsub, pattern, replacement end tainted = false unless replacement == undefined tainted = replacement.tainted? replacement = StringValue(replacement) tainted ||= replacement.tainted? end pattern = get_pattern(pattern, true) copy = self.dup last_end = 0 offset = nil ret = substring(0,0) # Empty string and string subclass last_match = nil match = pattern.match_from self, last_end offset = match.begin 0 if match while match if str = match.pre_match_from(last_end) ret.append str end if replacement == undefined Regexp.last_match = match val = yield(match[0]).to_s tainted ||= val.tainted? ret.append val raise RuntimeError, "string modified" if self != copy else ret.append replacement.to_sub_replacement(match) end tainted ||= val.tainted? last_end = match.end(0) if match.collapsing? if char = find_character(offset) offset += char.size else offset += 1 end else offset = match.end(0) end last_match = match match = pattern.match_from self, offset break unless match offset = match.begin 0 end Regexp.last_match = last_match str = substring(last_end, @num_bytes-last_end+1) ret.append str if str ret.taint if tainted || self.tainted? return ret end # Performs the substitutions of <code>String#gsub</code> in place, returning # <i>self</i>, or <code>nil</code> if no substitutions were performed. def gsub!(pattern, replacement=undefined) # Because of the behavior of $~, this is duplicated from gsub! because # if we call gsub! from gsub, the last_match can't be updated properly. unless block_given? or replacement != undefined return to_enum :gsub, pattern, replacement end tainted = false unless replacement == undefined tainted = replacement.tainted? replacement = StringValue(replacement) tainted ||= replacement.tainted? end pattern = get_pattern(pattern, true) copy = self.dup last_end = 0 offset = nil ret = substring(0,0) # Empty string and string subclass last_match = nil match = pattern.match_from self, last_end offset = match.begin 0 if match while match if str = match.pre_match_from(last_end) ret.append str end if replacement == undefined Regexp.last_match = match val = yield(match[0]).to_s tainted ||= val.tainted? ret.append val raise RuntimeError, "string modified" if self != copy else ret.append replacement.to_sub_replacement(match) end tainted ||= val.tainted? last_end = match.end(0) if match.collapsing? if char = find_character(offset) offset += char.size else offset += 1 end else offset = match.end(0) end last_match = match match = pattern.match_from self, offset break unless match offset = match.begin 0 end Regexp.last_match = last_match str = substring(last_end, @num_bytes-last_end+1) ret.append str if str ret.taint if tainted || self.tainted? if last_match replace(ret) return self else return nil end end # Treats leading characters from <i>self</i> as a string of hexadecimal digits # (with an optional sign and an optional <code>0x</code>) and returns the # corresponding number. Zero is returned on error. # # "0x0a".hex #=> 10 # "-1234".hex #=> -4660 # "0".hex #=> 0 # "wombat".hex #=> 0 def hex self.to_inum(16, false) end # Returns <code>true</code> if <i>self</i> contains the given string or # character. # # "hello".include? "lo" #=> true # "hello".include? "ol" #=> false # "hello".include? ?h #=> true def include?(needle) if needle.is_a? Fixnum needle = needle % 256 str_needle = needle.chr else str_needle = StringValue(needle) end !!find_string(str_needle, 0) end # Returns the index of the first occurrence of the given <i>substring</i>, # character (<i>fixnum</i>), or pattern (<i>regexp</i>) in <i>self</i>. Returns # <code>nil</code> if not found. If the second parameter is present, it # specifies the position in the string to begin the search. # # "hello".index('e') #=> 1 # "hello".index('lo') #=> 3 # "hello".index('a') #=> nil # "hello".index(101) #=> 1 # "hello".index(/[aeiou]/, -3) #=> 4 def index(needle, offset = 0) offset = Type.coerce_to(offset, Integer, :to_int) offset = @num_bytes + offset if offset < 0 return nil if offset < 0 || offset > @num_bytes needle = needle.to_str if !needle.instance_of?(String) && needle.respond_to?(:to_str) # What are we searching for? case needle when Fixnum return nil if needle > 255 or needle < 0 return find_string(needle.chr, offset) when String return offset if needle == "" needle_size = needle.size max = @num_bytes - needle_size return if max < 0 # <= 0 maybe? return find_string(needle, offset) when Regexp if match = needle.match_from(self[offset..-1], 0) Regexp.last_match = match return (offset + match.begin(0)) else Regexp.last_match = nil end else raise TypeError, "type mismatch: #{needle.class} given" end return nil end # Inserts <i>other_string</i> before the character at the given # <i>index</i>, modifying <i>self</i>. Negative indices count from the # end of the string, and insert <em>after</em> the given character. # The intent is insert <i>other_string</i> so that it starts at the given # <i>index</i>. # # "abcd".insert(0, 'X') #=> "Xabcd" # "abcd".insert(3, 'X') #=> "abcXd" # "abcd".insert(4, 'X') #=> "abcdX" # "abcd".insert(-3, 'X') #=> "abXcd" # "abcd".insert(-1, 'X') #=> "abcdX" def insert(index, other) other = StringValue(other) index = Type.coerce_to(index, Integer, :to_int) unless index.__kind_of__ Fixnum osize = other.size size = @num_bytes + osize str = self.class.new("\0") * size index = @num_bytes + 1 + index if index < 0 if index > @num_bytes or index < 0 then raise IndexError, "index #{index} out of string" end modify! if index == 0 str.copy_from other, 0, other.size, 0 str.copy_from self, 0, @num_bytes, other.size elsif index < @num_bytes str.copy_from self, 0, index, 0 str.copy_from other, 0, osize, index str.copy_from self, index, @num_bytes - index, index + osize else str.copy_from self, 0, @num_bytes, 0 str.copy_from other, 0, other.size, @num_bytes end @num_bytes = size @data = str.data taint if other.tainted? self end ControlCharacters = [?\n, ?\t, ?\a, ?\v, ?\f, ?\r, ?\e, ?\b] ControlPrintValue = ["\\n", "\\t", "\\a", "\\v", "\\f", "\\r", "\\e", "\\b"] # Returns a printable version of _self_, with special characters # escaped. # # str = "hello" # str[3] = 8 # str.inspect #=> "hel\010o" def inspect str = '"' str << transform(CType::Printed, true) str << '"' str end # If <i>integer</i> is greater than the length of <i>self</i>, returns a new # <code>String</code> of length <i>integer</i> with <i>self</i> left justified # and padded with <i>padstr</i>; otherwise, returns <i>self</i>. # # "hello".ljust(4) #=> "hello" # "hello".ljust(20) #=> "hello " # "hello".ljust(20, '1234') #=> "hello123412341234123" def ljust(width, padstr = " ") justify(width, :left, padstr) end # Returns a copy of <i>self</i> with leading whitespace removed. See also # <code>String#rstrip</code> and <code>String#strip</code>. # # " hello ".lstrip #=> "hello " # "hello".lstrip #=> "hello" def lstrip (str = self.dup).lstrip! || str end # Removes leading whitespace from <i>self</i>, returning <code>nil</code> if no # change was made. See also <code>String#rstrip!</code> and # <code>String#strip!</code>. # # " hello ".lstrip #=> "hello " # "hello".lstrip! #=> nil def lstrip! return if @num_bytes == 0 start = 0 while start < @num_bytes c = @data[start] if c.isspace or c == 0 start += 1 else break end end return if start == 0 modify! @num_bytes = @characters = @num_bytes - start @data.move_bytes start, @num_bytes, 0 self end # Converts <i>pattern</i> to a <code>Regexp</code> (if it isn't already one), # then invokes its <code>match</code> method on <i>self</i>. # # 'hello'.match('(.)\1') #=> #<MatchData:0x401b3d30> # 'hello'.match('(.)\1')[0] #=> "ll" # 'hello'.match(/(.)\1/)[0] #=> "ll" # 'hello'.match('xx') #=> nil def match(pattern) obj = get_pattern(pattern).match_from(self, 0) Regexp.last_match = obj return obj end # Treats leading characters of <i>self</i> as a string of octal digits (with an # optional sign) and returns the corresponding number. Returns 0 if the # conversion fails. # # "123".oct # => 83 # "-377".oct # => -255 # "bad".oct # => 0 # "0377bad".oct # => 255 # # Any valid base identifier, if found, is honored though. For instance: # # "0b1010".oct # => 10 # "0xff".oct # => 256 # # If a valid base identifier is not found, the string is assumed to be base 8. def oct self.to_inum(-8, false) end # Replaces the contents and taintedness of <i>string</i> with the corresponding # values in <i>other</i>. # # s = "hello" #=> "hello" # s.replace "world" #=> "world" def replace(other) # If we're replacing with ourselves, then we have nothing to do return self if self.equal?(other) Ruby.check_frozen other = StringValue(other) @shared = true other.shared! @data = other.data @num_bytes = other.num_bytes @characters = other.characters @hash_value = nil self.taint if other.tainted? self end alias_method :initialize_copy, :replace # private :initialize_copy # Returns a new string with the characters from <i>self</i> in reverse order. # # "stressed".reverse #=> "desserts" def reverse self.dup.reverse! end # Reverses <i>self</i> in place. def reverse! return self if @num_bytes <= 1 self.modify! i = 0 j = @num_bytes - 1 while i < j @data[i], @data[j] = @data[j], @data[i] i += 1 j -= 1 end self end # Returns the index of the last occurrence of the given <i>substring</i>, # character (<i>fixnum</i>), or pattern (<i>regexp</i>) in <i>self</i>. Returns # <code>nil</code> if not found. If the second parameter is present, it # specifies the position in the string to end the search---characters beyond # this point will not be considered. # # "hello".rindex('e') #=> 1 # "hello".rindex('l') #=> 3 # "hello".rindex('a') #=> nil # "hello".rindex(101) #=> 1 # "hello".rindex(/[aeiou]/, -2) #=> 1 def rindex(sub, finish=undefined) if finish.equal?(undefined) finish = size else finish = Type.coerce_to(finish, Integer, :to_int) finish += @num_bytes if finish < 0 return nil if finish < 0 finish = @num_bytes if finish >= @num_bytes end case sub when Fixnum if finish == size return nil if finish == 0 finish -= 1 end begin str = sub.chr rescue RangeError return nil end return find_string_reverse(str, finish) when Regexp ret = sub.search_region(self, 0, finish, false) Regexp.last_match = ret return ret.begin(0) if ret else needle = StringValue(sub) needle_size = needle.size # needle is bigger that haystack return nil if size < needle_size # Boundary case return finish if needle_size == 0 return find_string_reverse(needle, finish) end return nil end # call-seq: str.partition(sep) => [head, sep, tail] # # Searches the string for _sep_ and returns the part before it, the # _sep_, and the part after it. If _sep_ is not found, returns _str_ # and two empty strings. If no argument is given, # Enumerable#partition is called. # # "hello".partition("l") #=> ["he", "l", "lo"] # "hello".partition("x") #=> ["hello", "", ""] # def partition(pattern=nil) return super() if block_given? if pattern.kind_of? Regexp if m = pattern.match(self) return [m.pre_match, m[0], m.post_match] end else pattern = StringValue(pattern) if i = index(pattern) post_start = i + pattern.length post_len = size - post_start return [self.substring(0, i), pattern.dup, self.substring(post_start, post_len)] end end # Nothing worked out, this is the default. return [self, "", ""] end # call-seq: # # str.rpartition(sep) => [head, sep, tail] # str.rpartition(regexp) => [head, match, tail] # # Searches _sep_ or pattern (_regexp_) in the string from the end # of the string, and returns the part before it, the match, and the part # after it. # If it is not found, returns two empty strings and _str_. # # "hello".rpartition("l") #=> ["hel", "l", "o"] # "hello".rpartition("x") #=> ["", "", "hello"] # "hello".rpartition(/.l/) #=> ["he", "ll", "o"] # def rpartition(pattern) if pattern.kind_of? Regexp if m = pattern.search_region(self, 0, size, false) Regexp.last_match = m [m.pre_match, m[0], m.post_match] end else pattern = StringValue(pattern) if i = rindex(pattern) post_start = i + pattern.length post_len = size - post_start return [self.substring(0, i), pattern.dup, self.substring(post_start, post_len)] end # Nothing worked out, this is the default. return ["", "", self] end end # If <i>integer</i> is greater than the length of <i>self</i>, returns a new # <code>String</code> of length <i>integer</i> with <i>self</i> right justified # and padded with <i>padstr</i>; otherwise, returns <i>self</i>. # # "hello".rjust(4) #=> "hello" # "hello".rjust(20) #=> " hello" # "hello".rjust(20, '1234') #=> "123412341234123hello" def rjust(width, padstr = " ") justify(width, :right, padstr) end # Returns a copy of <i>self</i> with trailing whitespace removed. See also # <code>String#lstrip</code> and <code>String#strip</code>. # # " hello ".rstrip #=> " hello" # "hello".rstrip #=> "hello" def rstrip (str = self.dup).rstrip! || str end # Removes trailing whitespace from <i>self</i>, returning <code>nil</code> if # no change was made. See also <code>String#lstrip!</code> and # <code>String#strip!</code>. # # " hello ".rstrip #=> " hello" # "hello".rstrip! #=> nil def rstrip! return if @num_bytes == 0 stop = @num_bytes - 1 while stop >= 0 c = @data[stop] if c.isspace || c == 0 stop -= 1 else break end end return if (stop += 1) == @num_bytes modify! @num_bytes = @characters = stop self end # Both forms iterate through <i>self</i>, matching the pattern (which may be a # <code>Regexp</code> or a <code>String</code>). For each match, a result is # generated and either added to the result array or passed to the block. If # the pattern contains no groups, each individual result consists of the # matched string, <code>$&</code>. If the pattern contains groups, each # individual result is itself an array containing one entry per group. # # a = "cruel world" # a.scan(/\w+/) #=> ["cruel", "world"] # a.scan(/.../) #=> ["cru", "el ", "wor"] # a.scan(/(...)/) #=> [["cru"], ["el "], ["wor"]] # a.scan(/(..)(..)/) #=> [["cr", "ue"], ["l ", "wo"]] # # And the block form: # # a.scan(/\w+/) {|w| print "<<#{w}>> " } # print "\n" # a.scan(/(.)(.)/) {|x,y| print y, x } # print "\n" # # <em>produces:</em> # # <<cruel>> <<world>> # rceu lowlr def scan(pattern) taint = self.tainted? || pattern.tainted? pattern = get_pattern(pattern, true) index = 0 last_match = nil if block_given? ret = self else ret = [] end while match = pattern.match_from(self, index) fin = match.end(0) if match.collapsing? if char = find_character(fin) index = fin + char.size else index = fin + 1 end else index = fin end last_match = match val = (match.length == 1 ? match[0] : match.captures) val.taint if taint if block_given? Regexp.last_match = match yield(val) else ret << val end end Regexp.last_match = last_match return ret end # Deletes the specified portion from <i>self</i>, and returns the portion # deleted. The forms that take a <code>Fixnum</code> will raise an # <code>IndexError</code> if the value is out of range; the <code>Range</code> # form will raise a <code>RangeError</code>, and the <code>Regexp</code> and # <code>String</code> forms will silently ignore the assignment. # # string = "this is a string" # string.slice!(2) #=> 105 # string.slice!(3..6) #=> " is " # string.slice!(/s.*t/) #=> "sa st" # string.slice!("r") #=> "r" # string #=> "thing" def slice!(one, two=undefined) # This is un-DRY, but it's a simple manual argument splitting. Keeps # the code fast and clean since the sequence are pretty short. # if two.equal? undefined result = slice(one) if one.kind_of? Regexp lm = Regexp.last_match self[one] = '' if result Regexp.last_match = lm else self[one] = '' if result end else result = slice(one, two) if one.kind_of? Regexp lm = Regexp.last_match self[one, two] = '' if result Regexp.last_match = lm else self[one, two] = '' if result end end result end # Divides <i>self</i> into substrings based on a delimiter, returning an array # of these substrings. # # If <i>pattern</i> is a <code>String</code>, then its contents are used as # the delimiter when splitting <i>self</i>. If <i>pattern</i> is a single # space, <i>self</i> is split on whitespace, with leading whitespace and runs # of contiguous whitespace characters ignored. # # If <i>pattern</i> is a <code>Regexp</code>, <i>self</i> is divided where the # pattern matches. Whenever the pattern matches a zero-length string, # <i>self</i> is split into individual characters. # # If <i>pattern</i> is omitted, the value of <code>$;</code> is used. If # <code>$;</code> is <code>nil</code> (which is the default), <i>self</i> is # split on whitespace as if ` ' were specified. # # If the <i>limit</i> parameter is omitted, trailing null fields are # suppressed. If <i>limit</i> is a positive number, at most that number of # fields will be returned (if <i>limit</i> is <code>1</code>, the entire # string is returned as the only entry in an array). If negative, there is no # limit to the number of fields returned, and trailing null fields are not # suppressed. # # " now's the time".split #=> ["now's", "the", "time"] # " now's the time".split(' ') #=> ["now's", "the", "time"] # " now's the time".split(/ /) #=> ["", "now's", "", "the", "time"] # "1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"] # "hello".split(//) #=> ["h", "e", "l", "l", "o"] # "hello".split(//, 3) #=> ["h", "e", "llo"] # "hi mom".split(%r{\s*}) #=> ["h", "i", "m", "o", "m"] # # "mellow yellow".split("ello") #=> ["m", "w y", "w"] # "1,2,,3,4,,".split(',') #=> ["1", "2", "", "3", "4"] # "1,2,,3,4,,".split(',', 4) #=> ["1", "2", "", "3,4,,"] # "1,2,,3,4,,".split(',', -4) #=> ["1", "2", "", "3", "4", "", ""] def split(pattern = nil, limit = undefined) # Odd edge case return [] if empty? tail_empty = false if limit == undefined limited = false else limit = Type.coerce_to limit, Fixnum, :to_int if limit > 0 return [self.dup] if limit == 1 limited = true else tail_empty = true limited = false end end pattern ||= ($; || " ") if pattern == ' ' spaces = true pattern = /\s+/ elsif pattern.nil? pattern = /\s+/ elsif pattern.kind_of?(Regexp) # Pass else pattern = StringValue(pattern) unless pattern.kind_of?(String) if !limited and limit.equal? undefined if pattern.empty? return pull_apart else return split_on_string(pattern) end end pattern = Regexp.new(Regexp.quote(pattern)) end start = 0 ret = [] # Handle // as a special case. if pattern.source.empty? if limited iterations = limit - 1 while c = self.find_character(start) ret << c start += c.size iterations -= 1 break if iterations == 0 end ret << self[start..-1] else while c = self.find_character(start) ret << c start += c.size end # Use #substring because it returns the right class and taints # automatically. This is just appending a "", which is this # strange protocol if a negative limit is passed in ret << substring(0,0) if tail_empty end return ret end last_match = nil while match = pattern.match_from(self, start) break if limited && limit - ret.size <= 1 collapsed = match.collapsing? if !collapsed || (match.begin(0) != 0) ret << match.pre_match_from(last_match ? last_match.end(0) : 0) ret.push(*match.captures.compact) end if collapsed start += 1 elsif last_match && last_match.collapsing? start = match.end(0) + 1 else start = match.end(0) end last_match = match end if last_match ret << last_match.post_match elsif ret.empty? ret << self.dup end # Trim from end if !ret.empty? and (limit == undefined || limit == 0) while s = ret.last and s.empty? ret.pop end end # Trim from front if !ret.empty? and spaces while s = ret.first and s.empty? ret.shift end end ret end def pull_apart ret = [] pos = 0 while pos < @num_bytes ret << substring(pos, 1) pos += 1 end ret end private :pull_apart def split_on_string(pattern) pos = 0 ret = [] pat_size = pattern.size while pos < @num_bytes nxt = find_string(pattern, pos) break unless nxt match_size = nxt - pos ret << substring(pos, match_size) pos = nxt + pat_size end # No more seperates, but we need to grab the last part still. ret << substring(pos, @num_bytes - pos) ret.pop while !ret.empty? and ret.last.empty? ret end # Builds a set of characters from the <i>*strings</i> parameter(s) using the # procedure described for <code>String#count</code>. Returns a new string # where runs of the same character that occur in this set are replaced by a # single character. If no arguments are given, all runs of identical # characters are replaced by a single character. # # "yellow moon".squeeze #=> "yelow mon" # " now is the".squeeze(" ") #=> " now is the" # "putters shoot balls".squeeze("m-z") #=> "puters shot balls" def squeeze(*strings) (str = self.dup).squeeze!(*strings) || str end # Squeezes <i>self</i> in place, returning either <i>self</i>, or # <code>nil</code> if no changes were made. def squeeze!(*strings) return if @num_bytes == 0 self.modify! table = count_table(*strings).data i, j, last = 1, 0, @data[0] while i < @num_bytes c = @data[i] unless c == last and table[c] == 1 @data[j+=1] = last = c end i += 1 end if (j += 1) < @num_bytes @num_bytes = j self else nil end end def start_with?(*prefixes) prefixes.each do |prefix| next unless prefix.respond_to? :to_str prefix = prefix.to_str return true if self[0, prefix.length] == prefix end false end # Returns a copy of <i>self</i> with leading and trailing whitespace removed. # # " hello ".strip #=> "hello" # "\tgoodbye\r\n".strip #=> "goodbye" def strip (str = self.dup).strip! || str end # Removes leading and trailing whitespace from <i>self</i>. Returns # <code>nil</code> if <i>self</i> was not altered. def strip! left = lstrip! right = rstrip! left.nil? && right.nil? ? nil : self end # Returns a copy of <i>self</i> with the <em>first</em> occurrence of # <i>pattern</i> replaced with either <i>replacement</i> or the value of the # block. The <i>pattern</i> will typically be a <code>Regexp</code>; if it is # a <code>String</code> then no regular expression metacharacters will be # interpreted (that is <code>/\d/</code> will match a digit, but # <code>'\d'</code> will match a backslash followed by a 'd'). # # If the method call specifies <i>replacement</i>, special variables such as # <code>$&</code> will not be useful, as substitution into the string occurs # before the pattern match starts. However, the sequences <code>\1</code>, # <code>\2</code>, etc., may be used. # # In the block form, the current match string is passed in as a parameter, and # variables such as <code>$1</code>, <code>$2</code>, <code>$`</code>, # <code>$&</code>, and <code>$'</code> will be set appropriately. The value # returned by the block will be substituted for the match on each call. # # The result inherits any tainting in the original string or any supplied # replacement string. # # "hello".sub(/[aeiou]/, '*') #=> "h*llo" # "hello".sub(/([aeiou])/, '<\1>') #=> "h<e>llo" # "hello".sub(/./) {|s| s[0].to_s + ' ' } #=> "104 ello" def sub(pattern, replacement=undefined) if replacement.equal?(undefined) and !block_given? raise ArgumentError, "wrong number of arguments (1 for 2)" end unless pattern raise ArgumentError, "wrong number of arguments (0 for 2)" end if match = get_pattern(pattern, true).match_from(self, 0) out = match.pre_match Regexp.last_match = match if replacement == undefined replacement = yield(match[0].dup).to_s out.taint if replacement.tainted? else out.taint if replacement.tainted? replacement = StringValue(replacement).to_sub_replacement(match) end # We have to reset it again to match the specs Regexp.last_match = match out << replacement << match.post_match out.taint if self.tainted? else out = self Regexp.last_match = nil end # MRI behavior emulation. Sub'ing String subclasses doen't return the # subclass, they return String instances. unless self.instance_of?(String) out = self.class.new(out) end return out end # Performs the substitutions of <code>String#sub</code> in place, # returning <i>self</i>, or <code>nil</code> if no substitutions were # performed. def sub!(pattern, replacement=undefined) # Copied mostly from sub to keep Regexp.last_match= working right. if replacement.equal?(undefined) and !block_given? raise ArgumentError, "wrong number of arguments (1 for 2)" end unless pattern raise ArgumentError, "wrong number of arguments (0 for 2)" end if match = get_pattern(pattern, true).match_from(self, 0) out = match.pre_match Regexp.last_match = match if replacement == undefined replacement = yield(match[0].dup).to_s out.taint if replacement.tainted? else out.taint if replacement.tainted? replacement = StringValue(replacement).to_sub_replacement(match) end # We have to reset it again to match the specs Regexp.last_match = match out << replacement << match.post_match out.taint if self.tainted? else out = self Regexp.last_match = nil return nil end replace(out) return self end # Returns the successor to <i>self</i>. The successor is calculated by # incrementing characters starting from the rightmost alphanumeric (or # the rightmost character if there are no alphanumerics) in the # string. Incrementing a digit always results in another digit, and # incrementing a letter results in another letter of the same case. # Incrementing nonalphanumerics uses the underlying character set's # collating sequence. # # If the increment generates a ``carry,'' the character to the left of # it is incremented. This process repeats until there is no carry, # adding an additional character if necessary. # # "abcd".succ #=> "abce" # "THX1138".succ #=> "THX1139" # "<<koala>>".succ #=> "<<koalb>>" # "1999zzz".succ #=> "2000aaa" # "ZZZ9999".succ #=> "AAAA0000" # "***".succ #=> "**+" def succ self.dup.succ! end # Equivalent to <code>String#succ</code>, but modifies the receiver in # place. def succ! self.modify! return self if @num_bytes == 0 carry = nil last_alnum = 0 start = @num_bytes - 1 while start >= 0 if (s = @data[start]).isalnum carry = 0 if (?0 <= s && s < ?9) || (?a <= s && s < ?z) || (?A <= s && s < ?Z) @data[start] += 1 elsif s == ?9 @data[start] = ?0 carry = ?1 elsif s == ?z @data[start] = carry = ?a elsif s == ?Z @data[start] = carry = ?A end break if carry == 0 last_alnum = start end start -= 1 end if carry.nil? start = length - 1 carry = ?\001 while start >= 0 if @data[start] >= 255 @data[start] = 0 else @data[start] += 1 break end start -= 1 end end if start < 0 splice! last_alnum, 1, carry.chr + @data[last_alnum].chr end return self end alias_method :next, :succ alias_method :next!, :succ! # Returns a basic <em>n</em>-bit checksum of the characters in <i>self</i>, # where <em>n</em> is the optional <code>Fixnum</code> parameter, defaulting # to 16. The result is simply the sum of the binary value of each character in # <i>self</i> modulo <code>2n - 1</code>. This is not a particularly good # checksum. def sum(bits = 16) bits = Type.coerce_to bits, Integer, :to_int unless bits.__kind_of__ Fixnum i, sum = -1, 0 sum += @data[i] while (i += 1) < @num_bytes sum & ((1 << bits) - 1) end # Returns a copy of <i>self</i> with uppercase alphabetic characters converted to # lowercase and lowercase characters converted to uppercase. # # "Hello".swapcase #=> "hELLO" # "cYbEr_PuNk11".swapcase #=> "CyBeR_pUnK11" def swapcase (str = self.dup).swapcase! || str end # Equivalent to <code>String#swapcase</code>, but modifies the receiver in # place, returning <i>self</i>, or <code>nil</code> if no changes were made. def swapcase! self.modify! return if @num_bytes == 0 modified = false i = 0 while i < @num_bytes c = @data[i] if c.islower @data[i] = c.toupper! modified = true elsif c.isupper @data[i] = c.tolower! modified = true end i += 1 end modified ? self : nil end # The +intern+ method is an alias of +to_sym+. See <code>Symbol#to_sym</code>. alias_method :intern, :to_sym # Returns the result of interpreting leading characters in <i>self</i> as an # integer base <i>base</i> (between 2 and 36). Extraneous characters past the # end of a valid number are ignored. If there is not a valid number at the # start of <i>self</i>, <code>0</code> is returned. This method never raises an # exception. # # "12345".to_i #=> 12345 # "99 red balloons".to_i #=> 99 # "0a".to_i #=> 0 # "0a".to_i(16) #=> 10 # "hello".to_i #=> 0 # "1100101".to_i(2) #=> 101 # "1100101".to_i(8) #=> 294977 # "1100101".to_i(10) #=> 1100101 # "1100101".to_i(16) #=> 17826049 def to_i(base = 10) base = Type.coerce_to(base, Integer, :to_int) raise ArgumentError, "illegal radix #{base}" if base < 0 || base == 1 || base > 36 self.to_inum(base, false) end # Returns self if self is an instance of String, # else returns self converted to a String instance. def to_s instance_of?(String) ? self : "".replace(self) end alias_method :to_str, :to_s # Returns a copy of <i>self</i> with the characters in <i>from_str</i> replaced # by the corresponding characters in <i>to_str</i>. If <i>to_str</i> is # shorter than <i>from_str</i>, it is padded with its last character. Both # strings may use the c1--c2 notation to denote ranges of characters, and # <i>from_str</i> may start with a <code>^</code>, which denotes all # characters except those listed. # # "hello".tr('aeiou', '*') #=> "h*ll*" # "hello".tr('^aeiou', '*') #=> "*e**o" # "hello".tr('el', 'ip') #=> "hippo" # "hello".tr('a-y', 'b-z') #=> "ifmmp" def tr(source, replacement) (str = self.dup).tr!(source, replacement) || str end # Translates <i>self</i> in place, using the same rules as # <code>String#tr</code>. Returns <i>self</i>, or <code>nil</code> if no # changes were made. def tr!(source, replacement) tr_trans(source, replacement, false) end # Processes a copy of <i>self</i> as described under <code>String#tr</code>, # then removes duplicate characters in regions that were affected by the # translation. # # "hello".tr_s('l', 'r') #=> "hero" # "hello".tr_s('el', '*') #=> "h*o" # "hello".tr_s('el', 'hx') #=> "hhxo" def tr_s(source, replacement) (str = self.dup).tr_s!(source, replacement) || str end # Performs <code>String#tr_s</code> processing on <i>self</i> in place, # returning <i>self</i>, or <code>nil</code> if no changes were made. def tr_s!(source, replacement) tr_trans(source, replacement, true) end # Returns a copy of <i>self</i> with all lowercase letters replaced with their # uppercase counterparts. The operation is locale insensitive---only # characters ``a'' to ``z'' are affected. # # "hEllO".upcase #=> "HELLO" def upcase (str = self.dup).upcase! || str end ## # Upcases the contents of <i>self</i>, returning <code>nil</code> if no # changes were made. def upcase! return if @num_bytes == 0 self.modify! modified = false i = 0 while i < @num_bytes c = @data[i] if c.islower @data[i] = c.toupper! modified = true end i += 1 end modified ? self : nil end def upto(stop, exclusive=false) stop = StringValue(stop) return self if self > stop after_stop = exclusive ? stop : stop.succ current = self until current == after_stop yield current current = StringValue(current.succ) break if current.size > stop.size || current.size == 0 end self end def tr_trans(source, replacement, squeeze) source = StringValue(source).dup replacement = StringValue(replacement).dup self.modify! return self.delete!(source) if replacement.empty? return if @num_bytes == 0 invert = source[0] == ?^ && source.length > 1 expanded = source.tr_expand! nil size = source.size src = source.data if invert replacement.tr_expand! nil r = replacement.data[replacement.size-1] table = Rubinius::Tuple.pattern 256, r i = 0 while i < size table[src[i]] = -1 i += 1 end else table = Rubinius::Tuple.pattern 256, -1 replacement.tr_expand! expanded repl = replacement.data rsize = replacement.size i = 0 while i < size r = repl[i] if i < rsize table[src[i]] = r i += 1 end end self.modify! modified = false if squeeze i, j, last = -1, -1, nil while (i += 1) < @num_bytes s = @data[i] c = table[s] if c >= 0 next if last == c @data[j+=1] = last = c modified = true else @data[j+=1] = s last = nil end end @num_bytes = j if (j += 1) < @num_bytes else i = 0 while i < @num_bytes c = table[@data[i]] if c >= 0 @data[i] = c modified = true end i += 1 end end return modified ? self : nil end def to_sub_replacement(match) index = 0 result = "" while index < @num_bytes current = index while current < @num_bytes && @data[current] != ?\\ current += 1 end result << substring(index, current - index) break if current == @num_bytes # found backslash escape, looking next if current == @num_bytes - 1 result << ?\\ # backslash at end of string break end index = current + 1 result << case (cap = @data[index]) when ?& match[0] when ?` match.pre_match when ?' match.post_match when ?+ match.captures.compact[-1].to_s when ?0..?9 match[cap - ?0].to_s when ?\\ # escaped backslash '\\' else # unknown escape '\\' << cap end index += 1 end return result end def to_inum(base, check) Ruby.primitive :string_to_inum detect_base = true if base == 0 raise(ArgumentError, "invalid value for Integer: #{inspect}") if check and self =~ /__/ s = if check then self else self.delete('_').strip end if detect_base then base = if s =~ /^[+-]?0([bdox]?)/i then {"b" => 2, "d" => 10, "o" => 8, '' => 8, "x" => 16}[$1.downcase] else base == 8 ? 8 : 10 end end raise ArgumentError, "illegal radix #{base}" unless (2..36).include? base if check match_re = case base when 2 then /^([+-])?(?:0b)?([a-z0-9_]*)$/ix when 8 then /^([+-])?(?:0o)?([a-z0-9_]*)$/ix when 10 then /^([+-])?(?:0d)?([a-z0-9_]*)$/ix when 16 then /^([+-])?(?:0x)?([a-z0-9_]*)$/ix else /^([+-])? ([a-z0-9_]*)$/ix end else match_re = case base when 2 then /([+-])?(?:0b)?([a-z0-9_]*)/ix when 8 then /([+-])?(?:0o)?([a-z0-9_]*)/ix when 10 then /([+-])?(?:0d)?([a-z0-9_]*)/ix when 16 then /([+-])?(?:0x)?([a-z0-9_]*)/ix else /([+-])? ([a-z0-9_]*)/ix end end sign = data = nil sign, data = $1, $2 if s =~ match_re raise ArgumentError, "error in impl parsing: #{self.inspect} with #{match_re.source}" if data.nil? || (check && (s =~ /^_|_$/ || data.empty? )) negative = sign == "-" result = 0 data.each_byte do |char| value = case char when ?0..?9 then (char - ?0) when ?A..?Z then (char - ?A + 10) when ?a..?z then (char - ?a + 10) when ?_ then next else nil end if value.nil? or value >= base then raise ArgumentError, "invalid value for Integer: #{inspect}" if check return negative ? -result : result end result *= base result += value end return negative ? -result : result end def apply_and!(other) Ruby.primitive :string_apply_and raise PrimitiveFailure, "String#apply_and! primitive failed" end def compare_substring(other, start, size) Ruby.primitive :string_compare_substring if start > @num_bytes || start + @num_bytes < 0 raise IndexError, "index #{start} out of string" end raise PrimitiveFailure, "String#compare_substring primitive failed" end def count_table(*strings) table = String.pattern 256, 1 i, size = 0, strings.size while i < size str = StringValue(strings[i]).dup if str.size > 1 && str[0] == ?^ pos, neg = 0, 1 else pos, neg = 1, 0 end set = String.pattern 256, neg str.tr_expand! nil j, chars = -1, str.size set[str[j]] = pos while (j += 1) < chars table.apply_and! set i += 1 end table end def tr_expand!(limit) Ruby.primitive :string_tr_expand raise PrimitiveFailure, "String#tr_expand primitive failed" end def justify(width, direction, padstr=" ") padstr = StringValue(padstr) raise ArgumentError, "zero width padding" if padstr.size == 0 width = Type.coerce_to(width, Integer, :to_int) unless width.__kind_of__ Fixnum if width > @num_bytes padsize = width - @num_bytes else return dup end str = self.class.new("\0") * (padsize + @num_bytes) str.taint if tainted? or padstr.tainted? case direction when :right pad = String.pattern padsize, padstr str.copy_from pad, 0, padsize, 0 str.copy_from self, 0, @num_bytes, padsize when :left pad = String.pattern padsize, padstr str.copy_from self, 0, @num_bytes, 0 str.copy_from pad, 0, padsize, @num_bytes when :center half = padsize / 2.0 lsize = half.floor rsize = half.ceil lpad = String.pattern lsize, padstr rpad = String.pattern rsize, padstr str.copy_from lpad, 0, lsize, 0 str.copy_from self, 0, @num_bytes, lsize str.copy_from rpad, 0, rsize, lsize + @num_bytes end str end # Unshares shared strings. def modify! Ruby.check_frozen if @shared @data = @data.dup @shared = nil end @hash_value = nil # reset the hash value end def subpattern(pattern, capture) # TODO: A part of the functionality here should go into MatchData#[] match = pattern.match(self) if !match or capture >= match.size return nil end if capture < 0 capture += match.size return nil if capture <= 0 end start = match.begin(capture) count = match.end(capture) - match.begin(capture) str = self.substring(start, count) str.taint if pattern.tainted? [match, str] end def subpattern_set(pattern, capture, replacement) unless match = pattern.match(self) raise IndexError, "regexp not matched" end raise IndexError, "index #{capture} out of regexp" if capture >= match.size if capture < 0 raise IndexError, "index #{capture} out of regexp" if -capture >= match.size capture += match.size end start = match.begin(capture) length = match.end(capture) - start splice! start, length, replacement end def splice!(start, count, replacement) start += @num_bytes if start < 0 if start > @num_bytes || start < 0 then raise IndexError, "index #{start} out of string" end raise IndexError, "negative length #{count}" if count < 0 replacement = StringValue replacement modify! count = @num_bytes - start if start + count > @num_bytes size = start < @num_bytes ? @num_bytes - count : @num_bytes rsize = replacement.size str = self.class.new("\0") * (size + rsize) str.taint if tainted? || replacement.tainted? last = start + count str.copy_from self, 0, start, 0 if start > 0 str.copy_from replacement, 0, rsize, start if last < @num_bytes then str.copy_from self, last, @num_bytes - last, start + rsize end replace str end def prefix?(other) size = other.size return false if size > @num_bytes other.compare_substring(self, 0, size) == 0 end def suffix?(other) size = other.size return false if size > @num_bytes other.compare_substring(self, -size, size) == 0 end def shorten!(size) self.modify! return if @num_bytes == 0 @num_bytes = @characters = @num_bytes - size end def dump str = self.class.new '"' str << transform(CType::Printed, false) str << '"' str end def shared! @shared = true end def get_pattern(pattern, quote=false) case pattern when Regexp return pattern when String # nothing else pattern = StringValue(pattern) end pattern = Regexp.quote(pattern) if quote Regexp.new(pattern) end def full_to_i err = "invalid value for Integer: #{self.inspect}" raise ArgumentError, err if self.match(/__/) || self.empty? case self when /^[-+]?0(\d|_\d)/ raise ArgumentError, err if self =~ /[^0-7_]/ to_i(8) when /^[-+]?0x[a-f\d]/i after = self.match(/^[-+]?0x/i) raise ArgumentError, err if /([^0-9a-f_])/i.match_from(self, after.end(0)) to_i(16) when /^[-+]?0b[01]/i after = self.match(/^[-+]?0b/i) raise ArgumentError, err if /[^01_]/.match_from(self, after.end(0)) to_i(2) when /^[-+]?\d/ raise ArgumentError, err if self.match(/[^0-9_]/) to_i(10) else raise ArgumentError, err end end ## # call-seq: # str.unpack(format) => anArray # # Decodes <i>str</i> (which may contain binary data) according to # the format string, returning an array of each value # extracted. The format string consists of a sequence of # single-character directives, summarized in the table at the end # of this entry. # # Each directive may be followed by a number, indicating the number # of times to repeat with this directive. An asterisk # (``<code>*</code>'') will use up all remaining elements. The # directives <code>sSiIlL</code> may each be followed by an # underscore (``<code>_</code>'') to use the underlying platform's # native size for the specified type; otherwise, it uses a # platform-independent consistent size. Spaces are ignored in the # format string. See also <code>Array#pack</code>. # # "abc \0\0abc \0\0".unpack('A6Z6') #=> ["abc", "abc "] # "abc \0\0".unpack('a3a3') #=> ["abc", " \000\000"] # "abc \0abc \0".unpack('Z*Z*') #=> ["abc ", "abc "] # "aa".unpack('b8B8') #=> ["10000110", "01100001"] # "aaa".unpack('h2H2c') #=> ["16", "61", 97] # "\xfe\xff\xfe\xff".unpack('sS') #=> [-2, 65534] # "now=20is".unpack('M*') #=> ["now is"] # "whole".unpack('xax2aX2aX1aX2a') #=> ["h", "e", "l", "l", "o"] # # This table summarizes the various formats and the Ruby classes # returned by each. # # Format | Returns | Function # -------+---------+----------------------------------------- # A | String | with trailing nulls and spaces removed # -------+---------+----------------------------------------- # a | String | string # -------+---------+----------------------------------------- # B | String | extract bits from each character (msb first) # -------+---------+----------------------------------------- # b | String | extract bits from each character (lsb first) # -------+---------+----------------------------------------- # C | Fixnum | extract a character as an unsigned integer # -------+---------+----------------------------------------- # c | Fixnum | extract a character as an integer # -------+---------+----------------------------------------- # d,D | Float | treat sizeof(double) characters as # | | a native double # -------+---------+----------------------------------------- # E | Float | treat sizeof(double) characters as # | | a double in little-endian byte order # -------+---------+----------------------------------------- # e | Float | treat sizeof(float) characters as # | | a float in little-endian byte order # -------+---------+----------------------------------------- # f,F | Float | treat sizeof(float) characters as # | | a native float # -------+---------+----------------------------------------- # G | Float | treat sizeof(double) characters as # | | a double in network byte order # -------+---------+----------------------------------------- # g | Float | treat sizeof(float) characters as a # | | float in network byte order # -------+---------+----------------------------------------- # H | String | extract hex nibbles from each character # | | (most significant first) # -------+---------+----------------------------------------- # h | String | extract hex nibbles from each character # | | (least significant first) # -------+---------+----------------------------------------- # I | Integer | treat sizeof(int) (modified by _) # | | successive characters as an unsigned # | | native integer # -------+---------+----------------------------------------- # i | Integer | treat sizeof(int) (modified by _) # | | successive characters as a signed # | | native integer # -------+---------+----------------------------------------- # L | Integer | treat four (modified by _) successive # | | characters as an unsigned native # | | long integer # -------+---------+----------------------------------------- # l | Integer | treat four (modified by _) successive # | | characters as a signed native # | | long integer # -------+---------+----------------------------------------- # M | String | quoted-printable # -------+---------+----------------------------------------- # m | String | base64-encoded # -------+---------+----------------------------------------- # N | Integer | treat four characters as an unsigned # | | long in network byte order # -------+---------+----------------------------------------- # n | Fixnum | treat two characters as an unsigned # | | short in network byte order # -------+---------+----------------------------------------- # P | String | treat sizeof(char *) characters as a # | | pointer, and return \emph{len} characters # | | from the referenced location # -------+---------+----------------------------------------- # p | String | treat sizeof(char *) characters as a # | | pointer to a null-terminated string # -------+---------+----------------------------------------- # Q | Integer | treat 8 characters as an unsigned # | | quad word (64 bits) # -------+---------+----------------------------------------- # q | Integer | treat 8 characters as a signed # | | quad word (64 bits) # -------+---------+----------------------------------------- # S | Fixnum | treat two (different if _ used) # | | successive characters as an unsigned # | | short in native byte order # -------+---------+----------------------------------------- # s | Fixnum | Treat two (different if _ used) # | | successive characters as a signed short # | | in native byte order # -------+---------+----------------------------------------- # U | Integer | UTF-8 characters as unsigned integers # -------+---------+----------------------------------------- # u | String | UU-encoded # -------+---------+----------------------------------------- # V | Fixnum | treat four characters as an unsigned # | | long in little-endian byte order # -------+---------+----------------------------------------- # v | Fixnum | treat two characters as an unsigned # | | short in little-endian byte order # -------+---------+----------------------------------------- # w | Integer | BER-compressed integer (see Array.pack) # -------+---------+----------------------------------------- # X | --- | skip backward one character # -------+---------+----------------------------------------- # x | --- | skip forward one character # -------+---------+----------------------------------------- # Z | String | with trailing nulls removed # | | upto first null with * # -------+---------+----------------------------------------- # @ | --- | skip to the offset given by the # | | length argument # -------+---------+----------------------------------------- def unpack(format) # see pack.rb for String::Unpacker Unpacker.new(self,format).dispatch end end
29.933579
92
0.559184
184fe73ee74588f50470f214e37868d9b781a5c5
60,377
# frozen_string_literal: true require 'active_record' require 'zombie_battleground/api/validation_helper' ## # Dummy class for testing ZombieBattleground::Api::ValidationHelper class ValidationHelperDummy include ActiveModel::Validations include ZombieBattleground::Api::ValidationHelper attr_accessor :ability, :amount, :block_height, :card_name, :cost, :created_at, :damage, :deck_id, :description, :frame, :health, :hero_id, :id, :image_url, :kind, :limit, :mould_id, :name, :page, :player1_deck_id, :player1_id, :player2_deck_id, :player2_id, :primary_skill_id, :random_seed, :rank, :rarity, :secondary_skill_id, :sender_address, :set, :status, :total, :type, :updated_at, :user_id, :version, :winner_id end RSpec.describe ZombieBattleground::Api::ValidationHelper do before(:each) { @dummy = ValidationHelperDummy.new } describe '#value_is_a_class' do it 'does not add an error when String is a String' do @dummy.version = 'v3' @dummy.send(:value_is_a_class, target: :version, value: @dummy.version, klass: String, nullable: false) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:value_is_a_class, target: :version, value: @dummy.version, klass: String, nullable: true) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.send(:value_is_a_class, target: :version, value: @dummy.version, klass: String, nullable: false) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:version]).not_to be_empty end end describe '#value_is_a_string' do it 'does not add an error when String is a String' do @dummy.version = 'v3' @dummy.send(:value_is_a_string, target: :version, value: @dummy.version, nullable: false) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:value_is_a_string, target: :version, value: @dummy.version, nullable: true) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.send(:value_is_a_string, target: :version, value: @dummy.version, nullable: false) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:version]).not_to be_empty end end describe '#value_is_a_time' do it 'does not add an error when Time is a Time' do @dummy.created_at = Time.at(1_550_045_898) @dummy.send(:value_is_a_time, target: :created_at, value: @dummy.created_at, nullable: false) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Time is nil and nullable is true' do @dummy.send(:value_is_a_time, target: :created_at, value: @dummy.created_at, nullable: true) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Time is a not a Time' do @dummy.send(:value_is_a_time, target: :created_at, value: @dummy.created_at, nullable: false) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:created_at]).not_to be_empty end end describe '#value_is_an_integer' do it 'does not add an error when Integer is a Integer' do @dummy.id = 1 @dummy.send(:value_is_an_integer, target: :id, value: @dummy.id, nullable: false) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:value_is_an_integer, target: :id, value: @dummy.id, nullable: true) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.send(:value_is_an_integer, target: :id, value: @dummy.id, nullable: false) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:id]).not_to be_empty end end describe '#value_is_a_non_negative_integer' do it 'is not an integer' do @dummy.id = 'one' @dummy.send(:value_is_a_non_negative_integer, target: :id, value: @dummy.id, nullable: false) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:id]).not_to be_empty end it 'is nullable and is nil' do @dummy.send(:value_is_a_non_negative_integer, target: :id, value: @dummy.id, nullable: true) expect(@dummy.errors.messages.empty?).to be true end it 'is zero' do @dummy.id = 0 @dummy.send(:value_is_a_non_negative_integer, target: :id, value: @dummy.id, nullable: false) expect(@dummy.errors.messages.empty?).to be true end it 'is positive' do @dummy.id = 1 @dummy.send(:value_is_a_non_negative_integer, target: :id, value: @dummy.id, nullable: false) expect(@dummy.errors.messages.empty?).to be true end it 'is not positive' do @dummy.id = -1 @dummy.send(:value_is_a_non_negative_integer, target: :id, value: @dummy.id, nullable: false) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:id]).not_to be_empty end end describe '#id_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.id = 1 @dummy.send(:id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.id = 'one' @dummy.send(:id_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:id]).not_to be_empty end end describe '#id_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.id = 1 @dummy.send(:id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:id]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.id = 'one' @dummy.send(:id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:id]).not_to be_empty end end describe '#user_id_is_a_string' do it 'does not add an error when String is a String' do @dummy.user_id = 'one' @dummy.send(:user_id_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:user_id_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.user_id = 1 @dummy.send(:user_id_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:user_id]).not_to be_empty end end describe '#user_id_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.user_id = 'one' @dummy.send(:user_id_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:user_id_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:user_id]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.user_id = 1 @dummy.send(:user_id_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:user_id]).not_to be_empty end end describe '#deck_id_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.deck_id = 1 @dummy.send(:deck_id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:deck_id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.deck_id = 'one' @dummy.send(:deck_id_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:deck_id]).not_to be_empty end end describe '#deck_id_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.deck_id = 1 @dummy.send(:deck_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:deck_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:deck_id]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.deck_id = 'one' @dummy.send(:deck_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:deck_id]).not_to be_empty end end describe '#name_is_a_string' do it 'does not add an error when String is a String' do @dummy.name = 'one' @dummy.send(:name_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:name_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.name = 1 @dummy.send(:name_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:name]).not_to be_empty end end describe '#name_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.name = 'one' @dummy.send(:name_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:name_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:name]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.name = 1 @dummy.send(:name_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:name]).not_to be_empty end end describe '#hero_id_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.hero_id = 1 @dummy.send(:hero_id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:hero_id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.hero_id = 'one' @dummy.send(:hero_id_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:hero_id]).not_to be_empty end end describe '#hero_id_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.hero_id = 1 @dummy.send(:hero_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:hero_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:hero_id]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.hero_id = 'one' @dummy.send(:hero_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:hero_id]).not_to be_empty end end describe '#primary_skill_id_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.primary_skill_id = 1 @dummy.send(:primary_skill_id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:primary_skill_id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.primary_skill_id = 'one' @dummy.send(:primary_skill_id_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:primary_skill_id]).not_to be_empty end end describe '#primary_skill_id_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.primary_skill_id = 1 @dummy.send(:primary_skill_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:primary_skill_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:primary_skill_id]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.primary_skill_id = 'one' @dummy.send(:primary_skill_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:primary_skill_id]).not_to be_empty end end describe '#secondary_skill_id_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.secondary_skill_id = 1 @dummy.send(:secondary_skill_id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:secondary_skill_id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.secondary_skill_id = 'one' @dummy.send(:secondary_skill_id_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:secondary_skill_id]).not_to be_empty end end describe '#secondary_skill_id_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.secondary_skill_id = 1 @dummy.send(:secondary_skill_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:secondary_skill_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:secondary_skill_id]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.secondary_skill_id = 'one' @dummy.send(:secondary_skill_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:secondary_skill_id]).not_to be_empty end end describe '#version_is_a_string' do it 'does not add an error when String is a String' do @dummy.version = 'one' @dummy.send(:version_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:version_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.version = 1 @dummy.send(:version_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:version]).not_to be_empty end end describe '#version_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.version = 'one' @dummy.send(:version_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:version_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:version]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.version = 1 @dummy.send(:version_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:version]).not_to be_empty end end describe '#total_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.total = 1 @dummy.send(:total_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:total_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.total = 'one' @dummy.send(:total_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:total]).not_to be_empty end end describe '#total_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.total = 1 @dummy.send(:total_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:total_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:total]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.total = 'one' @dummy.send(:total_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:total]).not_to be_empty end end describe '#page_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.page = 1 @dummy.send(:page_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:page_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.page = 'one' @dummy.send(:page_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:page]).not_to be_empty end end describe '#page_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.page = 1 @dummy.send(:page_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:page_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:page]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.page = 'one' @dummy.send(:page_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:page]).not_to be_empty end end describe '#limit_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.limit = 1 @dummy.send(:limit_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:limit_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.limit = 'one' @dummy.send(:limit_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:limit]).not_to be_empty end end describe '#limit_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.limit = 1 @dummy.send(:limit_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:limit_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:limit]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.limit = 'one' @dummy.send(:limit_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:limit]).not_to be_empty end end describe '#card_name_is_a_string' do it 'does not add an error when String is a String' do @dummy.card_name = 'one' @dummy.send(:card_name_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:card_name_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.card_name = 1 @dummy.send(:card_name_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:card_name]).not_to be_empty end end describe '#card_name_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.card_name = 'one' @dummy.send(:card_name_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:card_name_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:card_name]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.card_name = 1 @dummy.send(:card_name_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:card_name]).not_to be_empty end end describe '#amount_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.amount = 1 @dummy.send(:amount_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:amount_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.amount = 'one' @dummy.send(:amount_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:amount]).not_to be_empty end end describe '#amount_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.amount = 1 @dummy.send(:amount_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:amount_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:amount]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.amount = 'one' @dummy.send(:amount_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:amount]).not_to be_empty end end describe '#sender_address_is_a_string' do it 'does not add an error when String is a String' do @dummy.sender_address = 'one' @dummy.send(:sender_address_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:sender_address_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.sender_address = 1 @dummy.send(:sender_address_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:sender_address]).not_to be_empty end end describe '#sender_address_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.sender_address = 'one' @dummy.send(:sender_address_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:sender_address_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:sender_address]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.sender_address = 1 @dummy.send(:sender_address_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:sender_address]).not_to be_empty end end describe '#created_at_is_a_time' do it 'does not add an error when Time is a Time' do @dummy.created_at = Time.at(1_550_045_898) @dummy.send(:created_at_is_a_time) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Time is nil and nullable is true' do @dummy.send(:created_at_is_a_time) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Time is a not a Time' do @dummy.created_at = 1 @dummy.send(:created_at_is_a_time) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:created_at]).not_to be_empty end end describe '#created_at_is_a_time_and_not_null' do it 'does not add an error when Time is a Time' do @dummy.created_at = Time.at(1_550_045_898) @dummy.send(:created_at_is_a_time_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Time is nil and nullable is true' do @dummy.send(:created_at_is_a_time_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:created_at]).not_to be_empty end it 'adds an error when Time is a not a Time' do @dummy.created_at = 1 @dummy.send(:created_at_is_a_time_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:created_at]).not_to be_empty end end describe '#updated_at_is_a_time' do it 'does not add an error when Time is a Time' do @dummy.updated_at = Time.at(1_550_045_898) @dummy.send(:updated_at_is_a_time) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Time is nil and nullable is true' do @dummy.send(:updated_at_is_a_time) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Time is a not a Time' do @dummy.updated_at = 1 @dummy.send(:updated_at_is_a_time) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:updated_at]).not_to be_empty end end describe '#updated_at_is_a_time_and_not_null' do it 'does not add an error when Time is a Time' do @dummy.updated_at = Time.at(1_550_045_898) @dummy.send(:updated_at_is_a_time_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Time is nil and nullable is true' do @dummy.send(:updated_at_is_a_time_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:updated_at]).not_to be_empty end it 'adds an error when Time is a not a Time' do @dummy.updated_at = 1 @dummy.send(:updated_at_is_a_time_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:updated_at]).not_to be_empty end end describe '#block_height_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.block_height = 1 @dummy.send(:block_height_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:block_height_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.block_height = 'one' @dummy.send(:block_height_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:block_height]).not_to be_empty end end describe '#block_height_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.block_height = 1 @dummy.send(:block_height_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:block_height_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:block_height]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.block_height = 'one' @dummy.send(:block_height_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:block_height]).not_to be_empty end end describe '#player1_id_is_a_string' do it 'does not add an error when String is a String' do @dummy.player1_id = 'one' @dummy.send(:player1_id_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:player1_id_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.player1_id = 1 @dummy.send(:player1_id_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:player1_id]).not_to be_empty end end describe '#player1_id_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.player1_id = 'one' @dummy.send(:player1_id_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:player1_id_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:player1_id]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.player1_id = 1 @dummy.send(:player1_id_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:player1_id]).not_to be_empty end end describe '#player2_id_is_a_string' do it 'does not add an error when String is a String' do @dummy.player2_id = 'one' @dummy.send(:player2_id_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:player2_id_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.player2_id = 1 @dummy.send(:player2_id_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:player2_id]).not_to be_empty end end describe '#player2_id_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.player2_id = 'one' @dummy.send(:player2_id_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:player2_id_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:player2_id]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.player2_id = 1 @dummy.send(:player2_id_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:player2_id]).not_to be_empty end end describe '#player1_deck_id_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.player1_deck_id = 1 @dummy.send(:player1_deck_id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:player1_deck_id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.player1_deck_id = 'one' @dummy.send(:player1_deck_id_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:player1_deck_id]).not_to be_empty end end describe '#player1_deck_id_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.player1_deck_id = 1 @dummy.send(:player1_deck_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:player1_deck_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:player1_deck_id]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.player1_deck_id = 'one' @dummy.send(:player1_deck_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:player1_deck_id]).not_to be_empty end end describe '#player2_deck_id_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.player2_deck_id = 1 @dummy.send(:player2_deck_id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:player2_deck_id_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.player2_deck_id = 'one' @dummy.send(:player2_deck_id_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:player2_deck_id]).not_to be_empty end end describe '#player2_deck_id_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.player2_deck_id = 1 @dummy.send(:player2_deck_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:player2_deck_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:player2_deck_id]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.player2_deck_id = 'one' @dummy.send(:player2_deck_id_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:player2_deck_id]).not_to be_empty end end describe '#random_seed_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.random_seed = 1 @dummy.send(:random_seed_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:random_seed_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.random_seed = 'one' @dummy.send(:random_seed_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:random_seed]).not_to be_empty end end describe '#random_seed_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.random_seed = 1 @dummy.send(:random_seed_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:random_seed_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:random_seed]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.random_seed = 'one' @dummy.send(:random_seed_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:random_seed]).not_to be_empty end end describe '#status_is_a_string' do it 'does not add an error when String is a String' do @dummy.status = 'one' @dummy.send(:status_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:status_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.status = 1 @dummy.send(:status_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:status]).not_to be_empty end end describe '#status_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.status = 'one' @dummy.send(:status_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:status_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:status]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.status = 1 @dummy.send(:status_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:status]).not_to be_empty end end describe '#winner_id_is_a_string' do it 'does not add an error when String is a String' do @dummy.winner_id = 'one' @dummy.send(:winner_id_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:winner_id_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.winner_id = 1 @dummy.send(:winner_id_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:winner_id]).not_to be_empty end end describe '#winner_id_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.winner_id = 'one' @dummy.send(:winner_id_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:winner_id_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:winner_id]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.winner_id = 1 @dummy.send(:winner_id_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:winner_id]).not_to be_empty end end describe '#mould_id_is_a_string' do it 'does not add an error when String is a String' do @dummy.mould_id = 'one' @dummy.send(:mould_id_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:mould_id_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.mould_id = 1 @dummy.send(:mould_id_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:mould_id]).not_to be_empty end end describe '#mould_id_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.mould_id = 'one' @dummy.send(:mould_id_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:mould_id_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:mould_id]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.mould_id = 1 @dummy.send(:mould_id_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:mould_id]).not_to be_empty end end describe '#kind_is_a_string' do it 'does not add an error when String is a String' do @dummy.kind = 'one' @dummy.send(:kind_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:kind_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.kind = 1 @dummy.send(:kind_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:kind]).not_to be_empty end end describe '#kind_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.kind = 'one' @dummy.send(:kind_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:kind_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:kind]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.kind = 1 @dummy.send(:kind_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:kind]).not_to be_empty end end describe '#set_is_a_string' do it 'does not add an error when String is a String' do @dummy.set = 'one' @dummy.send(:set_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:set_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.set = 1 @dummy.send(:set_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:set]).not_to be_empty end end describe '#set_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.set = 'one' @dummy.send(:set_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:set_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:set]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.set = 1 @dummy.send(:set_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:set]).not_to be_empty end end describe '#description_is_a_string' do it 'does not add an error when String is a String' do @dummy.description = 'one' @dummy.send(:description_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:description_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.description = 1 @dummy.send(:description_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:description]).not_to be_empty end end describe '#description_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.description = 'one' @dummy.send(:description_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:description_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:description]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.description = 1 @dummy.send(:description_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:description]).not_to be_empty end end describe '#rank_is_a_string' do it 'does not add an error when String is a String' do @dummy.rank = 'one' @dummy.send(:rank_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:rank_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.rank = 1 @dummy.send(:rank_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:rank]).not_to be_empty end end describe '#rank_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.rank = 'one' @dummy.send(:rank_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:rank_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:rank]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.rank = 1 @dummy.send(:rank_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:rank]).not_to be_empty end end describe '#type_is_a_string' do it 'does not add an error when String is a String' do @dummy.type = 'one' @dummy.send(:type_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:type_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.type = 1 @dummy.send(:type_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:type]).not_to be_empty end end describe '#type_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.type = 'one' @dummy.send(:type_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:type_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:type]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.type = 1 @dummy.send(:type_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:type]).not_to be_empty end end describe '#rarity_is_a_string' do it 'does not add an error when String is a String' do @dummy.rarity = 'one' @dummy.send(:rarity_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:rarity_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.rarity = 1 @dummy.send(:rarity_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:rarity]).not_to be_empty end end describe '#rarity_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.rarity = 'one' @dummy.send(:rarity_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:rarity_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:rarity]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.rarity = 1 @dummy.send(:rarity_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:rarity]).not_to be_empty end end describe '#frame_is_a_string' do it 'does not add an error when String is a String' do @dummy.frame = 'one' @dummy.send(:frame_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:frame_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.frame = 1 @dummy.send(:frame_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:frame]).not_to be_empty end end describe '#frame_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.frame = 'one' @dummy.send(:frame_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:frame_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:frame]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.frame = 1 @dummy.send(:frame_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:frame]).not_to be_empty end end describe '#damage_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.damage = 1 @dummy.send(:damage_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:damage_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.damage = 'one' @dummy.send(:damage_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:damage]).not_to be_empty end end describe '#damage_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.damage = 1 @dummy.send(:damage_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:damage_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:damage]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.damage = 'one' @dummy.send(:damage_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:damage]).not_to be_empty end end describe '#health_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.health = 1 @dummy.send(:health_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:health_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.health = 'one' @dummy.send(:health_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:health]).not_to be_empty end end describe '#health_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.health = 1 @dummy.send(:health_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:health_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:health]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.health = 'one' @dummy.send(:health_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:health]).not_to be_empty end end describe '#cost_is_a_non_negative_integer' do it 'does not add an error when Integer is a Integer' do @dummy.cost = 1 @dummy.send(:cost_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:cost_is_a_non_negative_integer) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when Integer is a not a Integer' do @dummy.cost = 'one' @dummy.send(:cost_is_a_non_negative_integer) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:cost]).not_to be_empty end end describe '#cost_is_a_non_negative_integer_and_not_null' do it 'does not add an error when Integer is a Integer' do @dummy.cost = 1 @dummy.send(:cost_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when Integer is nil and nullable is true' do @dummy.send(:cost_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:cost]).not_to be_empty end it 'adds an error when Integer is a not a Integer' do @dummy.cost = 'one' @dummy.send(:cost_is_a_non_negative_integer_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:cost]).not_to be_empty end end describe '#ability_is_a_string' do it 'does not add an error when String is a String' do @dummy.ability = 'one' @dummy.send(:ability_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:ability_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.ability = 1 @dummy.send(:ability_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:ability]).not_to be_empty end end describe '#ability_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.ability = 'one' @dummy.send(:ability_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:ability_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:ability]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.ability = 1 @dummy.send(:ability_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:ability]).not_to be_empty end end describe '#image_url_is_a_string' do it 'does not add an error when String is a String' do @dummy.image_url = 'one' @dummy.send(:image_url_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:image_url_is_a_string) expect(@dummy.errors.messages.empty?).to be true end it 'adds an error when String is a not a String' do @dummy.image_url = 1 @dummy.send(:image_url_is_a_string) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:image_url]).not_to be_empty end end describe '#image_url_is_a_string_and_not_null' do it 'does not add an error when String is a String' do @dummy.image_url = 'one' @dummy.send(:image_url_is_a_string_and_not_null) expect(@dummy.errors.messages.empty?).to be true end it 'does not add an error when String is nil and nullable is true' do @dummy.send(:image_url_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:image_url]).not_to be_empty end it 'adds an error when String is a not a String' do @dummy.image_url = 1 @dummy.send(:image_url_is_a_string_and_not_null) expect(@dummy.errors.messages.size).to eq 1 expect(@dummy.errors.messages[:image_url]).not_to be_empty end end end
36.614312
109
0.698942
e996080237815f94e388b012634e7d6c4f708947
10,255
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Group or Project invitations', :aggregate_failures do let(:user) { create(:user, email: '[email protected]') } let(:owner) { create(:user, name: 'John Doe') } let(:group) { create(:group, name: 'Owned') } let(:project) { create(:project, :repository, namespace: group) } let(:group_invite) { group.group_members.invite.last } before do stub_application_setting(require_admin_approval_after_user_signup: false) project.add_maintainer(owner) group.add_owner(owner) group.add_developer('[email protected]', owner) group_invite.generate_invite_token! end def confirm_email(new_user) new_user_token = User.find_by_email(new_user.email).confirmation_token visit user_confirmation_path(confirmation_token: new_user_token) end def fill_in_sign_up_form(new_user) fill_in 'new_user_first_name', with: new_user.first_name fill_in 'new_user_last_name', with: new_user.last_name fill_in 'new_user_username', with: new_user.username fill_in 'new_user_email', with: new_user.email fill_in 'new_user_password', with: new_user.password click_button 'Register' end def fill_in_sign_in_form(user) fill_in 'user_login', with: user.email fill_in 'user_password', with: user.password check 'user_remember_me' click_button 'Sign in' end def fill_in_welcome_form select 'Software Developer', from: 'user_role' click_button 'Get started!' end context 'when signed out' do before do visit invite_path(group_invite.raw_invite_token) end it 'renders sign in page with sign in notice' do expect(current_path).to eq(new_user_registration_path) expect(page).to have_content('To accept this invitation, create an account or sign in') end it 'pre-fills the "Username or email" field on the sign in box with the invite_email from the invite' do click_link 'Sign in' expect(find_field('Username or email').value).to eq(group_invite.invite_email) end it 'pre-fills the Email field on the sign up box with the invite_email from the invite' do expect(find_field('Email').value).to eq(group_invite.invite_email) end it 'sign in, grants access and redirects to group page' do click_link 'Sign in' fill_in_sign_in_form(user) expect(current_path).to eq(group_path(group)) expect(page).to have_content('You have been granted Developer access to group Owned.') end end context 'when signed in as an existing member' do before do sign_in(owner) end it 'shows message user already a member' do visit invite_path(group_invite.raw_invite_token) expect(page).to have_link(owner.name, href: user_url(owner)) expect(page).to have_content('However, you are already a member of this group.') end end context 'when inviting an unregistered user' do let(:new_user) { build_stubbed(:user) } let(:invite_email) { new_user.email } let(:group_invite) { create(:group_member, :invited, group: group, invite_email: invite_email, created_by: owner) } let!(:project_invite) { create(:project_member, :invited, project: project, invite_email: invite_email) } context 'when registering using invitation email' do before do stub_application_setting(send_user_confirmation_email: send_email_confirmation) visit invite_path(group_invite.raw_invite_token) end context 'with admin approval required enabled' do before do stub_application_setting(require_admin_approval_after_user_signup: true) end let(:send_email_confirmation) { true } it 'does not sign the user in' do fill_in_sign_up_form(new_user) expect(current_path).to eq(new_user_session_path) expect(page).to have_content('You have signed up successfully. However, we could not sign you in because your account is awaiting approval from your GitLab administrator') end end context 'email confirmation disabled' do let(:send_email_confirmation) { false } it 'signs up and redirects to the dashboard page with all the projects/groups invitations automatically accepted' do fill_in_sign_up_form(new_user) fill_in_welcome_form expect(current_path).to eq(dashboard_projects_path) expect(page).to have_content(project.full_name) visit group_path(group) expect(page).to have_content(group.full_name) end context 'the user sign-up using a different email address' do let(:invite_email) { build_stubbed(:user).email } it 'signs up and redirects to the invitation page' do fill_in_sign_up_form(new_user) fill_in_welcome_form expect(current_path).to eq(invite_path(group_invite.raw_invite_token)) end end end context 'email confirmation enabled' do let(:send_email_confirmation) { true } context 'when soft email confirmation is not enabled' do before do allow(User).to receive(:allow_unconfirmed_access_for).and_return 0 end it 'signs up and redirects to root page with all the project/groups invitation automatically accepted' do fill_in_sign_up_form(new_user) confirm_email(new_user) fill_in_sign_in_form(new_user) fill_in_welcome_form expect(current_path).to eq(root_path) expect(page).to have_content(project.full_name) visit group_path(group) expect(page).to have_content(group.full_name) end end context 'when soft email confirmation is enabled' do before do allow(User).to receive(:allow_unconfirmed_access_for).and_return 2.days end it 'signs up and redirects to root page with all the project/groups invitation automatically accepted' do fill_in_sign_up_form(new_user) fill_in_welcome_form confirm_email(new_user) expect(current_path).to eq(root_path) expect(page).to have_content(project.full_name) visit group_path(group) expect(page).to have_content(group.full_name) end end it "doesn't accept invitations until the user confirms their email" do fill_in_sign_up_form(new_user) fill_in_welcome_form sign_in(owner) visit project_project_members_path(project) expect(page).to have_content 'Invited' end context 'the user sign-up using a different email address' do let(:invite_email) { build_stubbed(:user).email } context 'when soft email confirmation is not enabled' do before do stub_feature_flags(soft_email_confirmation: false) allow(User).to receive(:allow_unconfirmed_access_for).and_return 0 end it 'signs up and redirects to the invitation page' do fill_in_sign_up_form(new_user) confirm_email(new_user) fill_in_sign_in_form(new_user) fill_in_welcome_form expect(current_path).to eq(invite_path(group_invite.raw_invite_token)) end end context 'when soft email confirmation is enabled' do before do stub_feature_flags(soft_email_confirmation: true) allow(User).to receive(:allow_unconfirmed_access_for).and_return 2.days end it 'signs up and redirects to the invitation page' do fill_in_sign_up_form(new_user) fill_in_welcome_form expect(current_path).to eq(invite_path(group_invite.raw_invite_token)) end end end end end context 'when declining the invitation' do let(:send_email_confirmation) { true } context 'as an existing user' do let(:group_invite) { create(:group_member, user: user, group: group, created_by: owner) } context 'when signed in' do before do sign_in(user) visit decline_invite_path(group_invite.raw_invite_token) end it 'declines application and redirects to dashboard' do expect(current_path).to eq(dashboard_projects_path) expect(page).to have_content('You have declined the invitation to join group Owned.') expect { group_invite.reload }.to raise_error ActiveRecord::RecordNotFound end end context 'when signed out' do before do visit decline_invite_path(group_invite.raw_invite_token) end it 'declines application and redirects to sign in page' do expect(current_path).to eq(new_user_session_path) expect(page).to have_content('You have declined the invitation to join group Owned.') expect { group_invite.reload }.to raise_error ActiveRecord::RecordNotFound end end end context 'as a non-existing user' do before do visit decline_invite_path(group_invite.raw_invite_token) end it 'declines application and shows a decline page' do expect(current_path).to eq(decline_invite_path(group_invite.raw_invite_token)) expect(page).to have_content('You successfully declined the invitation') expect { group_invite.reload }.to raise_error ActiveRecord::RecordNotFound end end end context 'when accepting the invitation' do let(:send_email_confirmation) { true } before do sign_in(user) visit invite_path(group_invite.raw_invite_token) end it 'grants access and redirects to group page' do expect(group.users.include?(user)).to be false page.click_link 'Accept invitation' expect(current_path).to eq(group_path(group)) expect(page).to have_content('You have been granted Owner access to group Owned.') expect(group.users.include?(user)).to be true end end end end
34.64527
181
0.674305
7a2f928d7f7bfc58016c978bc87a0ae223939bc9
480
module Twitter::API::Endpoint class Adapter < Trailblazer::Endpoint::Adapter def success(_ctx, api:, model:, representer_class:, **) api.body(representer_class.new(model)) end def failure(_ctx, api:, error:, **) api.error(error, 422) end def unauthenticated(_ctx, api:, **) api.error!('401 Unauthorized', 401) end def invalid_data(_ctx, api:, contract:, **) api.error!(contract.errors.full_messages, 422) end end end
24
59
0.641667
1aaf8c51d5e0f92fc0099919204219c0e1fc5513
588
module ConvertApi class Configuration attr_accessor :api_secret attr_accessor :base_uri attr_accessor :connect_timeout attr_accessor :read_timeout attr_accessor :conversion_timeout attr_accessor :conversion_timeout_delta attr_accessor :upload_timeout attr_accessor :download_timeout def initialize @base_uri = URI('https://v2.convertapi.com/') @connect_timeout = 15 @read_timeout = 120 @conversion_timeout = 180 @conversion_timeout_delta = 20 @upload_timeout = 600 @download_timeout = 600 end end end
25.565217
51
0.719388
b9c09a16cf889e42a4397c70944965c9bcd6187c
13,569
class GradesController < ApplicationController helper :file helper :submitted_content helper :penalty include PenaltyHelper include StudentTaskHelper def action_allowed? case params[:action] when 'view_my_scores' ['Instructor', 'Teaching Assistant', 'Administrator', 'Super-Administrator', 'Student'].include? current_role_name and are_needed_authorizations_present?(params[:id], "reader", "reviewer") and check_self_review_status when 'view_team' if ['Student'].include? current_role_name # students can only see the head map for their own team participant = AssignmentParticipant.find(params[:id]) session[:user].id == participant.user_id else true end else ['Instructor', 'Teaching Assistant', 'Administrator', 'Super-Administrator'].include? current_role_name end end # the view grading report provides the instructor with an overall view of all the grades for # an assignment. It lists all participants of an assignment and all the reviews they received. # It also gives a final score, which is an average of all the reviews and greatest difference # in the scores of all the reviews. def view @assignment = Assignment.find(params[:id]) @questions = {} questionnaires = @assignment.questionnaires if @assignment.varying_rubrics_by_round? retrieve_questions questionnaires else # if this assignment does not have "varying rubric by rounds" feature questionnaires.each do |questionnaire| @questions[questionnaire.symbol] = questionnaire.questions end end @scores = @assignment.scores(@questions) averages = calculate_average_vector(@assignment.scores(@questions)) @average_chart = bar_chart(averages, 300, 100, 5) @avg_of_avg = mean(averages) calculate_all_penalties(@assignment.id) end # This method is used to retrieve questions for different review rounds def retrieve_questions(questionnaires) questionnaires.each do |questionnaire| round = AssignmentQuestionnaire.where(assignment_id: @assignment.id, questionnaire_id: questionnaire.id).first.used_in_round questionnaire_symbol = if (!round.nil?) (questionnaire.symbol.to_s+round.to_s).to_sym else questionnaire.symbol end @questions[questionnaire_symbol] = questionnaire.questions end end def view_my_scores @participant = AssignmentParticipant.find(params[:id]) @team_id = TeamsUser.team_id(@participant.parent_id, @participant.user_id) return if redirect_when_disallowed @assignment = @participant.assignment @questions = {} # A hash containing all the questions in all the questionnaires used in this assignment questionnaires = @assignment.questionnaires retrieve_questions questionnaires # @pscore has the newest versions of response for each response map, and only one for each response map (unless it is vary rubric by round) @pscore = @participant.scores(@questions) make_chart @topic_id = SignedUpTeam.topic_id(@participant.assignment.id, @participant.user_id) @stage = @participant.assignment.get_current_stage(@topic_id) calculate_all_penalties(@assignment.id) # prepare feedback summaries summary_ws_url = WEBSERVICE_CONFIG["summary_webservice_url"] sum = SummaryHelper::Summary.new.summarize_reviews_by_reviewee(@questions, @assignment, @team_id, summary_ws_url) @summary = sum.summary @avg_scores_by_round = sum.avg_scores_by_round @avg_scores_by_criterion = sum.avg_scores_by_criterion end def view_team # get participant, team, questionnaires for assignment. @participant = AssignmentParticipant.find(params[:id]) @assignment = @participant.assignment @team = @participant.team @team_id = @team.id questionnaires = @assignment.questionnaires @vmlist = [] # loop through each questionnaire, and populate the view model for all data necessary # to render the html tables. questionnaires.each do |questionnaire| @round = if @assignment.varying_rubrics_by_round? && questionnaire.type == "ReviewQuestionnaire" AssignmentQuestionnaire.find_by_assignment_id_and_questionnaire_id(@assignment.id, questionnaire.id).used_in_round else nil end vm = VmQuestionResponse.new(questionnaire, @round, @assignment.rounds_of_reviews) questions = questionnaire.questions vm.add_questions(questions) vm.add_team_members(@team) vm.add_reviews(@participant, @team, @assignment.varying_rubrics_by_round?) vm.get_number_of_comments_greater_than_10_words @vmlist << vm end @current_role_name = current_role_name end def edit @participant = AssignmentParticipant.find(params[:id]) @assignment = @participant.assignment list_questions @assignment @scores = @participant.scores(@questions) end def instructor_review participant = AssignmentParticipant.find(params[:id]) reviewer = AssignmentParticipant.where(user_id: session[:user].id, parent_id: participant.assignment.id).first if reviewer.nil? reviewer = AssignmentParticipant.create(user_id: session[:user].id, parent_id: participant.assignment.id) reviewer.set_handle end review_exists = true if participant.assignment.team_assignment? reviewee = participant.team review_mapping = ReviewResponseMap.where(reviewee_id: reviewee.id, reviewer_id: reviewer.id).first if review_mapping.nil? review_exists = false review_mapping = ReviewResponseMap.create(reviewee_id: participant.team.id, reviewer_id: reviewer.id, reviewed_object_id: participant.assignment.id) review = Response.find_by_map_id(review_mapping.map_id) unless review_exists redirect_to controller: 'response', action: 'new', id: review_mapping.map_id, return: "instructor" else redirect_to controller: 'response', action: 'edit', id: review.id, return: "instructor" end end end end def open send_file(params['fname'], disposition: 'inline') end # This method is used from edit methods def list_questions(assignment) @questions = {} questionnaires = assignment.questionnaires questionnaires.each do |questionnaire| @questions[questionnaire.symbol] = questionnaire.questions end end def update participant = AssignmentParticipant.find(params[:id]) total_score = params[:total_score] if sprintf("%.2f", total_score) != params[:participant][:grade] participant.update_attribute(:grade, params[:participant][:grade]) message = if participant.grade.nil? "The computed score will be used for "+participant.user.name+"." else "A score of "+params[:participant][:grade]+"% has been saved for "+participant.user.name+"." end end flash[:note] = message redirect_to action: 'edit', id: params[:id] end def save_grade_and_comment_for_submission participant = AssignmentParticipant.find(params[:participant_id]) @team = participant.team @team.grade_for_submission = params[:grade_for_submission] @team.comment_for_submission = params[:comment_for_submission] begin @team.save rescue flash[:error] = $ERROR_INFO end redirect_to controller: 'grades', action: 'view_team', id: params[:participant_id] end private def redirect_when_disallowed # For author feedback, participants need to be able to read feedback submitted by other teammates. # If response is anything but author feedback, only the person who wrote feedback should be able to see it. ## This following code was cloned from response_controller. # ACS Check if team count is more than 1 instead of checking if it is a team assignment if @participant.assignment.max_team_size > 1 team = @participant.team unless team.nil? unless team.has_user session[:user] redirect_to '/denied?reason=You are not on the team that wrote this feedback' return true end end else reviewer = AssignmentParticipant.where(user_id: session[:user].id, parent_id: @participant.assignment.id).first return true unless current_user_id?(reviewer.try(:user_id)) end false end def get_body_text(submission) if submission role = "reviewer" item = "submission" else role = "metareviewer" item = "review" end "Hi ##[recipient_name], You submitted a score of ##[recipients_grade] for assignment ##[assignment_name] that varied greatly from another " + role + "'s score for the same " + item + ". The Expertiza system has brought this to my attention." end def calculate_all_penalties(assignment_id) @all_penalties = {} @assignment = Assignment.find(assignment_id) calculate_for_participants = true unless @assignment.is_penalty_calculated Participant.where(parent_id: assignment_id).each do |participant| penalties = calculate_penalty(participant.id) @total_penalty = 0 unless (penalties[:submission].zero? || penalties[:review].zero? || penalties[:meta_review].zero?) @total_penalty = (penalties[:submission] + penalties[:review] + penalties[:meta_review]) l_policy = LatePolicy.find(@assignment.late_policy_id) if (@total_penalty > l_policy.max_penalty) @total_penalty = l_policy.max_penalty end calculate_penatly_attributes(@participant) if calculate_for_participants end assign_all_penalties(participant, penalties) end unless @assignment.is_penalty_calculated @assignment.update_attribute(:is_penalty_calculated, true) end end def calculate_penatly_attributes(_participant) penalty_attr1 = {deadline_type_id: 1, participant_id: @participant.id, penalty_points: penalties[:submission]} CalculatedPenalty.create(penalty_attr1) penalty_attr2 = {deadline_type_id: 2, participant_id: @participant.id, penalty_points: penalties[:review]} CalculatedPenalty.create(penalty_attr2) penalty_attr3 = {deadline_type_id: 5, participant_id: @participant.id, penalty_points: penalties[:meta_review]} CalculatedPenalty.create(penalty_attr3) end def assign_all_penalties(participant, penalties) @all_penalties[participant.id] = {} @all_penalties[participant.id][:submission] = penalties[:submission] @all_penalties[participant.id][:review] = penalties[:review] @all_penalties[participant.id][:meta_review] = penalties[:meta_review] @all_penalties[participant.id][:total_penalty] = @total_penalty end def make_chart @grades_bar_charts = {} if @pscore[:review] scores = [] if @assignment.varying_rubrics_by_round? for round in [email protected]_of_reviews responses = @pscore[:review][:assessments].reject {|response| response.round != round } scores = scores.concat(get_scores_for_chart(responses, 'review' + round.to_s)) scores -= [-1.0] end @grades_bar_charts[:review] = bar_chart(scores) else scores = get_scores_for_chart @pscore[:review][:assessments], 'review' scores -= [-1.0] @grades_bar_charts[:review] = bar_chart(scores) end end if @pscore[:metareview] scores = get_scores_for_chart @pscore[:metareview][:assessments], 'metareview' scores -= [-1.0] @grades_bar_charts[:metareview] = bar_chart(scores) end if @pscore[:feedback] scores = get_scores_for_chart @pscore[:feedback][:assessments], 'feedback' scores -= [-1.0] @grades_bar_charts[:feedback] = bar_chart(scores) end if @pscore[:teammate] scores = get_scores_for_chart @pscore[:teammate][:assessments], 'teammate' scores -= [-1.0] @grades_bar_charts[:teammate] = bar_chart(scores) end end def get_scores_for_chart(reviews, symbol) scores = [] reviews.each do |review| scores << Answer.get_total_score(response: [review], questions: @questions[symbol.to_sym], q_types: []) end scores end def calculate_average_vector(scores) scores[:teams].reject! {|_k, v| v[:scores][:avg].nil? } scores[:teams].map {|_k, v| v[:scores][:avg].to_i } end def bar_chart(scores, width = 100, height = 100, spacing = 1) link = nil GoogleChart::BarChart.new("#{width}x#{height}", " ", :vertical, false) do |bc| data = scores bc.data "Line green", data, '990000' bc.axis :y, range: [0, data.max], positions: [data.min, data.max] bc.show_legend = false bc.stacked = false bc.width_spacing_options(bar_width: (width - 30) / (data.size + 1), bar_spacing: 1, group_spacing: spacing) bc.data_encoding = :extended link = bc.to_url end link end def check_self_review_status participant = Participant.find(params[:id]) assignment = participant.try(:assignment) if assignment.try(:is_selfreview_enabled) and unsubmitted_self_review?(participant.try(:id)) return false else return true end end def mean(array) array.inject(0) {|sum, x| sum += x } / array.size.to_f end def mean_and_standard_deviation(array) m = mean(array) variance = array.inject(0) {|variance, x| variance += (x - m)**2 } [m, Math.sqrt(variance/(array.size-1))] end end
36.772358
169
0.701526
113ae37e94b5cd64965a6a2cf3608de182645ff9
702
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'sqflite' s.version = '0.0.1' s.summary = 'A new flutter plugin project.' s.description = <<-DESC A new flutter plugin project. DESC s.homepage = 'http://example.com' s.license = { :file => '../LICENSE' } s.author = { 'Your Company' => '[email protected]' } s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.public_header_files = 'Classes/**/*.h' s.dependency 'Flutter' s.dependency 'WCDB.swift' , '~> 1.0.8.2' s.ios.deployment_target = '8.0' end
30.521739
83
0.541311
b94f5136d6eed7398078f050283fc3fd0dd1b08a
2,264
require 'set' module Stockfish module Functionable def functions_filter self.class.jq_functions_chain.map(&:to_filter) end def self.included(base) base.extend ClassMethods end module ClassMethods def define_function(name, body = nil, depends_on: []) body = block_given? ? yield : body func = Stockfish::Function.new(name, body, depends_on) jq_functions[func.name] = func end def load_function(name, path) if File.extname(path) != '.jq' raise(ArgumentError, 'File must have extension .jq') end File.open(path) do |file| define_function(name, file.read) end end def resolve_dependencies(func) deps = func.dependencies.map { |dep| resolve_dependencies(load_lazy_function(dep)) } deps + [func] end def jq_functions_chain stack = Set.new selected_functions.merge(jq_functions).values.each do |func| stack.merge(resolve_dependencies(func).flatten) end stack end def inherited_functions ancestors.map do |klass| klass.jq_functions if klass.respond_to?(:jq_functions) end.compact.flatten end def load_lazy_function(name) lazy_functions[name] || raise(Stockfish::MissingFunctionError, "Missing function: '#{name}'") end # Functions defined in subclasses def lazy_functions inherited_functions.inject(&:merge) end def all_dependencies ancestors.reverse.map do |klass| klass.dependencies if klass.respond_to?(:dependencies) end.compact.inject(&:merge) end def selected_functions all_dependencies.reduce({}) do |h, k| if !lazy_functions.has_key?(k) raise(Stockfish::MissingFunctionError, "Missing function: '#{k}'") end h[k] = lazy_functions[k] h end end def depends_on(*function_names) function_names.each do |name| dependencies.add(name.to_sym) end end def dependencies @dependencies ||= Set.new end def jq_functions @jq_functions ||= {} end end end end
24.344086
101
0.609541
33e87f20aa4facffc4f8b6ced1ffeea803436601
240
require 'serverspec' set :backend, :exec def cmd(exec, match) describe command(exec), sudo: false do its(:stdout) { should match match } end end cmd 'git --version', '1.9.1' cmd 'cd ${HOME}/adhoc; git status', 'On branch staging'
20
55
0.670833
ffc3fa7ae4215d550e0ad906d1cc9192adac9d48
534
class SessionsController < ApplicationController def new redirect_to user_path(current_user) if user_signed_in? end def create user = User.find_by(email: params[:session][:email].downcase) if user && user.authenticate(params[:session][:password]) sign_in(user) redirect_to contacts_path(user) else flash.now[:danger] = 'Email ou senha invalidos...' render 'new' end end def destroy sign_out flash[:success] = 'Logout bem sucedido!' redirect_to entrar_path end end
23.217391
65
0.687266
ed1386b417fc5e63775ec0e7f7852eb7219c46bc
10,311
# -*- coding: utf-8 -*- require "time" require "cakewalk/formatting" module Cakewalk # This class serves two purposes. For one, it simply # represents incoming messages and allows for querying various # details (who sent the message, what kind of message it is, etc). # # At the same time, it allows **responding** to messages, which # means sending messages to either users or channels. class Message # @return [String] attr_reader :raw # @return [String] attr_reader :prefix # @return [String] attr_reader :command # @return [Array<String>] attr_reader :params # @return [Hash] attr_reader :tags # @return [Array<Symbol>] attr_reader :events # @api private attr_writer :events # @return [Time] # @since 2.0.0 attr_reader :time # @return [Bot] # @since 1.1.0 attr_reader :bot # @return [User] The user who sent this message attr_reader :user # @return [String, nil] attr_reader :server # @return [Integer, nil] the numeric error code, if any attr_reader :error # @return [String, nil] the command part of an CTCP message attr_reader :ctcp_command # @return [Channel] The channel in which this message was sent attr_reader :channel # @return [String, nil] the CTCP message, without \001 control characters attr_reader :ctcp_message # @return [Array<String>, nil] attr_reader :ctcp_args # @return [String, nil] attr_reader :message # @return [String, nil] The action message # @since 2.0.0 attr_reader :action_message # @return [Target] attr_reader :target # The STATUSMSG mode a channel message was sent to. # # Some IRC servers allow sending messages limited to people in a # channel who have a certain mode. For example, by sending a # message to `+#channel`, only people who are voiced, or have a # higher mode (op) will receive the message. # # This attribute contains the mode character the message was sent # to, or nil if it was a normal message. For the previous example, # this attribute would be set to `"v"`, for voiced. # # @return [String, nil] # @since 2.3.0 attr_reader :statusmsg_mode def initialize(msg, bot) @raw = msg @bot = bot @matches = {ctcp: {}, action: {}, other: {}} @events = [] @time = Time.now @statusmsg_mode = nil parse if msg end # @api private # @return [void] def parse match = @raw.match(/(?:^@([^:]+))?(?::?(\S+) )?(\S+)(.*)/) if match.captures[3].empty? # no IRCv3 tags @prefix, @command, raw_params = match.captures else tags, @prefix, @command, raw_params = match.captures end @params = parse_params(raw_params) @tags = parse_tags(tags) @user = parse_user @channel, @statusmsg_mode = parse_channel @target = @channel || @user @server = parse_server @error = parse_error @message = parse_message @ctcp_message = parse_ctcp_message @ctcp_command = parse_ctcp_command @ctcp_args = parse_ctcp_args @action_message = parse_action_message end # @group Type checking # @return [Boolean] true if the message is an numeric reply (as # opposed to a command) def numeric_reply? [email protected](/^\d{3}$/) end # @return [Boolean] true if the message describes an error def error? [email protected]? end # @return [Boolean] true if this message was sent in a channel def channel? [email protected]? end # @return [Boolean] true if the message is an CTCP message def ctcp? !!(@params.last =~ /\001.+\001/) end # @return [Boolean] true if the message is an action (/me) # @since 2.0.0 def action? @ctcp_command == "ACTION" end # @endgroup # @api private # @return [MatchData] def match(regexp, type, strip_colors) text = "" case type when :ctcp text = ctcp_message when :action text = action_message else text = message.to_s type = :other end if strip_colors text = Cakewalk::Formatting.unformat(text) end @matches[type][regexp] ||= text.match(regexp) end # @group Replying # Replies to a message, automatically determining if it was a # channel or a private message. # # If the message is a STATUSMSG, i.e. it was send to `+#channel` # or `@#channel` instead of `#channel`, the reply will be sent as # the same kind of STATUSMSG. See {#statusmsg_mode} for more # information on STATUSMSG. # # @param [String] text the message # @param [Boolean] prefix if prefix is true and the message was in # a channel, the reply will be prefixed by the nickname of whoever # send the mesage # @return [void] def reply(text, prefix = false) text = text.to_s if @channel && prefix text = text.split("\n").map {|l| "#{user.nick}: #{l}"}.join("\n") end reply_target.send(text) end # Like {#reply}, but using {Target#safe_send} instead # # @param (see #reply) # @return (see #reply) def safe_reply(text, prefix = false) text = text.to_s if channel && prefix text = "#{@user.nick}: #{text}" end reply_target.safe_send(text) end # Reply to a message with an action. # # For its behaviour with regard to STATUSMSG, see {#reply}. # # @param [String] text the action message # @return [void] def action_reply(text) text = text.to_s reply_target.action(text) end # Like {#action_reply}, but using {Target#safe_action} instead # # @param (see #action_reply) # @return (see #action_reply) def safe_action_reply(text) text = text.to_s reply_target.safe_action(text) end # Reply to a CTCP message # # @return [void] def ctcp_reply(answer) return unless ctcp? @user.notice "\001#{@ctcp_command} #{answer}\001" end # @endgroup # @return [String] # @since 1.1.0 def to_s "#<Cakewalk::Message @raw=#{@raw.chomp.inspect} @params=#{@params.inspect} channel=#{@channel.inspect} user=#{@user.inspect}>" end private def reply_target if @channel.nil? || @statusmsg_mode.nil? return @target end prefix = @bot.irc.isupport["PREFIX"][@statusmsg_mode] return Target.new(prefix + @channel.name, @bot) end def regular_command? !numeric_reply? # a command can only be numeric or "regular"… end def parse_params(raw_params) params = [] if match = raw_params.match(/(?:^:| :)(.*)$/) params = match.pre_match.split(" ") params << match[1] else params = raw_params.split(" ") end return params end def parse_tags(raw_tags) return {} if raw_tags.nil? def to_symbol(string) return string.gsub(/-/, "_").downcase.to_sym end tags = {} raw_tags.split(";").each do |tag| tag_name, tag_value = tag.split("=") if tag_value =~ /,/ tag_value = tag_value.split(',') elsif tag_value.nil? tag_value = tag_name end if tag_name =~ /\// vendor, tag_name = tag_name.split('/') tags[to_symbol(vendor)] = { to_symbol(tag_name) => tag_value } else tags[to_symbol(tag_name)] = tag_value end end return tags end def parse_user return unless @prefix nick = @prefix[/^(\S+)!/, 1] user = @prefix[/^\S+!(\S+)@/, 1] host = @prefix[/@(\S+)$/, 1] return nil if nick.nil? return @bot.user_list.find_ensured(user, nick, host) end def parse_channel # has to be called after parse_params return nil if @params.empty? case @command when "INVITE", Constants::RPL_CHANNELMODEIS.to_s, Constants::RPL_BANLIST.to_s @bot.channel_list.find_ensured(@params[1]) when Constants::RPL_NAMEREPLY.to_s @bot.channel_list.find_ensured(@params[2]) else # Note that this will also find channels for messages that # don't actually include a channel parameter. For example # `QUIT :#sometext` will be interpreted as a channel. The # alternative to the currently used heuristic would be to # hardcode a list of commands that provide a channel argument. ch, status = privmsg_channel_name(@params.first) if ch.nil? && numeric_reply? && @params.size > 1 ch, status = privmsg_channel_name(@params[1]) end if ch return @bot.channel_list.find_ensured(ch), status end end end def privmsg_channel_name(s) chantypes = @bot.irc.isupport["CHANTYPES"] statusmsg = @bot.irc.isupport["STATUSMSG"] if statusmsg.include?(s[0]) && chantypes.include?(s[1]) status = @bot.irc.isupport["PREFIX"].invert[s[0]] return s[1..-1], status elsif chantypes.include?(s[0]) return s, nil end end def parse_server return unless @prefix return if @prefix.match(/[@!]/) return @prefix[/^(\S+)/, 1] end def parse_error return @command.to_i if numeric_reply? && @command[/[45]\d\d/] end def parse_message # has to be called after parse_params if error? @error.to_s elsif regular_command? @params.last end end def parse_ctcp_message # has to be called after parse_params return unless ctcp? @params.last =~ /\001(.+)\001/ $1 end def parse_ctcp_command # has to be called after parse_ctcp_message return unless ctcp? @ctcp_message.split(" ").first end def parse_ctcp_args # has to be called after parse_ctcp_message return unless ctcp? @ctcp_message.split(" ")[1..-1] end def parse_action_message # has to be called after parse_ctcp_message return nil unless action? @ctcp_message.split(" ", 2).last end end end
26.303571
132
0.599845
872d1c44565f6df0dea09369869af2f448f709b4
2,726
class Field::FilePresenter < FieldPresenter delegate :tag, :number_to_human_size, :to => :view def input(form, method, options={}) item_type = options[:item_type] || field.item_type.slug # rubocop:disable Layout/LineLength field_category = field.belongs_to_category? ? "data-field-category=\"#{field.category_id}\" data-field-category-choice-id=\"#{field.category_choice.id}\" data-field-category-choice-set-id=\"#{field.category_choice_set.id}\"" : "" # rubocop:enable Layout/LineLength btn_label = field.multiple ? t('presenters.field.file.add_files') : t('presenters.field.file.add_file') render_html(form, method, item_type, field_category, btn_label) end def value return nil unless value? file_info end def value? return false if raw_value.blank? true end def file_info info = files_as_array.map do |file| "<div class=\"file-link\">" \ "<a href=\"#{file_url(file)}\" target=\"_blank\">" \ "<i class=\"fa fa-file\"></i> #{file['name']}" \ "</a>" \ ", #{number_to_human_size(file['size'], :prefix => :si)}" \ "<a style=\"margin-left: 7px;\" href=\"#{file_url(file)}\" download=\"#{file['name']}\">" \ "<i class=\"fa fa-download\"></i>" \ "</a>" \ "</div>" end info.join.html_safe end def file_url(file) file['path'].nil? ? nil : "/#{file['path']}" end def files_as_array raw_value.is_a?(Array) ? raw_value : [raw_value] end private # rubocop:disable Style/StringConcatenation def render_html(form, method, item_type, field_category, btn_label) [ form.text_area( "#{method}_json", input_defaults(options).reverse_merge(:rows => 1, 'data-field-type' => 'file') ), '<div class="form-component">', "<div class=\"form-group file-upload\" #{field_category} " \ "id=\"fileupload_#{method}\" " \ "data-field=\"#{method}\" " \ "data-field-type=\"#{field.type}\" " \ "data-multiple=\"#{field.multiple}\" " \ "data-required=\"#{field.required?}\" " \ "data-fieldname=\"#{field.name}\" " \ "data-upload-url=\"/#{field.catalog.slug}/#{I18n.locale}/admin/#{item_type}/upload\" " \ "data-file-types=\"#{field.types}\" " \ "data-file-size=\"#{field.max_file_size.megabytes}\" " \ "data-button-text=\"" + btn_label + "\"></div>", "<h4>", "<small>#{t('presenters.field.file.size_constraint', :max_size => field.max_file_size)}</small><br>", "<small>#{t('presenters.field.file.types_constraint', :types => field.types)}</small>", "</h4>", "</div>" ].compact.join.html_safe end # rubocop:enable Style/StringConcatenation end
33.654321
233
0.604916
bb525f7d330054d54bc32f2ac07ee6f3ede5d5ab
19,513
# frozen_string_literal: true require 'test_helper' class HelperMethodsTest < ActionView::TestCase include Gretel::ViewHelpers self.fixture_path = File.expand_path("../../test/fixtures", __FILE__) fixtures :all helper :application setup do Gretel.reset! end def itemscope_value ActionView::Helpers::TagHelper::BOOLEAN_ATTRIBUTES.include?("itemscope") ? "itemscope" : "" end # Breadcrumb generation test "basic breadcrumb" do breadcrumb :basic assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">About</span></div>}, breadcrumbs.to_s end test "breadcrumb with root" do breadcrumb :with_root assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">About</span></div>}, breadcrumbs.to_s end test "breadcrumb with parent" do breadcrumb :with_parent assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <a href="/about">About</a> &rsaquo; <span class="current">Contact</span></div>}, breadcrumbs.to_s end test "breadcrumb with autopath" do breadcrumb :with_autopath, projects(:one) assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">Test Project</span></div>}, breadcrumbs.to_s end test "breadcrumb with parent object" do breadcrumb :with_parent_object, issues(:one) assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <a href="/projects/1">Test Project</a> &rsaquo; <span class="current">Test Issue</span></div>}, breadcrumbs.to_s end test "multiple links" do breadcrumb :multiple_links assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <a href="/about/contact">Contact</a> &rsaquo; <span class="current">Contact form</span></div>}, breadcrumbs.to_s end test "multiple links with parent" do breadcrumb :multiple_links_with_parent assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <a href="/about">About</a> &rsaquo; <a href="/about/contact">Contact</a> &rsaquo; <span class="current">Contact form</span></div>}, breadcrumbs.to_s end test "semantic breadcrumb" do breadcrumb :with_root assert_dom_equal %{<div class="breadcrumbs" itemscope="#{itemscope_value}" itemtype="https://schema.org/BreadcrumbList"><span itemprop="itemListElement" itemscope="#{itemscope_value}" itemtype="https://schema.org/ListItem"><a itemprop="item" href="/"><span itemprop="name">Home</span></a><meta itemprop="position" content="1" /></span> &rsaquo; <span class="current" itemprop="itemListElement" itemscope="#{itemscope_value}" itemtype="https://schema.org/ListItem"><span itemprop="name">About</span><meta itemprop="item" content="http://test.host/about" /><meta itemprop="position" content="2" /></span></div>}, breadcrumbs(semantic: true).to_s end test "doesn't show root alone" do breadcrumb :root assert_dom_equal "", breadcrumbs.to_s end test "displays single fragment" do breadcrumb :root assert_dom_equal %{<div class="breadcrumbs"><span class="current">Home</span></div>}, breadcrumbs(display_single_fragment: true).to_s end test "displays single non-root fragment" do breadcrumb :basic assert_dom_equal %{<div class="breadcrumbs"><span class="current">About</span></div>}, breadcrumbs(autoroot: false, display_single_fragment: true).to_s end test "no breadcrumb" do assert_dom_equal "", breadcrumbs.to_s end test "links current breadcrumb" do breadcrumb :with_root assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <a href="/about" class="current">About</a></div>}, breadcrumbs(link_current: true).to_s end test "pretext" do breadcrumb :basic assert_dom_equal %{<div class="breadcrumbs"><span class="pretext">You are here:</span> <a href="/">Home</a> &rsaquo; <span class="current">About</span></div>}, breadcrumbs(pretext: "You are here:").to_s end test "posttext" do breadcrumb :basic assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">About</span> <span class="posttext">text after breadcrumbs</span></div>}, breadcrumbs(posttext: "text after breadcrumbs").to_s end test "autoroot disabled" do breadcrumb :basic assert_dom_equal "", breadcrumbs(autoroot: false).to_s end test "separator" do breadcrumb :with_root assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &raquo; <span class="current">About</span></div>}, breadcrumbs(separator: " &raquo; ").to_s end test "element id" do breadcrumb :basic assert_dom_equal %{<div class="breadcrumbs" id="custom_id"><a href="/">Home</a> &rsaquo; <span class="current">About</span></div>}, breadcrumbs(id: "custom_id").to_s end test "custom container class" do breadcrumb :basic assert_dom_equal %{<div class="custom_class"><a href="/">Home</a> &rsaquo; <span class="current">About</span></div>}, breadcrumbs(class: "custom_class").to_s end test "custom fragment class" do breadcrumb :basic assert_dom_equal %{<div class="breadcrumbs"><a class="custom_fragment_class" href="/">Home</a> &rsaquo; <span class="custom_fragment_class current">About</span></div>}, breadcrumbs(fragment_class: "custom_fragment_class").to_s end test "custom current class" do breadcrumb :basic assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="custom_current_class">About</span></div>}, breadcrumbs(current_class: "custom_current_class").to_s end test "custom pretext class" do breadcrumb :basic assert_dom_equal %{<div class="breadcrumbs"><span class="custom_pretext_class">You are here:</span> <a href="/">Home</a> &rsaquo; <span class="current">About</span></div>}, breadcrumbs(pretext: "You are here:", pretext_class: "custom_pretext_class").to_s end test "custom posttext class" do breadcrumb :basic assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">About</span> <span class="custom_posttext_class">after breadcrumbs</span></div>}, breadcrumbs(posttext: "after breadcrumbs", posttext_class: "custom_posttext_class").to_s end test "unsafe html" do breadcrumb :with_unsafe_html assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">Test &lt;strong&gt;bold text&lt;/strong&gt;</span></div>}, breadcrumbs.to_s end test "safe html" do breadcrumb :with_safe_html assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">Test <strong>bold text</strong></span></div>}, breadcrumbs.to_s end test "parent breadcrumb" do breadcrumb :multiple_links_with_parent parent = parent_breadcrumb assert_equal [:multiple_links_with_parent, "Contact", "/about/contact"], [parent.key, parent.text, parent.url] end test "yields parent breadcrumb" do breadcrumb :multiple_links_with_parent out = parent_breadcrumb do |parent| [parent.key, parent.text, parent.url] end assert_equal [:multiple_links_with_parent, "Contact", "/about/contact"], out end test "parent breadcrumb returns nil if not present" do breadcrumb :basic assert_nil parent_breadcrumb(autoroot: false) end test "parent breadcrumb yields only if present" do breadcrumb :basic out = parent_breadcrumb(autoroot: false) do "yielded" end assert_nil out end test "link keys" do breadcrumb :basic assert_equal [:root, :basic], breadcrumbs.keys end test "using breadcrumbs as array" do breadcrumb :basic breadcrumbs.tap do |links| assert_kind_of Array, links assert_equal 2, links.count end end test "sets current on last link in array" do breadcrumb :multiple_links_with_parent assert_equal [false, false, false, true], breadcrumbs.map(&:current?) end test "passing options to links" do breadcrumb :with_link_options breadcrumbs(autoroot: false).tap do |links| links[0].tap do |link| assert link.title? assert_equal "My Title", link.title assert link.other? assert_equal "Other Option", link.other assert !link.nonexistent? assert_nil link.nonexistent end links[1].tap do |link| assert link.some_option? assert_equal "Test", link.some_option end end assert_dom_equal %{<div class="breadcrumbs"><a href="/about">Test</a> &rsaquo; <span class="current">Other Link</span></div>}, breadcrumbs(autoroot: false).to_s end test "without link" do breadcrumb :without_link assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; Also without link &rsaquo; <span class="current">Without link</span></div>}, breadcrumbs.to_s end test "view context" do breadcrumb :using_view_helper assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">TestTest</span></div>}, breadcrumbs.to_s end test "multiple arguments" do breadcrumb :with_multiple_arguments, "One", "Two", "Three" assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <a href="/about">First OneOne then TwoTwo then ThreeThree</a> &rsaquo; <span class="current">One and Two and Three</span></div>}, breadcrumbs.to_s end test "from views folder" do breadcrumb :from_views assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">Breadcrumb From View</span></div>}, breadcrumbs.to_s end test "with_breadcrumb" do breadcrumb :basic assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">About</span></div>}, breadcrumbs.to_s with_breadcrumb(:with_parent_object, issues(:one)) do assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <a href="/projects/1">Test Project</a> &rsaquo; <span class="current">Test Issue</span></div>}, breadcrumbs.to_s end assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">About</span></div>}, breadcrumbs.to_s end test "calling breadcrumbs helper twice" do breadcrumb :with_parent 2.times do assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <a href="/about">About</a> &rsaquo; <span class="current">Contact</span></div>}, breadcrumbs.to_s end end test "breadcrumb not found" do assert_raises ArgumentError do breadcrumb :nonexistent breadcrumbs end end test "current link url is set to fullpath" do self.request = OpenStruct.new(fullpath: "/testpath?a=1&b=2") breadcrumb :basic assert_equal "/testpath?a=1&b=2", breadcrumbs.last.url end test "current link url is not set to fullpath using link_current_to_request_path=false" do self.request = OpenStruct.new(fullpath: "/testpath?a=1&b=2") breadcrumb :basic assert_equal "/about", breadcrumbs(:link_current_to_request_path => false).last.url end test "calling the breadcrumb method with wrong arguments" do assert_nothing_raised do breadcrumb :basic, test: 1 end assert_raises ArgumentError do breadcrumb end assert_raises ArgumentError do breadcrumb(pretext: "bla") end end test "inferred breadcrumb" do breadcrumb Project.first assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">Test Project</span></div>}, breadcrumbs.to_s end test "inferred parent" do breadcrumb :with_inferred_parent assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <a href="/projects/1">Test Project</a> &rsaquo; <span class="current">Test</span></div>}, breadcrumbs.to_s end # Styles test "default style" do breadcrumb :basic assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home</a> &rsaquo; <span class="current">About</span></div>}, breadcrumbs.to_s end test "ordered list style" do breadcrumb :basic assert_dom_equal %{<ol class="breadcrumbs"><li><a href="/">Home</a></li><li class="current">About</li></ol>}, breadcrumbs(style: :ol).to_s end test "unordered list style" do breadcrumb :basic assert_dom_equal %{<ul class="breadcrumbs"><li><a href="/">Home</a></li><li class="current">About</li></ul>}, breadcrumbs(style: :ul).to_s end test "bootstrap style" do breadcrumb :basic assert_dom_equal %{<ol class="breadcrumb"><li><a href="/">Home</a></li><li class="active">About</li></ol>}, breadcrumbs(style: :bootstrap).to_s end test "bootstrap4 style" do breadcrumb :basic assert_dom_equal %{<ol class="breadcrumb"><li class="breadcrumb-item"><a href="/">Home</a></li><li class="breadcrumb-item active">About</li></ol>}, breadcrumbs(style: :bootstrap4).to_s end test "foundation5 style" do breadcrumb :basic assert_dom_equal %{<ul class="breadcrumbs"><li><a href="/">Home</a></li><li class="current">About</li></ul>}, breadcrumbs(style: :foundation5).to_s end test "custom container and fragment tags" do breadcrumb :basic assert_dom_equal %{<c class="breadcrumbs"><f><a href="/">Home</a></f> &rsaquo; <f class="current">About</f></c>}, breadcrumbs(container_tag: :c, fragment_tag: :f).to_s end test "custom semantic container and fragment tags" do breadcrumb :basic assert_dom_equal %{<c class="breadcrumbs" itemscope="#{itemscope_value}" itemtype="https://schema.org/BreadcrumbList"><f itemprop="itemListElement" itemscope="#{itemscope_value}" itemtype="https://schema.org/ListItem"><a itemprop="item" href="/"><span itemprop="name">Home</span></a><meta itemprop="position" content="1" /></f> &rsaquo; <f class="current" itemprop="itemListElement" itemscope="#{itemscope_value}" itemtype="https://schema.org/ListItem"><span itemprop="name">About</span><meta itemprop="item" content="http://test.host/about" /><meta itemprop="position" content="2" /></f></c>}, breadcrumbs(container_tag: :c, fragment_tag: :f, semantic: true).to_s end test "unknown style" do breadcrumb :basic assert_raises ArgumentError do breadcrumbs(style: :nonexistent) end end test "register style" do Gretel.register_style :test_style, { container_tag: :one, fragment_tag: :two } breadcrumb :basic assert_dom_equal %{<one class="breadcrumbs"><two><a href="/">Home</a></two><two class="current">About</two></one>}, breadcrumbs(style: :test_style).to_s end # Configuration reload test "reload configuration when file is changed" do path = setup_loading_from_tmp_folder Gretel.reload_environments << "test" File.open(path.join("site.rb"), "w") do |f| f.write <<-EOT crumb :root do link "Home (loaded)", root_path end crumb :about do link "About (loaded)", about_path end EOT end breadcrumb :about assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home (loaded)</a> &rsaquo; <span class="current">About (loaded)</span></div>}, breadcrumbs.to_s sleep 1 # File change interval is 1 second File.open(path.join("site.rb"), "w") do |f| f.write <<-EOT crumb :root do link "Home (reloaded)", "/test" end crumb :about do link "About (reloaded)", "/reloaded" end EOT end breadcrumb :about assert_dom_equal %{<div class="breadcrumbs"><a href="/test">Home (reloaded)</a> &rsaquo; <span class="current">About (reloaded)</span></div>}, breadcrumbs.to_s end test "reload configuration when file is added" do path = setup_loading_from_tmp_folder Gretel.reload_environments << "test" File.open(path.join("site.rb"), "w") do |f| f.write <<-EOT crumb :root do link "Home (loaded)", root_path end EOT end assert_raises ArgumentError do breadcrumb :about breadcrumbs end File.open(path.join("pages.rb"), "w") do |f| f.write <<-EOT crumb :about do link "About (loaded)", about_path end EOT end breadcrumb :about assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home (loaded)</a> &rsaquo; <span class="current">About (loaded)</span></div>}, breadcrumbs.to_s end test "reload configuration when file is deleted" do path = setup_loading_from_tmp_folder Gretel.reload_environments << "test" File.open(path.join("site.rb"), "w") do |f| f.write <<-EOT crumb :root do link "Home (loaded)", root_path end crumb :about do link "About (loaded)", about_path end EOT end File.open(path.join("pages.rb"), "w") do |f| f.write <<-EOT crumb :contact do link "Contact (loaded)", "/contact" parent :about end EOT end breadcrumb :contact assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home (loaded)</a> &rsaquo; <a href="/about">About (loaded)</a> &rsaquo; <span class="current">Contact (loaded)</span></div>}, breadcrumbs.to_s File.delete path.join("pages.rb") assert_raises ArgumentError do breadcrumb :contact breadcrumbs end breadcrumb :about assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home (loaded)</a> &rsaquo; <span class="current">About (loaded)</span></div>}, breadcrumbs.to_s end test "reloads only in development environment" do path = setup_loading_from_tmp_folder assert_equal ["development"], Gretel.reload_environments File.open(path.join("site.rb"), "w") do |f| f.write <<-EOT crumb :root do link "Home (loaded)", root_path end crumb :about do link "About (loaded)", about_path end EOT end breadcrumb :about assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home (loaded)</a> &rsaquo; <span class="current">About (loaded)</span></div>}, breadcrumbs.to_s sleep 1 File.open(path.join("site.rb"), "w") do |f| f.write <<-EOT crumb :root do link "Home (reloaded)", "/test" end crumb :about do link "About (reloaded)", "/reloaded" end EOT end breadcrumb :about assert_dom_equal %{<div class="breadcrumbs"><a href="/">Home (loaded)</a> &rsaquo; <span class="current">About (loaded)</span></div>}, breadcrumbs.to_s end private def setup_loading_from_tmp_folder path = Rails.root.join("tmp", "testcrumbs") FileUtils.rm_rf path FileUtils.mkdir_p path Gretel.breadcrumb_paths = [path.join("*.rb")] path end end
34.782531
614
0.650028
62272dd40e5c14a9c52154edab07a072d0eac44c
991
require "rulers/version" require 'rulers/array' require 'rulers/routing' require 'rulers/util' require 'rulers/dependencies' require 'rulers/controller' require 'rulers/file_model' module Rulers class Application def call(env) if env['PATH_INFO'] == '/favicon.ico' return [404, {'Content-Type' => 'text/html'}, []] end # klass, act = get_controller_and_action(env) # controller = klass.new(env) # text = controller.send(act) # r = controller.get_response # system("echo debug > debug.txt") # if r # [r.status, r.headers, [r.body].flatten] # else # [ # 200, # {'Content-Type' => 'text/html'}, # # ["Hello from Ruby on Rulers! #{[1,2,3].hello}"] # [text] # ] # end rack_app = get_rack_app(env) rack_app.call(env) end end class Controller def initialize(env) @env = env end def env @env end end end
20.22449
61
0.562059
0175c2cb27103a93bf5544a9b9763ff588f4ed8f
802
module APIManager def self.get(options) execute(options.merge(method: :get)) end def self.post(options) execute(options.merge(method: :post)) end def self.put(options) execute(options.merge(method: :put)) end def self.delete(options) execute(options.merge(method: :delete)) end def self.execute(options) APIManager::Request.execute(options) end end require 'api_manager/error' require 'api_manager/error_with_response' require 'api_manager/request' require 'api_manager/response' require 'api_manager/response/base' require 'api_manager/response/html_response' require 'api_manager/response/json_response' require 'api_manager/response/raw_response' ActiveSupport::Inflector.inflections do |inflect| inflect.acronym 'HTML' inflect.acronym 'JSON' end
22.277778
49
0.763092
f88d36f68206a08681d5921f4b587a5db1a60a23
1,680
# # Credits to threedaymonk # https://github.com/threedaymonk/text/blob/master/lib/text/white_similarity.rb # # encoding: utf-8 # Original author: Wilker Lúcio <[email protected]> module OBFS # Ruby implementation of the string similarity described by Simon White # at: http://www.catalysoft.com/articles/StrikeAMatch.html # # 2 * |pairs(s1) INTERSECT pairs(s2)| # similarity(s1, s2) = ----------------------------------- # |pairs(s1)| + |pairs(s2)| # # e.g. # 2 * |{FR, NC}| # similarity(FRANCE, FRENCH) = --------------------------------------- # |{FR,RA,AN,NC,CE}| + |{FR,RE,EN,NC,CH}| # # = (2 * 2) / (5 + 5) # # = 0.4 # # WhiteSimilarity.new.similarity("FRANCE", "FRENCH") # class WhiteSimilarity def self.similarity(str1, str2) new.similarity(str1, str2) end def initialize @word_letter_pairs = {} end def similarity(str1, str2) pairs1 = word_letter_pairs(str1) pairs2 = word_letter_pairs(str2).dup union = pairs1.length + pairs2.length intersection = 0 pairs1.each do |pair1| if index = pairs2.index(pair1) intersection += 1 pairs2.delete_at(index) end end (2.0 * intersection) / union end private def word_letter_pairs(str) @word_letter_pairs[str] ||= str.upcase.split(/\s+/).map{ |word| (0 ... (word.length - 1)).map { |i| word[i, 2] } }.flatten.freeze end end end
25.454545
79
0.502381
b9472fca7482ad56b707f8bfbe3615cdca7957f4
798
# Be sure to restart your server when you modify this file. # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. ActionController::Base.session = { :key => '_2_3_2_session', :secret => 'e481875d8207ad4a2c3e1abc39b7aa2671f78f638ea1e36c8789b5bc1572523f828870dcef63fa21c249753799095e2da5cf6d10f5996922a1f87b6a80f7de3a' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # ActionController::Base.session_store = :active_record_store
49.875
148
0.789474
26fbedbef2f83f76a8e0c52dbbe7f721cda1d8e8
2,445
require 'spec_helper' describe Key, models: true do describe "Associations" do it { is_expected.to belong_to(:user) } end describe "Mass assignment" do end describe "Validation" do it { is_expected.to validate_presence_of(:title) } it { is_expected.to validate_presence_of(:key) } it { is_expected.to validate_length_of(:title).is_within(0..255) } it { is_expected.to validate_length_of(:key).is_within(0..5000) } end describe "Methods" do it { is_expected.to respond_to :projects } it { is_expected.to respond_to :publishable_key } describe "#publishable_keys" do it 'strips all personal information' do expect(build(:key).publishable_key).not_to match(/dummy@gitlab/) end end end context "validation of uniqueness" do let(:user) { create(:user) } it "accepts the key once" do expect(build(:key, user: user)).to be_valid end it "does not accept the exact same key twice" do create(:key, user: user) expect(build(:key, user: user)).not_to be_valid end it "does not accept a duplicate key with a different comment" do create(:key, user: user) duplicate = build(:key, user: user) duplicate.key << ' extra comment' expect(duplicate).not_to be_valid end end context "validate it is a fingerprintable key" do it "accepts the fingerprintable key" do expect(build(:key)).to be_valid end it 'rejects an unfingerprintable key that contains a space' do key = build(:key) # Not always the middle, but close enough key.key = key.key[0..100] + ' ' + key.key[101..-1] expect(key).not_to be_valid end it 'rejects the unfingerprintable key (not a key)' do expect(build(:key, key: 'ssh-rsa an-invalid-key==')).not_to be_valid end it 'rejects the multiple line key' do key = build(:key) key.key.tr!(' ', "\n") expect(key).not_to be_valid end end context 'callbacks' do it 'should add new key to authorized_file' do @key = build(:personal_key, id: 7) expect(GitlabShellWorker).to receive(:perform_async).with(:add_key, @key.shell_id, @key.key) @key.save end it 'should remove key from authorized_file' do @key = create(:personal_key) expect(GitlabShellWorker).to receive(:perform_async).with(:remove_key, @key.shell_id, @key.key) @key.destroy end end end
27.784091
101
0.658487
d5488297a848e68f80be525f72e67fce03527695
800
require 'roodi/checks/abc_metric_method_check' require 'roodi/checks/assignment_in_conditional_check' require 'roodi/checks/case_missing_else_check' require 'roodi/checks/class_line_count_check' require 'roodi/checks/class_name_check' require 'roodi/checks/class_variable_check' require 'roodi/checks/control_coupling_check' require 'roodi/checks/cyclomatic_complexity_block_check' require 'roodi/checks/cyclomatic_complexity_method_check' require 'roodi/checks/empty_rescue_body_check' require 'roodi/checks/for_loop_check' require 'roodi/checks/method_line_count_check' require 'roodi/checks/method_name_check' require 'roodi/checks/module_line_count_check' require 'roodi/checks/module_name_check' require 'roodi/checks/npath_complexity_method_check' require 'roodi/checks/parameter_number_check'
44.444444
57
0.8725
264b4f52237dc8ef365113eeb3fde701073c2013
964
class Surfraw < Formula desc "Shell Users' Revolutionary Front Rage Against the Web" homepage "http://surfraw.alioth.debian.org/" head "git://git.debian.org/surfraw/surfraw.git" url "http://surfraw.alioth.debian.org/dist/surfraw-2.2.9.tar.gz" sha1 "70bbba44ffc3b1bf7c7c4e0e9f0bdd656698a1c0" bottle do sha1 "6c592c99adf6c1a0bb4993a36e4392bce6e24eaa" => :yosemite sha1 "8ca477ffd5f157aa40b258d66e2536691d769921" => :mavericks sha1 "b17ead2b3f8030e659d0af4b44332f76397607f5" => :mountain_lion end def install system "./prebuild" if build.head? system "./configure", "--prefix=#{prefix}", "--sysconfdir=#{etc}", "--with-graphical-browser=open" system "make" ENV.j1 system "make", "install" end test do output = shell_output("#{bin}/surfraw -p google -results=1 homebrew") assert_equal "http://www.google.com/search?q=homebrew&num=1\n", output end end
33.241379
74
0.678423
1d35968bdb143a5ca0161d961a5252703b7f21fe
9,463
# This class implements a pretty printing algorithm. It finds line breaks and # nice indentations for grouped structure. # # By default, the class assumes that primitive elements are strings and each # byte in the strings have single column in width. But it can be used for # other situations by giving suitable arguments for some methods: # * newline object and space generation block for PrettyPrint.new # * optional width argument for PrettyPrint#text # * PrettyPrint#breakable # # There are several candidate uses: # * text formatting using proportional fonts # * multibyte characters which has columns different to number of bytes # * non-string formatting # # == Bugs # * Box based formatting? # * Other (better) model/algorithm? # # == References # Christian Lindig, Strictly Pretty, March 2000, # http://www.st.cs.uni-sb.de/~lindig/papers/#pretty # # Philip Wadler, A prettier printer, March 1998, # http://homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier # # == Author # Tanaka Akira <[email protected]> # class PrettyPrint # This is a convenience method which is same as follows: # # begin # q = PrettyPrint.new(output, maxwidth, newline, &genspace) # ... # q.flush # output # end # def PrettyPrint.format(output='', maxwidth=79, newline="\n", genspace=lambda {|n| ' ' * n}) q = PrettyPrint.new(output, maxwidth, newline, &genspace) yield q q.flush output end # This is similar to PrettyPrint::format but the result has no breaks. # # +maxwidth+, +newline+ and +genspace+ are ignored. # # The invocation of +breakable+ in the block doesn't break a line and is # treated as just an invocation of +text+. # def PrettyPrint.singleline_format(output='', maxwidth=nil, newline=nil, genspace=nil) q = SingleLine.new(output) yield q output end # Creates a buffer for pretty printing. # # +output+ is an output target. If it is not specified, '' is assumed. It # should have a << method which accepts the first argument +obj+ of # PrettyPrint#text, the first argument +sep+ of PrettyPrint#breakable, the # first argument +newline+ of PrettyPrint.new, and the result of a given # block for PrettyPrint.new. # # +maxwidth+ specifies maximum line length. If it is not specified, 79 is # assumed. However actual outputs may overflow +maxwidth+ if long # non-breakable texts are provided. # # +newline+ is used for line breaks. "\n" is used if it is not specified. # # The block is used to generate spaces. {|width| ' ' * width} is used if it # is not given. # def initialize(output='', maxwidth=79, newline="\n", &genspace) @output = output @maxwidth = maxwidth @newline = newline @genspace = genspace || lambda {|n| ' ' * n} @output_width = 0 @buffer_width = 0 @buffer = [] root_group = Group.new(0) @group_stack = [root_group] @group_queue = GroupQueue.new(root_group) @indent = 0 end attr_reader :output, :maxwidth, :newline, :genspace attr_reader :indent, :group_queue def current_group @group_stack.last end # first? is a predicate to test the call is a first call to first? with # current group. # # It is useful to format comma separated values as: # # q.group(1, '[', ']') { # xxx.each {|yyy| # unless q.first? # q.text ',' # q.breakable # end # ... pretty printing yyy ... # } # } # # first? is obsoleted in 1.8.2. # def first? warn "PrettyPrint#first? is obsoleted at 1.8.2." current_group.first? end def break_outmost_groups while @maxwidth < @output_width + @buffer_width return unless group = @group_queue.deq until group.breakables.empty? data = @buffer.shift @output_width = data.output(@output, @output_width) @buffer_width -= data.width end while [email protected]? && Text === @buffer.first text = @buffer.shift @output_width = text.output(@output, @output_width) @buffer_width -= text.width end end end # This adds +obj+ as a text of +width+ columns in width. # # If +width+ is not specified, obj.length is used. # def text(obj, width=obj.length) if @buffer.empty? @output << obj @output_width += width else text = @buffer.last unless Text === text text = Text.new @buffer << text end text.add(obj, width) @buffer_width += width break_outmost_groups end end def fill_breakable(sep=' ', width=sep.length) group { breakable sep, width } end # This tells "you can break a line here if necessary", and a +width+\-column # text +sep+ is inserted if a line is not broken at the point. # # If +sep+ is not specified, " " is used. # # If +width+ is not specified, +sep.length+ is used. You will have to # specify this when +sep+ is a multibyte character, for example. # def breakable(sep=' ', width=sep.length) group = @group_stack.last if group.break? flush @output << @newline @output << @genspace.call(@indent) @output_width = @indent @buffer_width = 0 else @buffer << Breakable.new(sep, width, self) @buffer_width += width break_outmost_groups end end # Groups line break hints added in the block. The line break hints are all # to be used or not. # # If +indent+ is specified, the method call is regarded as nested by # nest(indent) { ... }. # # If +open_obj+ is specified, <tt>text open_obj, open_width</tt> is called # before grouping. If +close_obj+ is specified, <tt>text close_obj, # close_width</tt> is called after grouping. # def group(indent=0, open_obj='', close_obj='', open_width=open_obj.length, close_width=close_obj.length) text open_obj, open_width group_sub { nest(indent) { yield } } text close_obj, close_width end def group_sub group = Group.new(@group_stack.last.depth + 1) @group_stack.push group @group_queue.enq group begin yield ensure @group_stack.pop if group.breakables.empty? @group_queue.delete group end end end # Increases left margin after newline with +indent+ for line breaks added in # the block. # def nest(indent) @indent += indent begin yield ensure @indent -= indent end end # outputs buffered data. # def flush @buffer.each {|data| @output_width = data.output(@output, @output_width) } @buffer.clear @buffer_width = 0 end class Text def initialize @objs = [] @width = 0 end attr_reader :width def output(out, output_width) @objs.each {|obj| out << obj} output_width + @width end def add(obj, width) @objs << obj @width += width end end class Breakable def initialize(sep, width, q) @obj = sep @width = width @pp = q @indent = q.indent @group = q.current_group @group.breakables.push self end attr_reader :obj, :width, :indent def output(out, output_width) @group.breakables.shift if @group.break? out << @pp.newline out << @pp.genspace.call(@indent) @indent else @pp.group_queue.delete @group if @group.breakables.empty? out << @obj output_width + @width end end end class Group def initialize(depth) @depth = depth @breakables = [] @break = false end attr_reader :depth, :breakables def break @break = true end def break? @break end def first? if defined? @first false else @first = false true end end end class GroupQueue def initialize(*groups) @queue = [] groups.each {|g| enq g} end def enq(group) depth = group.depth @queue << [] until depth < @queue.length @queue[depth] << group end def deq @queue.each {|gs| (gs.length-1).downto(0) {|i| unless gs[i].breakables.empty? group = gs.slice!(i, 1).first group.break return group end } gs.each {|group| group.break} gs.clear } return nil end def delete(group) @queue[group.depth].delete(group) end end class SingleLine def initialize(output, maxwidth=nil, newline=nil) @output = output @first = [true] end def text(obj, width=nil) @output << obj end def breakable(sep=' ', width=nil) @output << sep end def nest(indent) yield end def group(indent=nil, open_obj='', close_obj='', open_width=nil, close_width=nil) @first.push true @output << open_obj yield @output << close_obj @first.pop end def flush end def first? result = @first[-1] @first[-1] = false result end end end
25.034392
107
0.591144
bb2ecdbb9c3de9b481c2ea75dc482d4bcd5cbc03
6,544
module ActiveMerchant module Billing # Gateway for netregistry.com.au. # # Note that NetRegistry itself uses gateway service providers. At the # time of this writing, there are at least two (Quest and Ingenico). # This module has only been tested with Quest. # # Also note that NetRegistry does not offer a test mode, nor does it # have support for the authorize/capture/void functionality by default # (you may arrange for this as described in "Programming for # NetRegistry's E-commerce Gateway." [http://rubyurl.com/hNG]), and no # #void functionality is documented. As a result, the #authorize and # #capture have not yet been tested through a live gateway, and #void # will raise an error. # # If you have this functionality enabled, please consider contributing # to ActiveMerchant by writing tests/code for these methods, and # submitting a patch. # # In addition to the standard ActiveMerchant functionality, the # response will contain a 'receipt' parameter # (response.params['receipt']) if a receipt was issued by the gateway. class NetRegistryGateway < Gateway self.live_url = self.test_url = 'https://paygate.ssllock.net/external2.pl' FILTERED_PARAMS = ['card_no', 'card_expiry', 'receipt_array'] self.supported_countries = ['AU'] # Note that support for Diners, Amex, and JCB require extra # steps in setting up your account, as detailed in # "Programming for NetRegistry's E-commerce Gateway." # [http://rubyurl.com/hNG] self.supported_cardtypes = [:visa, :master, :diners_club, :american_express, :jcb] self.display_name = 'NetRegistry' self.homepage_url = 'http://www.netregistry.com.au' TRANSACTIONS = { :authorization => 'preauth', :purchase => 'purchase', :capture => 'completion', :status => 'status', :refund => 'refund' } # Create a new NetRegistry gateway. # # Options :login and :password must be given. def initialize(options = {}) requires!(options, :login, :password) super end # Note that #authorize and #capture only work if your account # vendor is St George, and if your account has been setup as # described in "Programming for NetRegistry's E-commerce # Gateway." [http://rubyurl.com/hNG] def authorize(money, credit_card, options = {}) params = { 'AMOUNT' => amount(money), 'CCNUM' => credit_card.number, 'CCEXP' => expiry(credit_card) } add_request_details(params, options) commit(:authorization, params) end # Note that #authorize and #capture only work if your account # vendor is St George, and if your account has been setup as # described in "Programming for NetRegistry's E-commerce # Gateway." [http://rubyurl.com/hNG] def capture(money, authorization, options = {}) requires!(options, :credit_card) credit_card = options[:credit_card] params = { 'PREAUTHNUM' => authorization, 'AMOUNT' => amount(money), 'CCNUM' => credit_card.number, 'CCEXP' => expiry(credit_card) } add_request_details(params, options) commit(:capture, params) end def purchase(money, credit_card, options = {}) params = { 'AMOUNT' => amount(money), 'CCNUM' => credit_card.number, 'CCEXP' => expiry(credit_card) } add_request_details(params, options) commit(:purchase, params) end def refund(money, identification, options = {}) params = { 'AMOUNT' => amount(money), 'TXNREF' => identification } add_request_details(params, options) commit(:refund, params) end def credit(money, identification, options = {}) ActiveMerchant.deprecated CREDIT_DEPRECATION_MESSAGE refund(money, identification, options) end # Specific to NetRegistry. # # Run a 'status' command. This lets you view the status of a # completed transaction. # def status(identification) params = { 'TXNREF' => identification } commit(:status, params) end private def add_request_details(params, options) params['COMMENT'] = options[:description] unless options[:description].blank? end # Return the expiry for the given creditcard in the required # format for a command. def expiry(credit_card) month = format(credit_card.month, :two_digits) year = format(credit_card.year, :two_digits) "#{month}/#{year}" end # Post the a request with the given parameters and return the # response object. # # Login and password are added automatically, and the comment is # omitted if nil. def commit(action, params) # get gateway response response = parse(ssl_post(self.live_url, post_data(action, params))) Response.new(response['status'] == 'approved', message_from(response), response, :authorization => authorization_from(response, action) ) end def post_data(action, params) params['COMMAND'] = TRANSACTIONS[action] params['LOGIN'] = "#{@options[:login]}/#{@options[:password]}" escape_uri(params.map { |k, v| "#{k}=#{v}" }.join('&')) end # The upstream is picky and so we can't use CGI.escape like we want to def escape_uri(uri) URI::DEFAULT_PARSER.escape(uri) end def parse(response) params = {} lines = response.split("\n") # Just incase there is no real response returned params['status'] = lines[0] params['response_text'] = lines[1] started = false lines.each do |line| if started key, val = line.chomp.split(/=/, 2) params[key] = val unless FILTERED_PARAMS.include?(key) end started = line.chomp =~ /^\.$/ unless started end params end def message_from(response) response['response_text'] end def authorization_from(response, command) case command when :purchase response['txn_ref'] when :authorization response['transaction_no'] end end end end end
32.72
88
0.610177
3962ff752ae56ab56360112580db5a3b30bb7db4
137
name "devstack" description "Devstack Role" run_list( "recipe[devstack::install]" ) default_attributes() override_attributes()
15.222222
36
0.737226
e2a9bb9cb982f3e7e081c7dbe137846570a904ed
2,638
require 'test_helper' describe Hanami::Model::Sql::Types::Schema::Array do let(:described_class) { Hanami::Model::Sql::Types::Schema::Array } let(:input) do Class.new do def to_ary [] end end.new end it 'returns nil for nil' do input = nil described_class[input].must_equal input end it 'coerces object that respond to #to_ary' do described_class[input].must_equal input.to_ary end it 'coerces string' do input = 'foo' exception = lambda do described_class[input] end.must_raise(ArgumentError) exception.message.must_equal "invalid value for Array(): #{input.inspect}" end it 'raises error for symbol' do input = :foo exception = lambda do described_class[input] end.must_raise(ArgumentError) exception.message.must_equal "invalid value for Array(): #{input.inspect}" end it 'raises error for integer' do input = 11 exception = lambda do described_class[input] end.must_raise(ArgumentError) exception.message.must_equal "invalid value for Array(): #{input.inspect}" end it 'raises error for float' do input = 3.14 exception = lambda do described_class[input] end.must_raise(ArgumentError) exception.message.must_equal "invalid value for Array(): #{input.inspect}" end it 'raises error for bigdecimal' do input = BigDecimal.new(3.14, 10) exception = lambda do described_class[input] end.must_raise(ArgumentError) exception.message.must_equal "invalid value for Array(): #{input.inspect}" end it 'raises error for date' do input = Date.today exception = lambda do described_class[input] end.must_raise(ArgumentError) exception.message.must_equal "invalid value for Array(): #{input.inspect}" end it 'raises error for datetime' do input = DateTime.new exception = lambda do described_class[input] end.must_raise(ArgumentError) exception.message.must_equal "invalid value for Array(): #{input.inspect}" end it 'raises error for time' do input = Time.now exception = lambda do described_class[input] end.must_raise(ArgumentError) exception.message.must_equal "invalid value for Array(): #{input.inspect}" end it 'coerces array' do input = [] described_class[input].must_equal input end it 'raises error for hash' do input = {} exception = lambda do described_class[input] end.must_raise(ArgumentError) exception.message.must_equal "invalid value for Array(): #{input.inspect}" end end
24.425926
78
0.675133