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
f85f1bdd7ddd3b54033a6345ab67b414ec099594
1,926
# frozen_string_literal: true lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "prometheus_exporter/version" Gem::Specification.new do |spec| spec.name = "prometheus_exporter" spec.version = PrometheusExporter::VERSION spec.authors = ["Sam Saffron"] spec.email = ["sam.saffron@gmail.com"] spec.summary = %q{Prometheus Exporter} spec.description = %q{Prometheus metric collector and exporter for Ruby} spec.homepage = "https://github.com/discourse/prometheus_exporter" spec.license = "MIT" spec.post_install_message = "prometheus_exporter will only bind to localhost by default as of v0.5" spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features|bin)/}) end spec.bindir = "bin" spec.executables = ["prometheus_exporter"] spec.require_paths = ["lib"] spec.add_dependency "webrick" spec.add_development_dependency "rubocop", ">= 0.69" spec.add_development_dependency "bundler", ">= 2.2.2" spec.add_development_dependency "rake", "~> 13.0" spec.add_development_dependency "minitest", "~> 5.0" spec.add_development_dependency "guard", "~> 2.0" spec.add_development_dependency "mini_racer", "~> 0.3.1" spec.add_development_dependency "guard-minitest", "~> 2.0" spec.add_development_dependency "oj", "~> 3.0" spec.add_development_dependency "rack-test", "~> 0.8.3" spec.add_development_dependency "minitest-stub-const", "~> 0.6" spec.add_development_dependency "rubocop-discourse", ">2" spec.add_development_dependency "appraisal", "~> 2.3" spec.add_development_dependency "activerecord", "~> 6.0.0" if !RUBY_ENGINE == 'jruby' spec.add_development_dependency "raindrops", "~> 0.19" end spec.required_ruby_version = '>= 2.5.0' end
40.978723
101
0.672897
e2e2a74d794db16012aee746f7d9f0beed3398e4
1,568
module Seek module Roles ADMIN = 'admin' # Roles that stand alone, and are not linked to anything, for example Project or Programme class StandAloneRoles < Seek::Roles::Roles class InvalidCheckException < Exception; end def self.role_names [Seek::Roles::ADMIN] end def add_roles(person, role_info) fail InvalidCheckException.new("This role should not be assigned with other items - #{items.inspect}") unless role_info.items.empty? mask = mask_for_role(role_info.role_name) person.roles_mask += mask if (person.roles_mask & mask).zero? end def remove_roles(person, role_info) fail InvalidCheckException.new("This role should not be assigned with other items - #{items.inspect}") unless role_info.items.empty? return unless person.has_role?(role_info.role_name) mask = mask_for_role(role_info.role_name) person.roles_mask -= mask end def check_role_for_item(_person, _role_name, item) fail InvalidCheckException.new("This role should not be checked against an item - #{item.inspect}") unless item.nil? true end module PersonInstanceMethods def is_admin? has_role?(Seek::Roles::ADMIN) end def is_admin=(flag_and_items) assign_or_remove_roles(Seek::Roles::ADMIN, flag_and_items) end end module PersonClassMethods def admins Seek::Roles::Roles.instance.people_with_role(Seek::Roles::ADMIN) end end end end end
32.666667
140
0.669005
61ea93635ce3d363498bd4991cccb7022893c78f
12,271
if RUBY_VERSION < '1.9' require 'uuid' else require 'securerandom' end module OneLogin module RubySaml # SAML2 Auxiliary class # class Utils @@uuid_generator = UUID.new if RUBY_VERSION < '1.9' DSIG = "http://www.w3.org/2000/09/xmldsig#" XENC = "http://www.w3.org/2001/04/xmlenc#" # Return a properly formatted x509 certificate # # @param cert [String] The original certificate # @return [String] The formatted certificate # def self.format_cert(cert) # don't try to format an encoded certificate or if is empty or nil return cert if cert.nil? || cert.empty? || cert.match(/\x0d/) if cert.scan(/BEGIN CERTIFICATE/).length > 1 formatted_cert = [] cert.scan(/-{5}BEGIN CERTIFICATE-{5}[\n\r]?.*?-{5}END CERTIFICATE-{5}[\n\r]?/m) {|c| formatted_cert << format_cert(c) } formatted_cert.join("\n") else cert = cert.gsub(/\-{5}\s?(BEGIN|END) CERTIFICATE\s?\-{5}/, "") cert = cert.gsub(/[\n\r\s]/, "") cert = cert.scan(/.{1,64}/) cert = cert.join("\n") "-----BEGIN CERTIFICATE-----\n#{cert}\n-----END CERTIFICATE-----" end end # Return a properly formatted private key # # @param key [String] The original private key # @return [String] The formatted private key # def self.format_private_key(key) # don't try to format an encoded private key or if is empty return key if key.nil? || key.empty? || key.match(/\x0d/) # is this an rsa key? rsa_key = key.match("RSA PRIVATE KEY") key = key.gsub(/\-{5}\s?(BEGIN|END)( RSA)? PRIVATE KEY\s?\-{5}/, "") key = key.gsub(/[\n\r\s]/, "") key = key.scan(/.{1,64}/) key = key.join("\n") key_label = rsa_key ? "RSA PRIVATE KEY" : "PRIVATE KEY" "-----BEGIN #{key_label}-----\n#{key}\n-----END #{key_label}-----" end # Build the Query String signature that will be used in the HTTP-Redirect binding # to generate the Signature # @param params [Hash] Parameters to build the Query String # @option params [String] :type 'SAMLRequest' or 'SAMLResponse' # @option params [String] :data Base64 encoded SAMLRequest or SAMLResponse # @option params [String] :relay_state The RelayState parameter # @option params [String] :sig_alg The SigAlg parameter # @return [String] The Query String # def self.build_query(params) type, data, relay_state, sig_alg = [:type, :data, :relay_state, :sig_alg].map { |k| params[k]} url_string = "#{type}=#{CGI.escape(data)}" url_string << "&RelayState=#{CGI.escape(relay_state)}" if relay_state url_string << "&SigAlg=#{CGI.escape(sig_alg)}" end # Reconstruct a canonical query string from raw URI-encoded parts, to be used in verifying a signature # # @param params [Hash] Parameters to build the Query String # @option params [String] :type 'SAMLRequest' or 'SAMLResponse' # @option params [String] :raw_data URI-encoded, base64 encoded SAMLRequest or SAMLResponse, as sent by IDP # @option params [String] :raw_relay_state URI-encoded RelayState parameter, as sent by IDP # @option params [String] :raw_sig_alg URI-encoded SigAlg parameter, as sent by IDP # @return [String] The Query String # def self.build_query_from_raw_parts(params) type, raw_data, raw_relay_state, raw_sig_alg = [:type, :raw_data, :raw_relay_state, :raw_sig_alg].map { |k| params[k]} url_string = "#{type}=#{raw_data}" url_string << "&RelayState=#{raw_relay_state}" if raw_relay_state url_string << "&SigAlg=#{raw_sig_alg}" end # Prepare raw GET parameters (build them from normal parameters # if not provided). # # @param rawparams [Hash] Raw GET Parameters # @param params [Hash] GET Parameters # @return [Hash] New raw parameters # def self.prepare_raw_get_params(rawparams, params) rawparams ||= {} if rawparams['SAMLRequest'].nil? && !params['SAMLRequest'].nil? rawparams['SAMLRequest'] = CGI.escape(params['SAMLRequest']) end if rawparams['SAMLResponse'].nil? && !params['SAMLResponse'].nil? rawparams['SAMLResponse'] = CGI.escape(params['SAMLResponse']) end if rawparams['RelayState'].nil? && !params['RelayState'].nil? rawparams['RelayState'] = CGI.escape(params['RelayState']) end if rawparams['SigAlg'].nil? && !params['SigAlg'].nil? rawparams['SigAlg'] = CGI.escape(params['SigAlg']) end rawparams end # Validate the Signature parameter sent on the HTTP-Redirect binding # @param params [Hash] Parameters to be used in the validation process # @option params [OpenSSL::X509::Certificate] cert The Identity provider public certtificate # @option params [String] sig_alg The SigAlg parameter # @option params [String] signature The Signature parameter (base64 encoded) # @option params [String] query_string The full GET Query String to be compared # @return [Boolean] True if the Signature is valid, False otherwise # def self.verify_signature(params) cert, sig_alg, signature, query_string = [:cert, :sig_alg, :signature, :query_string].map { |k| params[k]} signature_algorithm = XMLSecurity::BaseDocument.new.algorithm(sig_alg) return cert.public_key.verify(signature_algorithm.new, Base64.decode64(signature), query_string) end # Build the status error message # @param status_code [String] StatusCode value # @param status_message [Strig] StatusMessage value # @return [String] The status error message def self.status_error_msg(error_msg, status_code = nil, status_message = nil) unless status_code.nil? if status_code.include? "|" status_codes = status_code.split(' | ') values = status_codes.collect do |status_code| status_code.split(':').last end printable_code = values.join(" => ") else printable_code = status_code.split(':').last end error_msg << ', was ' + printable_code end unless status_message.nil? error_msg << ' -> ' + status_message end error_msg end # Obtains the decrypted string from an Encrypted node element in XML # @param encrypted_node [REXML::Element] The Encrypted element # @param private_key [OpenSSL::PKey::RSA] The Service provider private key # @return [String] The decrypted data def self.decrypt_data(encrypted_node, private_key) encrypt_data = REXML::XPath.first( encrypted_node, "./xenc:EncryptedData", { 'xenc' => XENC } ) symmetric_key = retrieve_symmetric_key(encrypt_data, private_key) cipher_value = REXML::XPath.first( encrypt_data, "./xenc:CipherData/xenc:CipherValue", { 'xenc' => XENC } ) node = Base64.decode64(element_text(cipher_value)) encrypt_method = REXML::XPath.first( encrypt_data, "./xenc:EncryptionMethod", { 'xenc' => XENC } ) algorithm = encrypt_method.attributes['Algorithm'] retrieve_plaintext(node, symmetric_key, algorithm) end # Obtains the symmetric key from the EncryptedData element # @param encrypt_data [REXML::Element] The EncryptedData element # @param private_key [OpenSSL::PKey::RSA] The Service provider private key # @return [String] The symmetric key def self.retrieve_symmetric_key(encrypt_data, private_key) encrypted_key = REXML::XPath.first( encrypt_data, "./ds:KeyInfo/xenc:EncryptedKey | ./KeyInfo/xenc:EncryptedKey | //xenc:EncryptedKey[@Id=$id]", { "ds" => DSIG, "xenc" => XENC }, { "id" => self.retrieve_symetric_key_reference(encrypt_data) } ) encrypted_symmetric_key_element = REXML::XPath.first( encrypted_key, "./xenc:CipherData/xenc:CipherValue", "xenc" => XENC ) cipher_text = Base64.decode64(element_text(encrypted_symmetric_key_element)) encrypt_method = REXML::XPath.first( encrypted_key, "./xenc:EncryptionMethod", "xenc" => XENC ) algorithm = encrypt_method.attributes['Algorithm'] retrieve_plaintext(cipher_text, private_key, algorithm) end def self.retrieve_symetric_key_reference(encrypt_data) REXML::XPath.first( encrypt_data, "substring-after(./ds:KeyInfo/ds:RetrievalMethod/@URI, '#')", { "ds" => DSIG } ) end # Obtains the deciphered text # @param cipher_text [String] The ciphered text # @param symmetric_key [String] The symetric key used to encrypt the text # @param algorithm [String] The encrypted algorithm # @return [String] The deciphered text def self.retrieve_plaintext(cipher_text, symmetric_key, algorithm) case algorithm when 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc' then cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').decrypt when 'http://www.w3.org/2001/04/xmlenc#aes128-cbc' then cipher = OpenSSL::Cipher.new('AES-128-CBC').decrypt when 'http://www.w3.org/2001/04/xmlenc#aes192-cbc' then cipher = OpenSSL::Cipher.new('AES-192-CBC').decrypt when 'http://www.w3.org/2001/04/xmlenc#aes256-cbc' then cipher = OpenSSL::Cipher.new('AES-256-CBC').decrypt when 'http://www.w3.org/2001/04/xmlenc#rsa-1_5' then rsa = symmetric_key when 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p' then oaep = symmetric_key end if cipher iv_len = cipher.iv_len data = cipher_text[iv_len..-1] cipher.padding, cipher.key, cipher.iv = 0, symmetric_key, cipher_text[0..iv_len-1] assertion_plaintext = cipher.update(data) assertion_plaintext << cipher.final elsif rsa rsa.private_decrypt(cipher_text) elsif oaep oaep.private_decrypt(cipher_text, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING) else cipher_text end end def self.uuid RUBY_VERSION < '1.9' ? "_#{@@uuid_generator.generate}" : "_#{SecureRandom.uuid}" end # Given two strings, attempt to match them as URIs using Rails' parse method. If they can be parsed, # then the fully-qualified domain name and the host should performa a case-insensitive match, per the # RFC for URIs. If Rails can not parse the string in to URL pieces, return a boolean match of the # two strings. This maintains the previous functionality. # @return [Boolean] def self.uri_match?(destination_url, settings_url) dest_uri = URI.parse(destination_url) acs_uri = URI.parse(settings_url) if dest_uri.scheme.nil? || acs_uri.scheme.nil? || dest_uri.host.nil? || acs_uri.host.nil? raise URI::InvalidURIError else dest_uri.scheme.downcase == acs_uri.scheme.downcase && dest_uri.host.downcase == acs_uri.host.downcase && dest_uri.path == acs_uri.path && dest_uri.query == acs_uri.query end rescue URI::InvalidURIError original_uri_match?(destination_url, settings_url) end # If Rails' URI.parse can't match to valid URL, default back to the original matching service. # @return [Boolean] def self.original_uri_match?(destination_url, settings_url) destination_url == settings_url end # Given a REXML::Element instance, return the concatenation of all child text nodes. Assumes # that there all children other than text nodes can be ignored (e.g. comments). If nil is # passed, nil will be returned. def self.element_text(element) element.texts.map(&:value).join if element end end end end
41.738095
126
0.626762
1df3c29997b0bab36a5bfd8486e3a48401059671
1,848
# frozen_string_literal: true require "bristle/types" require "bristle/util/dry_extensions" require "bristle/util/dsl" using Bristle::Util::DryExtensions module Bristle module Util module Dsl # Accessor base class class Accessor attr_reader :name attr_reader :type attr_reader :access_method attr_reader :set_method attr_reader :default_method attr_reader :variable attr_reader :singular_name def initialize(name:, type:) @name = NAME_TYPE[name] @type = TYPE_TYPE[type] @access_method = name @set_method = :"#{@name}=" @default_method = :"default_#{@name}" @variable = :"@#{@name}" @singular_name = INFLECTOR.singularize(@name).to_sym end def define(target:) setup(target: target) @converter&.setup(target: target, accessor: self) end def setup(target:) raise NotImplementedError, "Subclasses must implement" end def configure(target:, value:) raise NotImplementedError, "Subclasses must implement" end def access_value(target:, value: EMPTY) if value.equal?(EMPTY) result = target.instance_variable_get(variable) if result.nil? default_value(target: target) else result end else target.send(set_method, value) end end def default_value(target:) if target.respond_to?(default_method, true) target.instance_variable_set(variable, target.send(default_method)) end end def set_value(target:, value:) target.instance_variable_set(variable, type[value]) end end end end end
25.666667
79
0.589286
188cfde92cb32373cd128e59f7e8c7a75226d6af
1,484
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) puts "Cadastrando Categorias ... " categories = [ "Animais e acessórios", "Esportes", "Para sua casa", "Eletrônicos e celulares", "Música e hobbies", "Veículos e barcos", "Imóveis", "Empregos e negócios"] categories.each do |c| Category.find_or_create_by(description: c) end puts "Categorias cadastradas com sucesso ... " ############################## CADASTRO DE ADMINISTRADOR PADRÃO ###### puts "Cadstrando Administrador padrão do sistema" Admin.create!(name:"Admin Padrão", email: "admin@admin.com", password:"123456", password_confirmation:"123456", role:0) puts "Administrador padrão do sistema cadastrado com sucesso..." puts "Login: admin@admin.com" puts "Senha: 123456" ############################## CADASTRO DE MEMBRO PADRÃO ###### puts "Cadstrando membro padrão do sistema" Member.create!(email: "memb@memb.com", password:"123456", password_confirmation:"123456") puts "Membro padrão do sistema cadastrado com sucesso..." puts "Login: memb@memb.com" puts "Senha: 123456"
37.1
123
0.646226
e987d368a5b160d3475fe4003db7ab46f17266fc
234
class CreatePosts < ActiveRecord::Migration[5.2] def change create_table :posts do |t| t.integer :user_id t.integer :category_id t.string :content t.integer :uplifts t.timestamps end end end
18
48
0.645299
ffe5f009dc6b0d55102a484af60453d16138d883
3,879
require 'gh' require 'uri' module Travis::API::V3 class GitHub def self.config @config ||= Travis::Config.load end EVENTS = %i(push pull_request issue_comment public member create delete repository) DEFAULT_OPTIONS = { client_id: config.oauth2.try(:client_id), client_secret: config.oauth2.try(:client_secret), scopes: config.oauth2.try(:scope).to_s.split(?,), user_agent: "Travis-API/3 Travis-CI/0.0.1 GH/#{GH::VERSION}", origin: config.host, api_url: config.github.api_url, web_url: config.github.api_url.gsub(%r{\A(https?://)(?:api\.)?([^/]+)(?:/.*)?\Z}, '\1\2'), ssl: config.ssl.to_h.merge(config.github.ssl || {}).compact } private_constant :DEFAULT_OPTIONS HOOKS_URL = "repositories/%i/hooks" private_constant :HOOKS_URL def self.client_config { api_url: DEFAULT_OPTIONS[:api_url], web_url: DEFAULT_OPTIONS[:web_url], scopes: DEFAULT_OPTIONS[:scopes] } end attr_reader :gh, :user def initialize(user = nil, token = nil) if user.respond_to? :github_oauth_token raise ServerError, 'no GitHub token for user' if user.github_oauth_token.blank? token = user.github_oauth_token end @user = user @gh = GH.with(token: token, **DEFAULT_OPTIONS) end def set_hook(repo, active) set_webhook(repo, active) deactivate_service_hook(repo) if Travis.config.enterprise end def upload_key(repository) keys_path = "repositories/#{repository.github_id}/keys" key = gh[keys_path].detect { |e| e['key'] == repository.key.encoded_public_key } unless key gh.post keys_path, { title: Travis.config.host.to_s, key: repository.key.encoded_public_key, read_only: !Travis::Features.owner_active?(:read_write_github_keys, repository.owner) } end end def set_webhook(repo, active) payload = { name: 'web'.freeze, events: EVENTS, active: active, config: { url: service_hook_url.to_s, insecure_ssl: insecure_ssl? } } if url = webhook_url?(repo) info("Updating webhook repo=%s github_id=%i active=%s" % [repo.slug, repo.github_id, active]) gh.patch(url, payload) else hooks_url = HOOKS_URL % [repo.github_id] info("Creating webhook repo=%s github_id=%i active=%s" % [repo.slug, repo.github_id, active]) gh.post(hooks_url, payload) end end def deactivate_service_hook(repo) if url = service_hook_url?(repo) info("Deactivating service hook repo=%s github_id=%i" % [repo.slug, repo.github_id]) # Have to update events here too, to avoid old hooks failing validation gh.patch(url, { events: EVENTS, active: false }) end end def service_hook(repo) hooks(repo).detect { |h| h['name'] == 'travis' && h.dig('config', 'domain') == service_hook_url.host } end def service_hook_url?(repo) if hook = service_hook(repo) hook.dig('_links', 'self', 'href') end end def webhook(repo) hooks(repo).detect do |h| h['name'] == 'web' && URI(h.dig('config', 'url')) == service_hook_url end end def webhook_url?(repo) if hook = webhook(repo) hook.dig('_links', 'self', 'href') end end def hooks(repo) gh[HOOKS_URL % [repo.github_id]] end def service_hook_url url = Travis.config.service_hook_url || '' url.prepend('https://') unless url.starts_with?('https://', 'http://') URI(url) end def info(msg) Travis.logger.info(msg) end private def insecure_ssl? Travis.config.ssl.to_h.key?(:verify) && Travis.config.ssl.to_h[:verify] == false end end end
29.165414
108
0.610724
b9af883d16508e83cca1ae287abe0a776e3d3031
361
# Copyright (c) Facebook, Inc. and its affiliates. name 'cpe_bluetooth' maintainer 'Facebook' maintainer_email 'noreply@facebook.com' license 'Apache-2.0' description 'Manages Bluetooth settings / profile' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0' supports 'mac_os_x' depends 'fb_helpers' depends 'cpe_profiles'
25.785714
72
0.781163
1d4ec031bf27eba585ea45ca9c7e58ca5b9ed086
245
require 'Gosu' require_relative '../lib/tree.rb' require_relative '../lib/calendar.rb' require_relative '../lib/cursor.rb' require_relative '../lib/maple.rb' require_relative '../lib/menu.rb' require_relative '../lib/menu_item.rb' require 'pry'
27.222222
38
0.746939
1d884acfc6bf65f3cde169f714afda357fe81dfd
3,906
share_examples_for 'A semipublic Property' do before :all do %w[ @type @name @value @other_value ].each do |ivar| raise "+#{ivar}+ should be defined in before block" unless instance_variable_defined?(ivar) end module ::Blog class Article include DataMapper::Resource property :id, Serial end end @model = Blog::Article @options ||= {} @property = @type.new(@model, @name, @options) end describe '.new' do describe 'when provided no options' do it 'should return a Property' do @property.should be_kind_of(@type) end it 'should set the primitive' do @property.primitive.should be(@type.primitive) end it 'should set the model' do @property.model.should equal(@model) end it 'should set the options to the default' do @property.options.should == @type.options.merge(@options) end end [ :index, :unique_index, :unique, :lazy ].each do |attribute| [ true, false, :title, [ :title ] ].each do |value| describe "when provided #{(options = { attribute => value }).inspect}" do before :all do @property = @type.new(@model, @name, @options.merge(options)) end it 'should return a Property' do @property.should be_kind_of(@type) end it 'should set the model' do @property.model.should equal(@model) end it 'should set the primitive' do @property.primitive.should be(@type.primitive) end it "should set the options to #{options.inspect}" do @property.options.should == @type.options.merge(@options.merge(options)) end end end [ [], nil ].each do |value| describe "when provided #{(invalid_options = { attribute => value }).inspect}" do it 'should raise an exception' do lambda { @type.new(@model, @name, @options.merge(invalid_options)) }.should raise_error(ArgumentError, "options[#{attribute.inspect}] must be either true, false, a Symbol or an Array of Symbols") end end end end end describe '#load' do subject { @property.load(@value) } before do @property.should_receive(:typecast).with(@value).and_return(@value) end it { should eql(@value) } end describe "#typecast" do describe "when is able to do typecasting on it's own" do it 'delegates all the work to the type' do return_value = mock(@other_value) @property.should_receive(:typecast_to_primitive).with(@invalid_value).and_return(return_value) @property.typecast(@invalid_value) end end describe 'when value is nil' do it 'returns value unchanged' do @property.typecast(nil).should be(nil) end describe 'when value is a Ruby primitive' do it 'returns value unchanged' do @property.typecast(@value).should == @value end end end end describe '#valid?' do describe 'when provided a valid value' do it 'should return true' do @property.valid?(@value).should be(true) end end describe 'when provide an invalid value' do it 'should return false' do @property.valid?(@invalid_value).should be(false) end end describe 'when provide a nil value when required' do it 'should return false' do @property = @type.new(@model, @name, @options.merge(:required => true)) @property.valid?(nil).should be(false) end end describe 'when provide a nil value when not required' do it 'should return false' do @property = @type.new(@model, @name, @options.merge(:required => false)) @property.valid?(nil).should be(true) end end end end
28.933333
140
0.604199
f70700b525f9329bee7db8fd46aaff2b9ca7555a
23,346
module ActiveRecord module ClassMethods alias _new_without_sti_type_cast new def new(*args, &block) _new_without_sti_type_cast(*args, &block).cast_to_current_sti_type end def base_class unless self < Base raise ActiveRecordError, "#{name} doesn't descend from ActiveRecord" end if superclass == Base || superclass.abstract_class? self else superclass.base_class end end def abstract_class? defined?(@abstract_class) && @abstract_class == true end def primary_key @primary_key_value ||= (self == base_class) ? :id : base_class.primary_key end def primary_key=(val) @primary_key_value = val.to_s end def inheritance_column return nil if @no_inheritance_column @inheritance_column_value ||= if self == base_class @inheritance_column_value || 'type' else superclass.inheritance_column.tap { |v| @no_inheritance_column = !v } end end def inheritance_column=(name) @no_inheritance_column = !name @inheritance_column_value = name end def model_name @model_name ||= ActiveModel::Name.new(self) end def __hyperstack_preprocess_attrs(attrs) if inheritance_column && self < base_class && !attrs.key?(inheritance_column) attrs = attrs.merge(inheritance_column => model_name.to_s) end dealiased_attrs = {} attrs.each { |attr, value| dealiased_attrs[_dealias_attribute(attr)] = value } end def find(id) find_by(primary_key => id) end def find_by(attrs = {}) attrs = __hyperstack_preprocess_attrs(attrs) # r = ReactiveRecord::Base.find_locally(self, attrs, new_only: true) # return r.ar_instance if r (r = __hyperstack_internal_scoped_find_by(attrs)) || return r.backing_record.sync_attributes(attrs).set_ar_instance! end def enum(*args) # when we implement schema validation we should also implement value checking end def serialize(attr, *args) ReactiveRecord::Base.serialized?[self][attr] = true end def _dealias_attribute(new) if self == base_class _attribute_aliases[new] || new else _attribute_aliases[new] ||= superclass._dealias_attribute(new) end end def _attribute_aliases @_attribute_aliases ||= {} end def alias_attribute(new_name, old_name) ['', '=', '_changed?'].each do |variant| define_method("#{new_name}#{variant}") { |*args, &block| send("#{old_name}#{variant}", *args, &block) } end _attribute_aliases[new_name] = old_name end # ignore any of these methods if they get called on the client. This list should be trimmed down to include only # methods to be called as "macros" such as :after_create, etc... SERVER_METHODS = [ :regulate_relationship, :regulate_scope, :attribute_type_decorations, :defined_enums, :_validators, :timestamped_migrations, :lock_optimistically, :lock_optimistically=, :local_stored_attributes=, :lock_optimistically?, :attribute_aliases?, :attribute_method_matchers?, :defined_enums?, :has_many_without_reactive_record_add_changed_method, :has_many_with_reactive_record_add_changed_method, :belongs_to_without_reactive_record_add_changed_method, :belongs_to_with_reactive_record_add_changed_method, :cache_timestamp_format, :composed_of_with_reactive_record_add_changed_method, :schema_format, :schema_format=, :error_on_ignored_order_or_limit, :error_on_ignored_order_or_limit=, :timestamped_migrations=, :dump_schema_after_migration, :dump_schema_after_migration=, :dump_schemas, :dump_schemas=, :warn_on_records_fetched_greater_than=, :belongs_to_required_by_default, :default_connection_handler, :connection_handler=, :default_connection_handler=, :skip_time_zone_conversion_for_attributes, :skip_time_zone_conversion_for_attributes=, :time_zone_aware_types, :time_zone_aware_types=, :protected_environments, :skip_time_zone_conversion_for_attributes?, :time_zone_aware_types?, :partial_writes, :partial_writes=, :composed_of_without_reactive_record_add_changed_method, :logger, :partial_writes?, :after_initialize, :record_timestamps, :record_timestamps=, :after_find, :after_touch, :before_save, :around_save, :belongs_to_required_by_default=, :default_connection_handler?, :before_create, :around_create, :before_update, :around_update, :after_save, :before_destroy, :around_destroy, :after_create, :after_destroy, :after_update, :_validation_callbacks, :_validation_callbacks?, :_validation_callbacks=, :_initialize_callbacks, :_initialize_callbacks?, :_initialize_callbacks=, :_find_callbacks, :_find_callbacks?, :_find_callbacks=, :_touch_callbacks, :_touch_callbacks?, :_touch_callbacks=, :_save_callbacks, :_save_callbacks?, :_save_callbacks=, :_create_callbacks, :_create_callbacks?, :_create_callbacks=, :_update_callbacks, :_update_callbacks?, :_update_callbacks=, :_destroy_callbacks, :_destroy_callbacks?, :_destroy_callbacks=, :record_timestamps?, :pre_synchromesh_scope, :pre_synchromesh_default_scope, :do_not_synchronize, :do_not_synchronize?, :logger=, :maintain_test_schema, :maintain_test_schema=, :scope, :time_zone_aware_attributes, :time_zone_aware_attributes=, :default_timezone, :default_timezone=, :_attr_readonly, :warn_on_records_fetched_greater_than, :configurations, :configurations=, :_attr_readonly?, :table_name_prefix=, :table_name_suffix=, :schema_migrations_table_name=, :internal_metadata_table_name, :internal_metadata_table_name=, :primary_key_prefix_type, :_attr_readonly=, :pluralize_table_names=, :protected_environments=, :ignored_columns=, :ignored_columns, :index_nested_attribute_errors, :index_nested_attribute_errors=, :primary_key_prefix_type=, :table_name_prefix?, :table_name_suffix?, :schema_migrations_table_name?, :internal_metadata_table_name?, :protected_environments?, :pluralize_table_names?, :ignored_columns?, :store_full_sti_class, :store_full_sti_class=, :nested_attributes_options, :nested_attributes_options=, :store_full_sti_class?, :default_scopes, :default_scope_override, :default_scopes=, :default_scope_override=, :nested_attributes_options?, :cache_timestamp_format=, :cache_timestamp_format?, :reactive_record_association_keys, :_validators=, :has_many, :belongs_to, :composed_of, :belongs_to_without_reactive_record_add_is_method, :_rollback_callbacks, :_commit_callbacks, :_before_commit_callbacks, :attribute_type_decorations=, :_commit_callbacks=, :_commit_callbacks?, :_before_commit_callbacks?, :_before_commit_callbacks=, :_rollback_callbacks=, :_before_commit_without_transaction_enrollment_callbacks?, :_before_commit_without_transaction_enrollment_callbacks=, :_commit_without_transaction_enrollment_callbacks, :_commit_without_transaction_enrollment_callbacks?, :_commit_without_transaction_enrollment_callbacks=, :_rollback_callbacks?, :_rollback_without_transaction_enrollment_callbacks?, :_rollback_without_transaction_enrollment_callbacks=, :_rollback_without_transaction_enrollment_callbacks, :_before_commit_without_transaction_enrollment_callbacks, :aggregate_reflections, :_reflections=, :aggregate_reflections=, :pluralize_table_names, :public_columns_hash, :attributes_to_define_after_schema_loads, :attributes_to_define_after_schema_loads=, :table_name_suffix, :schema_migrations_table_name, :attribute_aliases, :attribute_method_matchers, :connection_handler, :attribute_aliases=, :attribute_method_matchers=, :_validate_callbacks, :_validate_callbacks?, :_validate_callbacks=, :_validators?, :_reflections?, :aggregate_reflections?, :include_root_in_json, :_reflections, :include_root_in_json=, :include_root_in_json?, :local_stored_attributes, :default_scope, :table_name_prefix, :attributes_to_define_after_schema_loads?, :attribute_type_decorations?, :defined_enums=, :suppress, :has_secure_token, :generate_unique_secure_token, :store, :store_accessor, :_store_accessors_module, :stored_attributes, :reflect_on_aggregation, :reflect_on_all_aggregations, :_reflect_on_association, :reflect_on_all_associations, :clear_reflections_cache, :reflections, :reflect_on_association, :reflect_on_all_autosave_associations, :no_touching, :transaction, :after_commit, :after_rollback, :before_commit, :before_commit_without_transaction_enrollment, :after_create_commit, :after_update_commit, :after_destroy_commit, :after_commit_without_transaction_enrollment, :after_rollback_without_transaction_enrollment, :raise_in_transactional_callbacks, :raise_in_transactional_callbacks=, :accepts_nested_attributes_for, :has_secure_password, :has_one, :has_and_belongs_to_many, :before_validation, :after_validation, :serialize, :primary_key, :dangerous_attribute_method?, :get_primary_key, :quoted_primary_key, :define_method_attribute, :reset_primary_key, :primary_key=, :define_method_attribute=, :attribute_names, :initialize_generated_modules, :column_for_attribute, :define_attribute_methods, :undefine_attribute_methods, :instance_method_already_implemented?, :method_defined_within?, :dangerous_class_method?, :class_method_defined_within?, :attribute_method?, :has_attribute?, :generated_attribute_methods, :attribute_method_prefix, :attribute_method_suffix, :attribute_method_affix, :attribute_alias?, :attribute_alias, :define_attribute_method, :update_counters, :locking_enabled?, :locking_column, :locking_column=, :reset_locking_column, :decorate_attribute_type, :decorate_matching_attribute_types, :attribute, :define_attribute, :reset_counters, :increment_counter, :decrement_counter, :validates_absence_of, :validates_length_of, :validates_size_of, :validates_presence_of, :validates_associated, :validates_uniqueness_of, :validates_acceptance_of, :validates_confirmation_of, :validates_exclusion_of, :validates_format_of, :validates_inclusion_of, :validates_numericality_of, :define_callbacks, :normalize_callback_params, :__update_callbacks, :get_callbacks, :set_callback, :set_callbacks, :skip_callback, :reset_callbacks, :deprecated_false_terminator, :define_model_callbacks, :validate, :validators, :validates_each, :validates_with, :clear_validators!, :validators_on, :validates, :_validates_default_keys, :_parse_validates_options, :validates!, :_to_partial_path, :sanitize, :sanitize_sql, :sanitize_conditions, :quote_value, :sanitize_sql_for_conditions, :sanitize_sql_array, :sanitize_sql_for_assignment, :sanitize_sql_hash_for_assignment, :sanitize_sql_for_order, :expand_hash_conditions_for_aggregates, :sanitize_sql_like, :replace_named_bind_variables, :replace_bind_variables, :raise_if_bind_arity_mismatch, :replace_bind_variable, :quote_bound_value, :all, :default_scoped, :valid_scope_name?, :scope_attributes?, :before_remove_const, :ignore_default_scope?, :unscoped, :build_default_scope, :evaluate_default_scope, :ignore_default_scope=, :current_scope, :current_scope=, :scope_attributes, :base_class, :abstract_class?, :finder_needs_type_condition?, :sti_name, :descends_from_active_record?, :abstract_class, :compute_type, :abstract_class=, :table_name, :columns, :table_exists?, :columns_hash, :column_names, :attribute_types, :prefetch_primary_key?, :sequence_name, :quoted_table_name, :_default_attributes, :type_for_attribute, :inheritance_column, :attributes_builder, :inheritance_column=, :reset_table_name, :table_name=, :reset_column_information, :full_table_name_prefix, :full_table_name_suffix, :reset_sequence_name, :sequence_name=, :next_sequence_value, :column_defaults, :content_columns, :readonly_attributes, :attr_readonly, :create, :create!, :instantiate, :find, :type_caster, :arel_table, :find_by, :find_by!, :initialize_find_by_cache, :generated_association_methods, :arel_engine, :arel_attribute, :predicate_builder, :collection_cache_key, :relation_delegate_class, :initialize_relation_delegate_cache, :enum, :collecting_queries_for_explain, :exec_explain, :i18n_scope, :lookup_ancestors, :human_attribute_name, :references, :uniq, :maximum, :none, :exists?, :second, :limit, :order, :eager_load, :update, :delete_all, :destroy, :ids, :many?, :pluck, :third, :delete, :fourth, :fifth, :forty_two, :second_to_last, :third_to_last, :preload, :sum, :take!, :first!, :last!, :second!, :offset, :select, :fourth!, :third!, :third_to_last!, :fifth!, :where, :first_or_create, :second_to_last!, :forty_two!, :first, :having, :any?, :one?, :none?, :find_or_create_by, :from, :first_or_create!, :first_or_initialize, :except, :find_or_create_by!, :find_or_initialize_by, :includes, :destroy_all, :update_all, :or, :find_in_batches, :take, :joins, :find_each, :last, :in_batches, :reorder, :group, :left_joins, :left_outer_joins, :rewhere, :readonly, :create_with, :distinct, :unscope, :calculate, :average, :count_by_sql, :minimum, :lock, :find_by_sql, :count, :cache, :uncached, :connection, :connection_pool, :establish_connection, :connected?, :clear_cache!, :clear_reloadable_connections!, :connection_id, :connection_config, :clear_all_connections!, :remove_connection, :connection_specification_name, :connection_specification_name=, :retrieve_connection, :connection_id=, :clear_active_connections!, :sqlite3_connection, :direct_descendants, :benchmark, :model_name, :with_options, :attr_protected, :attr_accessible ] def method_missing(name, *args, &block) if args.count == 1 && name.start_with?("find_by_") && !block find_by(name.sub(/^find_by_/, '') => args[0]) elsif [].respond_to?(name) all.send(name, *args, &block) elsif name.end_with?('!') send(name.chop, *args, &block).send(:reload_from_db) rescue nil elsif !SERVER_METHODS.include?(name) raise "#{self.name}.#{name}(#{args}) (called class method missing)" end end # client side AR # Any method that can be applied to an array will be applied to the result # of all instead. # Any method ending with ! just means apply the method after forcing a reload # from the DB. def create(*args, &block) new(*args).save(&block) end def scope(name, *args) opts = _synchromesh_scope_args_check(args) scope_description = ReactiveRecord::ScopeDescription.new(self, name, opts) singleton_class.send(:define_method, name) do |*vargs| all.build_child_scope(scope_description, *name, *vargs) end end def default_scope(*args, &block) opts = _synchromesh_scope_args_check([*block, *args]) @_default_scopes ||= [] @_default_scopes << opts end def all ReactiveRecord::Base.default_scope[self] ||= begin root = ReactiveRecord::Collection .new(self, nil, nil, self, 'all') .extend(ReactiveRecord::UnscopedCollection) (@_default_scopes || [{ client: _all_filter }]).inject(root) do |scope, opts| scope.build_child_scope(ReactiveRecord::ScopeDescription.new(self, :all, opts)) end end end def _all_filter # provides a filter for the all scopes taking into account STI subclasses # note: within the lambda `self` will be the model instance defining_class_is_base_class = base_class == self defining_model_name = model_name.to_s lambda do # have to delay computation of inheritance column since it might # not be defined when class is first defined ic = self.class.inheritance_column defining_class_is_base_class || !ic || self[ic] == defining_model_name end end def unscoped ReactiveRecord::Base.unscoped[self] ||= ReactiveRecord::Collection .new(self, nil, nil, self, 'unscoped') .extend(ReactiveRecord::UnscopedCollection) end def finder_method(name) ReactiveRecord::ScopeDescription.new(self, "_#{name}", {}) [name, "#{name}!"].each do |method| singleton_class.send(:define_method, method) do |*vargs| collection = all.apply_scope("_#{method}", *vargs) collection.first end end end def abstract_class=(val) @abstract_class = val end # def scope(name, body) # singleton_class.send(:define_method, name) do | *args | # args = (args.count == 0) ? name : [name, *args] # ReactiveRecord::Base.class_scopes(self)[args] ||= ReactiveRecord::Collection.new(self, nil, nil, self, args) # end # singleton_class.send(:define_method, "#{name}=") do |collection| # ReactiveRecord::Base.class_scopes(self)[name] = collection # end # end # def all # ReactiveRecord::Base.class_scopes(self)[:all] ||= ReactiveRecord::Collection.new(self, nil, nil, self, "all") # end # # def all=(collection) # ReactiveRecord::Base.class_scopes(self)[:all] = collection # end [:belongs_to, :has_many, :has_one].each do |macro| define_method(macro) do |*args| # is this a bug in opal? saying name, scope=nil, opts={} does not work! name = args.first opts = (args.count > 1 and args.last.is_a? Hash) ? args.last : {} assoc = Associations::AssociationReflection.new(self, macro, name, opts) if macro == :has_many define_method(name) { @backing_record.get_has_many(assoc, nil) } define_method("#{name}=") { |val| @backing_record.set_has_many(assoc, val) } else define_method(name) { @backing_record.get_belongs_to(assoc, nil) } define_method("#{name}=") { |val| @backing_record.set_belongs_to(assoc, val) } end assoc end end def composed_of(name, opts = {}) reflection = Aggregations::AggregationReflection.new(base_class, :composed_of, name, opts) if reflection.klass < ActiveRecord::Base define_method(name) { @backing_record.get_ar_aggregate(reflection, nil) } define_method("#{name}=") { |val| @backing_record.set_ar_aggregate(reflection, val) } else define_method(name) { @backing_record.get_non_ar_aggregate(name, nil) } define_method("#{name}=") { |val| @backing_record.set_non_ar_aggregate(reflection, val) } end end def column_names ReactiveRecord::Base.public_columns_hash.keys end def columns_hash ReactiveRecord::Base.public_columns_hash[name] || {} end def server_methods @server_methods ||= {} end def server_method(name, default: nil) server_methods[name] = { default: default } define_method(name) do |*args| vector = args.count.zero? ? name : [[name] + args] @backing_record.get_server_method(vector, nil) end define_method("#{name}!") do |*args| vector = args.count.zero? ? name : [[name] + args] @backing_record.get_server_method(vector, true) end end def define_attribute_methods columns_hash.each do |name, column_hash| next if name == primary_key define_method(name) { @backing_record.get_attr_value(name, nil) } define_method("#{name}!") { @backing_record.get_attr_value(name, true) } define_method("#{name}=") { |val| @backing_record.set_attr_value(name, val) } define_method("#{name}_changed?") { @backing_record.changed?(name) } define_method("#{name}?") { @backing_record.get_attr_value(name, nil).present? } end self.inheritance_column = nil if inheritance_column && !columns_hash.key?(inheritance_column) end def _react_param_conversion(param, opt = nil) param = Native(param) param = JSON.from_object(param.to_n) if param.is_a? Native::Object result = if param.is_a? self param elsif param.is_a? Hash if opt == :validate_only klass = ReactiveRecord::Base.infer_type_from_hash(self, param) klass == self || klass < self else # TODO: investigate saving .changes here and then replacing the # TODO: changes after the load is complete. In other words preserve the # TODO: changed values as changes while just updating the synced values. target = if param[primary_key] ReactiveRecord::Base.find(self, primary_key => param[primary_key]).tap do |r| r.backing_record.loaded_id = param[primary_key] end else new end associations = reflect_on_all_associations already_processed_keys = Set.new old_param = param.dup param = param.collect do |key, value| next if already_processed_keys.include? key model_name = model_id = nil assoc = associations.detect do |poly_assoc| if key == poly_assoc.polymorphic_type_attribute model_name = value already_processed_keys << poly_assoc.association_foreign_key elsif key == poly_assoc.association_foreign_key model_id = value already_processed_keys << poly_assoc.polymorphic_type_attribute end end if assoc if !value [assoc.attribute, [nil]] elsif assoc.polymorphic? model_id ||= param.detect { |k, *| k == assoc.association_foreign_key }&.last model_id ||= target.send(assoc.attribute)&.id if model_id.nil? raise "Error in #{self.name}._react_param_conversion. \n"\ "Could not determine the id of #{assoc.attribute} of #{target.inspect}.\n"\ "It was not provided in the conversion data, "\ "and it is unknown on the client" end model_name ||= param.detect { |k, *| k == assoc.polymorphic_type_attribute }&.last model_name ||= target.send(assoc.polymorphic_type_attribute) unless Object.const_defined?(model_name) raise "Error in #{self.name}._react_param_conversion. \n"\ "Could not determine the type of #{assoc.attribute} of #{target.inspect}.\n"\ "It was not provided in the conversion data, "\ "and it is unknown on the client" end [assoc.attribute, { id: [model_id], model_name: [model_name] }] else [assoc.attribute, { id: [value]}] end else [key, [value]] end end.compact ReactiveRecord::Base.load_data do ReactiveRecord::ServerDataCache.load_from_json(Hash[param], target) end target.cast_to_current_sti_type end end result end end end
53.792627
158
0.702262
f866827d73520c8b8e1967f17f31ded003edcd13
271
# encoding: utf-8 module Mutx module Support module Clean def self.start Mutx::Results.reset! Mutx::Support::FilesCleanner.delete_all_mutx_reports Mutx::Support::FilesCleanner.delete_all_console_output_files end end end end
22.583333
68
0.693727
f7a5b978045c97850a8c0162fb0a3c3143076143
2,014
require 'spec_helper' describe Squib::Deck do context '#xlsx' do it 'loads basic xlsx data' do expect(Squib.xlsx(file: xlsx_file('basic.xlsx')).to_h).to eq({ 'Name' => %w(Larry Curly Mo), 'General Number' => %w(1 2 3), # general types always get loaded as strings with no conversion 'Actual Number' => [4.0, 5.0, 6.0], # numbers get auto-converted to integers }) end it 'loads xlsx with formulas' do expect(Squib.xlsx(file: xlsx_file('formulas.xlsx')).to_h).to eq({ 'A' => %w(1 2), 'B' => %w(3 4), 'Sum' => %w(4 6), }) end it 'loads xlsm files with macros' do expect(Squib.xlsx(file: xlsx_file('with_macros.xlsm')).to_h).to eq({ 'foo' => %w(8 10), 'bar' => %w(9 11), }) end it 'strips whitespace by default' do expect(Squib.xlsx(file: xlsx_file('whitespace.xlsx')).to_h).to eq({ 'With Whitespace' => ['foo', 'bar', 'baz'], }) end it 'does not strip whitespace when specified' do expect(Squib.xlsx(file: xlsx_file('whitespace.xlsx'), strip: false).to_h).to eq({ ' With Whitespace ' => ['foo ', ' bar', ' baz '], }) end it 'yields to block when given' do data = Squib.xlsx(file: xlsx_file('basic.xlsx')) do |header, value| case header when 'Name' 'he' when 'Actual Number' value * 2 else 'ha' end end expect(data.to_h).to eq({ 'Name' => %w(he he he), 'General Number' => %w(ha ha ha), 'Actual Number' => [8.0, 10.0, 12.0], }) end it 'explodes quantities' do expect(Squib.xlsx(explode: 'Quantity', file: xlsx_file('explode_quantities.xlsx')).to_h).to eq({ 'Name' => ['Zergling', 'Zergling', 'Zergling', 'High Templar'], 'Quantity' => %w(3 3 3 1), }) end end end
30.059701
113
0.510924
39f1ed128ebf0dae1d6779d57267f8c15340271a
917
lib = File.expand_path('../lib/', __FILE__) $:.unshift lib unless $:.include?(lib) require 'peregrin/version' spec = Gem::Specification.new do |s| s.name = 'peregrin' s.version = Peregrin::VERSION s.summary = "Peregrin - ebook conversion" s.description = "Peregrin converts EPUBs, Zhooks and Ochooks." s.author = "Joseph Pearson" s.email = "joseph@inventivelabs.com.au" s.homepage = "http://ochook.org/peregrin" s.rubyforge_project = "nowarning" s.files = Dir['*.txt'] + Dir['bin/*'] + Dir['lib/**/*.rb'] + Dir['test/**/*.rb'] s.executables = ["peregrin"] s.require_path = 'lib' s.has_rdoc = true s.extra_rdoc_files = ['README.md', 'MIT-LICENSE'] s.rdoc_options += [ '--title', 'Peregrin', '--main', 'README.md' ] s.add_dependency('nokogiri', '~> 1.5.10') s.add_dependency('zipruby') s.add_dependency('mime-types') s.add_development_dependency("rake") end
27.787879
64
0.643402
5d8663a28f7d2645daceaf3198162f30a796d200
1,235
class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user (not logged in) if user.admin? can :manage, :all else #creator can manage list/chores/invites #list admin can manage chores can :manage, List, creator_id: user.id can :read, List do |list| list.users.include?(user) end can :join, :all can :leave_list, List do |list| list.users.include?(user) end can :complete, Chore do |chore| user.chores.include?(chore) end can :read, Chore do |chore| user.chores.include?(chore) end can :manage, Chore, :list => { :creator_id => user.id } can :manage, Invite, :list => { :creator_id => user.id } can :edit, List do |list| List.check_admin?(list, user) end can :manage, Chore do |chore| List.check_admin?(List.find_by(id: chore.list_id), user) end can :update, AdminUser do |admin_user| admin_user.role.to_sym == :node_moderator || admin_user.id == admin.id end end # https://github.com/ryanb/cancan/wiki/Defining-Abilities end end
28.72093
80
0.568421
4a69846171a052210950f2f8eb62a32a8babfd2d
182
class City < ActiveRecord::Base has_many :trips has_many :users, through: :trips belongs_to :country validates :name, :travel_advice, :tourist_rating, :presence => true end
22.75
69
0.741758
e8afec0511ec65346fa51938350ec29231feca54
53,023
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'date' require 'google/apis/core/base_service' require 'google/apis/core/json_representation' require 'google/apis/core/hashable' require 'google/apis/errors' module Google module Apis module VisionV1 # External image source (Google Cloud Storage image location). class ImageSource include Google::Apis::Core::Hashable # Google Cloud Storage image URI, which must be in the following form: # `gs://bucket_name/object_name` (for details, see # [Google Cloud Storage Request URIs](https://cloud.google.com/storage/docs/ # reference-uris)). # NOTE: Cloud Storage object versioning is not supported. # Corresponds to the JSON property `gcsImageUri` # @return [String] attr_accessor :gcs_image_uri def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @gcs_image_uri = args[:gcs_image_uri] if args.key?(:gcs_image_uri) end end # Request for performing Google Cloud Vision API tasks over a user-provided # image, with user-requested features. class AnnotateImageRequest include Google::Apis::Core::Hashable # Client image to perform Google Cloud Vision API tasks over. # Corresponds to the JSON property `image` # @return [Google::Apis::VisionV1::Image] attr_accessor :image # Image context and/or feature-specific parameters. # Corresponds to the JSON property `imageContext` # @return [Google::Apis::VisionV1::ImageContext] attr_accessor :image_context # Requested features. # Corresponds to the JSON property `features` # @return [Array<Google::Apis::VisionV1::Feature>] attr_accessor :features def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @image = args[:image] if args.key?(:image) @image_context = args[:image_context] if args.key?(:image_context) @features = args[:features] if args.key?(:features) end end # Response to an image annotation request. class AnnotateImageResponse include Google::Apis::Core::Hashable # If present, label detection has completed successfully. # Corresponds to the JSON property `labelAnnotations` # @return [Array<Google::Apis::VisionV1::EntityAnnotation>] attr_accessor :label_annotations # If present, landmark detection has completed successfully. # Corresponds to the JSON property `landmarkAnnotations` # @return [Array<Google::Apis::VisionV1::EntityAnnotation>] attr_accessor :landmark_annotations # If present, safe-search annotation has completed successfully. # Corresponds to the JSON property `safeSearchAnnotation` # @return [Google::Apis::VisionV1::SafeSearchAnnotation] attr_accessor :safe_search_annotation # Stores image properties, such as dominant colors. # Corresponds to the JSON property `imagePropertiesAnnotation` # @return [Google::Apis::VisionV1::ImageProperties] attr_accessor :image_properties_annotation # If present, text (OCR) detection has completed successfully. # Corresponds to the JSON property `textAnnotations` # @return [Array<Google::Apis::VisionV1::EntityAnnotation>] attr_accessor :text_annotations # If present, logo detection has completed successfully. # Corresponds to the JSON property `logoAnnotations` # @return [Array<Google::Apis::VisionV1::EntityAnnotation>] attr_accessor :logo_annotations # If present, face detection has completed successfully. # Corresponds to the JSON property `faceAnnotations` # @return [Array<Google::Apis::VisionV1::FaceAnnotation>] attr_accessor :face_annotations # The `Status` type defines a logical error model that is suitable for different # programming environments, including REST APIs and RPC APIs. It is used by # [gRPC](https://github.com/grpc). The error model is designed to be: # - Simple to use and understand for most users # - Flexible enough to meet unexpected needs # # Overview # The `Status` message contains three pieces of data: error code, error message, # and error details. The error code should be an enum value of # google.rpc.Code, but it may accept additional error codes if needed. The # error message should be a developer-facing English message that helps # developers *understand* and *resolve* the error. If a localized user-facing # error message is needed, put the localized message in the error details or # localize it in the client. The optional error details may contain arbitrary # information about the error. There is a predefined set of error detail types # in the package `google.rpc` which can be used for common error conditions. # # Language mapping # The `Status` message is the logical representation of the error model, but it # is not necessarily the actual wire format. When the `Status` message is # exposed in different client libraries and different wire protocols, it can be # mapped differently. For example, it will likely be mapped to some exceptions # in Java, but more likely mapped to some error codes in C. # # Other uses # The error model and the `Status` message can be used in a variety of # environments, either with or without APIs, to provide a # consistent developer experience across different environments. # Example uses of this error model include: # - Partial errors. If a service needs to return partial errors to the client, # it may embed the `Status` in the normal response to indicate the partial # errors. # - Workflow errors. A typical workflow has multiple steps. Each step may # have a `Status` message for error reporting purpose. # - Batch operations. If a client uses batch request and batch response, the # `Status` message should be used directly inside batch response, one for # each error sub-response. # - Asynchronous operations. If an API call embeds asynchronous operation # results in its response, the status of those operations should be # represented directly using the `Status` message. # - Logging. If some API errors are stored in logs, the message `Status` could # be used directly after any stripping needed for security/privacy reasons. # Corresponds to the JSON property `error` # @return [Google::Apis::VisionV1::Status] attr_accessor :error def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @label_annotations = args[:label_annotations] if args.key?(:label_annotations) @landmark_annotations = args[:landmark_annotations] if args.key?(:landmark_annotations) @safe_search_annotation = args[:safe_search_annotation] if args.key?(:safe_search_annotation) @image_properties_annotation = args[:image_properties_annotation] if args.key?(:image_properties_annotation) @text_annotations = args[:text_annotations] if args.key?(:text_annotations) @logo_annotations = args[:logo_annotations] if args.key?(:logo_annotations) @face_annotations = args[:face_annotations] if args.key?(:face_annotations) @error = args[:error] if args.key?(:error) end end # Rectangle determined by min and max `LatLng` pairs. class LatLongRect include Google::Apis::Core::Hashable # An object representing a latitude/longitude pair. This is expressed as a pair # of doubles representing degrees latitude and degrees longitude. Unless # specified otherwise, this must conform to the # <a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84 # standard</a>. Values must be within normalized ranges. # Example of normalization code in Python: # def NormalizeLongitude(longitude): # """Wraps decimal degrees longitude to [-180.0, 180.0].""" # q, r = divmod(longitude, 360.0) # if r > 180.0 or (r == 180.0 and q <= -1.0): # return r - 360.0 # return r # def NormalizeLatLng(latitude, longitude): # """Wraps decimal degrees latitude and longitude to # [-90.0, 90.0] and [-180.0, 180.0], respectively.""" # r = latitude % 360.0 # if r <= 90.0: # return r, NormalizeLongitude(longitude) # elif r >= 270.0: # return r - 360, NormalizeLongitude(longitude) # else: # return 180 - r, NormalizeLongitude(longitude + 180.0) # assert 180.0 == NormalizeLongitude(180.0) # assert -180.0 == NormalizeLongitude(-180.0) # assert -179.0 == NormalizeLongitude(181.0) # assert (0.0, 0.0) == NormalizeLatLng(360.0, 0.0) # assert (0.0, 0.0) == NormalizeLatLng(-360.0, 0.0) # assert (85.0, 180.0) == NormalizeLatLng(95.0, 0.0) # assert (-85.0, -170.0) == NormalizeLatLng(-95.0, 10.0) # assert (90.0, 10.0) == NormalizeLatLng(90.0, 10.0) # assert (-90.0, -10.0) == NormalizeLatLng(-90.0, -10.0) # assert (0.0, -170.0) == NormalizeLatLng(-180.0, 10.0) # assert (0.0, -170.0) == NormalizeLatLng(180.0, 10.0) # assert (-90.0, 10.0) == NormalizeLatLng(270.0, 10.0) # assert (90.0, 10.0) == NormalizeLatLng(-270.0, 10.0) # The code in logs/storage/validator/logs_validator_traits.cc treats this type # as if it were annotated as ST_LOCATION. # Corresponds to the JSON property `maxLatLng` # @return [Google::Apis::VisionV1::LatLng] attr_accessor :max_lat_lng # An object representing a latitude/longitude pair. This is expressed as a pair # of doubles representing degrees latitude and degrees longitude. Unless # specified otherwise, this must conform to the # <a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84 # standard</a>. Values must be within normalized ranges. # Example of normalization code in Python: # def NormalizeLongitude(longitude): # """Wraps decimal degrees longitude to [-180.0, 180.0].""" # q, r = divmod(longitude, 360.0) # if r > 180.0 or (r == 180.0 and q <= -1.0): # return r - 360.0 # return r # def NormalizeLatLng(latitude, longitude): # """Wraps decimal degrees latitude and longitude to # [-90.0, 90.0] and [-180.0, 180.0], respectively.""" # r = latitude % 360.0 # if r <= 90.0: # return r, NormalizeLongitude(longitude) # elif r >= 270.0: # return r - 360, NormalizeLongitude(longitude) # else: # return 180 - r, NormalizeLongitude(longitude + 180.0) # assert 180.0 == NormalizeLongitude(180.0) # assert -180.0 == NormalizeLongitude(-180.0) # assert -179.0 == NormalizeLongitude(181.0) # assert (0.0, 0.0) == NormalizeLatLng(360.0, 0.0) # assert (0.0, 0.0) == NormalizeLatLng(-360.0, 0.0) # assert (85.0, 180.0) == NormalizeLatLng(95.0, 0.0) # assert (-85.0, -170.0) == NormalizeLatLng(-95.0, 10.0) # assert (90.0, 10.0) == NormalizeLatLng(90.0, 10.0) # assert (-90.0, -10.0) == NormalizeLatLng(-90.0, -10.0) # assert (0.0, -170.0) == NormalizeLatLng(-180.0, 10.0) # assert (0.0, -170.0) == NormalizeLatLng(180.0, 10.0) # assert (-90.0, 10.0) == NormalizeLatLng(270.0, 10.0) # assert (90.0, 10.0) == NormalizeLatLng(-270.0, 10.0) # The code in logs/storage/validator/logs_validator_traits.cc treats this type # as if it were annotated as ST_LOCATION. # Corresponds to the JSON property `minLatLng` # @return [Google::Apis::VisionV1::LatLng] attr_accessor :min_lat_lng def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @max_lat_lng = args[:max_lat_lng] if args.key?(:max_lat_lng) @min_lat_lng = args[:min_lat_lng] if args.key?(:min_lat_lng) end end # The `Status` type defines a logical error model that is suitable for different # programming environments, including REST APIs and RPC APIs. It is used by # [gRPC](https://github.com/grpc). The error model is designed to be: # - Simple to use and understand for most users # - Flexible enough to meet unexpected needs # # Overview # The `Status` message contains three pieces of data: error code, error message, # and error details. The error code should be an enum value of # google.rpc.Code, but it may accept additional error codes if needed. The # error message should be a developer-facing English message that helps # developers *understand* and *resolve* the error. If a localized user-facing # error message is needed, put the localized message in the error details or # localize it in the client. The optional error details may contain arbitrary # information about the error. There is a predefined set of error detail types # in the package `google.rpc` which can be used for common error conditions. # # Language mapping # The `Status` message is the logical representation of the error model, but it # is not necessarily the actual wire format. When the `Status` message is # exposed in different client libraries and different wire protocols, it can be # mapped differently. For example, it will likely be mapped to some exceptions # in Java, but more likely mapped to some error codes in C. # # Other uses # The error model and the `Status` message can be used in a variety of # environments, either with or without APIs, to provide a # consistent developer experience across different environments. # Example uses of this error model include: # - Partial errors. If a service needs to return partial errors to the client, # it may embed the `Status` in the normal response to indicate the partial # errors. # - Workflow errors. A typical workflow has multiple steps. Each step may # have a `Status` message for error reporting purpose. # - Batch operations. If a client uses batch request and batch response, the # `Status` message should be used directly inside batch response, one for # each error sub-response. # - Asynchronous operations. If an API call embeds asynchronous operation # results in its response, the status of those operations should be # represented directly using the `Status` message. # - Logging. If some API errors are stored in logs, the message `Status` could # be used directly after any stripping needed for security/privacy reasons. class Status include Google::Apis::Core::Hashable # The status code, which should be an enum value of google.rpc.Code. # Corresponds to the JSON property `code` # @return [Fixnum] attr_accessor :code # A list of messages that carry the error details. There will be a # common set of message types for APIs to use. # Corresponds to the JSON property `details` # @return [Array<Hash<String,Object>>] attr_accessor :details # A developer-facing error message, which should be in English. Any # user-facing error message should be localized and sent in the # google.rpc.Status.details field, or localized by the client. # Corresponds to the JSON property `message` # @return [String] attr_accessor :message def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @code = args[:code] if args.key?(:code) @details = args[:details] if args.key?(:details) @message = args[:message] if args.key?(:message) end end # A face annotation object contains the results of face detection. class FaceAnnotation include Google::Apis::Core::Hashable # Pitch angle, which indicates the upwards/downwards angle that the face is # pointing relative to the image's horizontal plane. Range [-180,180]. # Corresponds to the JSON property `tiltAngle` # @return [Float] attr_accessor :tilt_angle # Under-exposed likelihood. # Corresponds to the JSON property `underExposedLikelihood` # @return [String] attr_accessor :under_exposed_likelihood # A bounding polygon for the detected image annotation. # Corresponds to the JSON property `fdBoundingPoly` # @return [Google::Apis::VisionV1::BoundingPoly] attr_accessor :fd_bounding_poly # Face landmarking confidence. Range [0, 1]. # Corresponds to the JSON property `landmarkingConfidence` # @return [Float] attr_accessor :landmarking_confidence # Joy likelihood. # Corresponds to the JSON property `joyLikelihood` # @return [String] attr_accessor :joy_likelihood # Detection confidence. Range [0, 1]. # Corresponds to the JSON property `detectionConfidence` # @return [Float] attr_accessor :detection_confidence # Surprise likelihood. # Corresponds to the JSON property `surpriseLikelihood` # @return [String] attr_accessor :surprise_likelihood # Anger likelihood. # Corresponds to the JSON property `angerLikelihood` # @return [String] attr_accessor :anger_likelihood # Headwear likelihood. # Corresponds to the JSON property `headwearLikelihood` # @return [String] attr_accessor :headwear_likelihood # Yaw angle, which indicates the leftward/rightward angle that the face is # pointing relative to the vertical plane perpendicular to the image. Range # [-180,180]. # Corresponds to the JSON property `panAngle` # @return [Float] attr_accessor :pan_angle # A bounding polygon for the detected image annotation. # Corresponds to the JSON property `boundingPoly` # @return [Google::Apis::VisionV1::BoundingPoly] attr_accessor :bounding_poly # Detected face landmarks. # Corresponds to the JSON property `landmarks` # @return [Array<Google::Apis::VisionV1::Landmark>] attr_accessor :landmarks # Blurred likelihood. # Corresponds to the JSON property `blurredLikelihood` # @return [String] attr_accessor :blurred_likelihood # Roll angle, which indicates the amount of clockwise/anti-clockwise rotation # of the face relative to the image vertical about the axis perpendicular to # the face. Range [-180,180]. # Corresponds to the JSON property `rollAngle` # @return [Float] attr_accessor :roll_angle # Sorrow likelihood. # Corresponds to the JSON property `sorrowLikelihood` # @return [String] attr_accessor :sorrow_likelihood def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @tilt_angle = args[:tilt_angle] if args.key?(:tilt_angle) @under_exposed_likelihood = args[:under_exposed_likelihood] if args.key?(:under_exposed_likelihood) @fd_bounding_poly = args[:fd_bounding_poly] if args.key?(:fd_bounding_poly) @landmarking_confidence = args[:landmarking_confidence] if args.key?(:landmarking_confidence) @joy_likelihood = args[:joy_likelihood] if args.key?(:joy_likelihood) @detection_confidence = args[:detection_confidence] if args.key?(:detection_confidence) @surprise_likelihood = args[:surprise_likelihood] if args.key?(:surprise_likelihood) @anger_likelihood = args[:anger_likelihood] if args.key?(:anger_likelihood) @headwear_likelihood = args[:headwear_likelihood] if args.key?(:headwear_likelihood) @pan_angle = args[:pan_angle] if args.key?(:pan_angle) @bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly) @landmarks = args[:landmarks] if args.key?(:landmarks) @blurred_likelihood = args[:blurred_likelihood] if args.key?(:blurred_likelihood) @roll_angle = args[:roll_angle] if args.key?(:roll_angle) @sorrow_likelihood = args[:sorrow_likelihood] if args.key?(:sorrow_likelihood) end end # A vertex represents a 2D point in the image. # NOTE: the vertex coordinates are in the same scale as the original image. class Vertex include Google::Apis::Core::Hashable # Y coordinate. # Corresponds to the JSON property `y` # @return [Fixnum] attr_accessor :y # X coordinate. # Corresponds to the JSON property `x` # @return [Fixnum] attr_accessor :x def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @y = args[:y] if args.key?(:y) @x = args[:x] if args.key?(:x) end end # Color information consists of RGB channels, score, and the fraction of # the image that the color occupies in the image. class ColorInfo include Google::Apis::Core::Hashable # The fraction of pixels the color occupies in the image. # Value in range [0, 1]. # Corresponds to the JSON property `pixelFraction` # @return [Float] attr_accessor :pixel_fraction # Represents a color in the RGBA color space. This representation is designed # for simplicity of conversion to/from color representations in various # languages over compactness; for example, the fields of this representation # can be trivially provided to the constructor of "java.awt.Color" in Java; it # can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha" # method in iOS; and, with just a little work, it can be easily formatted into # a CSS "rgba()" string in JavaScript, as well. Here are some examples: # Example (Java): # import com.google.type.Color; # // ... # public static java.awt.Color fromProto(Color protocolor) ` # float alpha = protocolor.hasAlpha() # ? protocolor.getAlpha().getValue() # : 1.0; # return new java.awt.Color( # protocolor.getRed(), # protocolor.getGreen(), # protocolor.getBlue(), # alpha); # ` # public static Color toProto(java.awt.Color color) ` # float red = (float) color.getRed(); # float green = (float) color.getGreen(); # float blue = (float) color.getBlue(); # float denominator = 255.0; # Color.Builder resultBuilder = # Color # .newBuilder() # .setRed(red / denominator) # .setGreen(green / denominator) # .setBlue(blue / denominator); # int alpha = color.getAlpha(); # if (alpha != 255) ` # result.setAlpha( # FloatValue # .newBuilder() # .setValue(((float) alpha) / denominator) # .build()); # ` # return resultBuilder.build(); # ` # // ... # Example (iOS / Obj-C): # // ... # static UIColor* fromProto(Color* protocolor) ` # float red = [protocolor red]; # float green = [protocolor green]; # float blue = [protocolor blue]; # FloatValue* alpha_wrapper = [protocolor alpha]; # float alpha = 1.0; # if (alpha_wrapper != nil) ` # alpha = [alpha_wrapper value]; # ` # return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; # ` # static Color* toProto(UIColor* color) ` # CGFloat red, green, blue, alpha; # if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) ` # return nil; # ` # Color* result = [Color alloc] init]; # [result setRed:red]; # [result setGreen:green]; # [result setBlue:blue]; # if (alpha <= 0.9999) ` # [result setAlpha:floatWrapperWithValue(alpha)]; # ` # [result autorelease]; # return result; # ` # // ... # Example (JavaScript): # // ... # var protoToCssColor = function(rgb_color) ` # var redFrac = rgb_color.red || 0.0; # var greenFrac = rgb_color.green || 0.0; # var blueFrac = rgb_color.blue || 0.0; # var red = Math.floor(redFrac * 255); # var green = Math.floor(greenFrac * 255); # var blue = Math.floor(blueFrac * 255); # if (!('alpha' in rgb_color)) ` # return rgbToCssColor_(red, green, blue); # ` # var alphaFrac = rgb_color.alpha.value || 0.0; # var rgbParams = [red, green, blue].join(','); # return ['rgba(', rgbParams, ',', alphaFrac, ')'].join(''); # `; # var rgbToCssColor_ = function(red, green, blue) ` # var rgbNumber = new Number((red << 16) | (green << 8) | blue); # var hexString = rgbNumber.toString(16); # var missingZeros = 6 - hexString.length; # var resultBuilder = ['#']; # for (var i = 0; i < missingZeros; i++) ` # resultBuilder.push('0'); # ` # resultBuilder.push(hexString); # return resultBuilder.join(''); # `; # // ... # Corresponds to the JSON property `color` # @return [Google::Apis::VisionV1::Color] attr_accessor :color # Image-specific score for this color. Value in range [0, 1]. # Corresponds to the JSON property `score` # @return [Float] attr_accessor :score def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @pixel_fraction = args[:pixel_fraction] if args.key?(:pixel_fraction) @color = args[:color] if args.key?(:color) @score = args[:score] if args.key?(:score) end end # A bounding polygon for the detected image annotation. class BoundingPoly include Google::Apis::Core::Hashable # The bounding polygon vertices. # Corresponds to the JSON property `vertices` # @return [Array<Google::Apis::VisionV1::Vertex>] attr_accessor :vertices def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @vertices = args[:vertices] if args.key?(:vertices) end end # A face-specific landmark (for example, a face feature). # Landmark positions may fall outside the bounds of the image # if the face is near one or more edges of the image. # Therefore it is NOT guaranteed that `0 <= x < width` or # `0 <= y < height`. class Landmark include Google::Apis::Core::Hashable # A 3D position in the image, used primarily for Face detection landmarks. # A valid Position must have both x and y coordinates. # The position coordinates are in the same scale as the original image. # Corresponds to the JSON property `position` # @return [Google::Apis::VisionV1::Position] attr_accessor :position # Face landmark type. # Corresponds to the JSON property `type` # @return [String] attr_accessor :type def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @position = args[:position] if args.key?(:position) @type = args[:type] if args.key?(:type) end end # Image context and/or feature-specific parameters. class ImageContext include Google::Apis::Core::Hashable # Rectangle determined by min and max `LatLng` pairs. # Corresponds to the JSON property `latLongRect` # @return [Google::Apis::VisionV1::LatLongRect] attr_accessor :lat_long_rect # List of languages to use for TEXT_DETECTION. In most cases, an empty value # yields the best results since it enables automatic language detection. For # languages based on the Latin alphabet, setting `language_hints` is not # needed. In rare cases, when the language of the text in the image is known, # setting a hint will help get better results (although it will be a # significant hindrance if the hint is wrong). Text detection returns an # error if one or more of the specified languages is not one of the # [supported languages](/vision/docs/languages). # Corresponds to the JSON property `languageHints` # @return [Array<String>] attr_accessor :language_hints def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @lat_long_rect = args[:lat_long_rect] if args.key?(:lat_long_rect) @language_hints = args[:language_hints] if args.key?(:language_hints) end end # Multiple image annotation requests are batched into a single service call. class BatchAnnotateImagesRequest include Google::Apis::Core::Hashable # Individual image annotation requests for this batch. # Corresponds to the JSON property `requests` # @return [Array<Google::Apis::VisionV1::AnnotateImageRequest>] attr_accessor :requests def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @requests = args[:requests] if args.key?(:requests) end end # Set of detected entity features. class EntityAnnotation include Google::Apis::Core::Hashable # Opaque entity ID. Some IDs may be available in # [Google Knowledge Graph Search API](https://developers.google.com/knowledge- # graph/). # Corresponds to the JSON property `mid` # @return [String] attr_accessor :mid # Entity textual description, expressed in its `locale` language. # Corresponds to the JSON property `description` # @return [String] attr_accessor :description # The relevancy of the ICA (Image Content Annotation) label to the # image. For example, the relevancy of "tower" is likely higher to an image # containing the detected "Eiffel Tower" than to an image containing a # detected distant towering building, even though the confidence that # there is a tower in each image may be the same. Range [0, 1]. # Corresponds to the JSON property `topicality` # @return [Float] attr_accessor :topicality # The language code for the locale in which the entity textual # `description` is expressed. # Corresponds to the JSON property `locale` # @return [String] attr_accessor :locale # Some entities may have optional user-supplied `Property` (name/value) # fields, such a score or string that qualifies the entity. # Corresponds to the JSON property `properties` # @return [Array<Google::Apis::VisionV1::Property>] attr_accessor :properties # Overall score of the result. Range [0, 1]. # Corresponds to the JSON property `score` # @return [Float] attr_accessor :score # A bounding polygon for the detected image annotation. # Corresponds to the JSON property `boundingPoly` # @return [Google::Apis::VisionV1::BoundingPoly] attr_accessor :bounding_poly # The location information for the detected entity. Multiple # `LocationInfo` elements can be present because one location may # indicate the location of the scene in the image, and another location # may indicate the location of the place where the image was taken. # Location information is usually present for landmarks. # Corresponds to the JSON property `locations` # @return [Array<Google::Apis::VisionV1::LocationInfo>] attr_accessor :locations # The accuracy of the entity detection in an image. # For example, for an image in which the "Eiffel Tower" entity is detected, # this field represents the confidence that there is a tower in the query # image. Range [0, 1]. # Corresponds to the JSON property `confidence` # @return [Float] attr_accessor :confidence def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @mid = args[:mid] if args.key?(:mid) @description = args[:description] if args.key?(:description) @topicality = args[:topicality] if args.key?(:topicality) @locale = args[:locale] if args.key?(:locale) @properties = args[:properties] if args.key?(:properties) @score = args[:score] if args.key?(:score) @bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly) @locations = args[:locations] if args.key?(:locations) @confidence = args[:confidence] if args.key?(:confidence) end end # A `Property` consists of a user-supplied name/value pair. class Property include Google::Apis::Core::Hashable # Value of the property. # Corresponds to the JSON property `value` # @return [String] attr_accessor :value # Name of the property. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @value = args[:value] if args.key?(:value) @name = args[:name] if args.key?(:name) end end # Represents a color in the RGBA color space. This representation is designed # for simplicity of conversion to/from color representations in various # languages over compactness; for example, the fields of this representation # can be trivially provided to the constructor of "java.awt.Color" in Java; it # can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha" # method in iOS; and, with just a little work, it can be easily formatted into # a CSS "rgba()" string in JavaScript, as well. Here are some examples: # Example (Java): # import com.google.type.Color; # // ... # public static java.awt.Color fromProto(Color protocolor) ` # float alpha = protocolor.hasAlpha() # ? protocolor.getAlpha().getValue() # : 1.0; # return new java.awt.Color( # protocolor.getRed(), # protocolor.getGreen(), # protocolor.getBlue(), # alpha); # ` # public static Color toProto(java.awt.Color color) ` # float red = (float) color.getRed(); # float green = (float) color.getGreen(); # float blue = (float) color.getBlue(); # float denominator = 255.0; # Color.Builder resultBuilder = # Color # .newBuilder() # .setRed(red / denominator) # .setGreen(green / denominator) # .setBlue(blue / denominator); # int alpha = color.getAlpha(); # if (alpha != 255) ` # result.setAlpha( # FloatValue # .newBuilder() # .setValue(((float) alpha) / denominator) # .build()); # ` # return resultBuilder.build(); # ` # // ... # Example (iOS / Obj-C): # // ... # static UIColor* fromProto(Color* protocolor) ` # float red = [protocolor red]; # float green = [protocolor green]; # float blue = [protocolor blue]; # FloatValue* alpha_wrapper = [protocolor alpha]; # float alpha = 1.0; # if (alpha_wrapper != nil) ` # alpha = [alpha_wrapper value]; # ` # return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; # ` # static Color* toProto(UIColor* color) ` # CGFloat red, green, blue, alpha; # if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) ` # return nil; # ` # Color* result = [Color alloc] init]; # [result setRed:red]; # [result setGreen:green]; # [result setBlue:blue]; # if (alpha <= 0.9999) ` # [result setAlpha:floatWrapperWithValue(alpha)]; # ` # [result autorelease]; # return result; # ` # // ... # Example (JavaScript): # // ... # var protoToCssColor = function(rgb_color) ` # var redFrac = rgb_color.red || 0.0; # var greenFrac = rgb_color.green || 0.0; # var blueFrac = rgb_color.blue || 0.0; # var red = Math.floor(redFrac * 255); # var green = Math.floor(greenFrac * 255); # var blue = Math.floor(blueFrac * 255); # if (!('alpha' in rgb_color)) ` # return rgbToCssColor_(red, green, blue); # ` # var alphaFrac = rgb_color.alpha.value || 0.0; # var rgbParams = [red, green, blue].join(','); # return ['rgba(', rgbParams, ',', alphaFrac, ')'].join(''); # `; # var rgbToCssColor_ = function(red, green, blue) ` # var rgbNumber = new Number((red << 16) | (green << 8) | blue); # var hexString = rgbNumber.toString(16); # var missingZeros = 6 - hexString.length; # var resultBuilder = ['#']; # for (var i = 0; i < missingZeros; i++) ` # resultBuilder.push('0'); # ` # resultBuilder.push(hexString); # return resultBuilder.join(''); # `; # // ... class Color include Google::Apis::Core::Hashable # The amount of green in the color as a value in the interval [0, 1]. # Corresponds to the JSON property `green` # @return [Float] attr_accessor :green # The amount of blue in the color as a value in the interval [0, 1]. # Corresponds to the JSON property `blue` # @return [Float] attr_accessor :blue # The amount of red in the color as a value in the interval [0, 1]. # Corresponds to the JSON property `red` # @return [Float] attr_accessor :red # The fraction of this color that should be applied to the pixel. That is, # the final pixel color is defined by the equation: # pixel color = alpha * (this color) + (1.0 - alpha) * (background color) # This means that a value of 1.0 corresponds to a solid color, whereas # a value of 0.0 corresponds to a completely transparent color. This # uses a wrapper message rather than a simple float scalar so that it is # possible to distinguish between a default value and the value being unset. # If omitted, this color object is to be rendered as a solid color # (as if the alpha value had been explicitly given with a value of 1.0). # Corresponds to the JSON property `alpha` # @return [Float] attr_accessor :alpha def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @green = args[:green] if args.key?(:green) @blue = args[:blue] if args.key?(:blue) @red = args[:red] if args.key?(:red) @alpha = args[:alpha] if args.key?(:alpha) end end # Detected entity location information. class LocationInfo include Google::Apis::Core::Hashable # An object representing a latitude/longitude pair. This is expressed as a pair # of doubles representing degrees latitude and degrees longitude. Unless # specified otherwise, this must conform to the # <a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84 # standard</a>. Values must be within normalized ranges. # Example of normalization code in Python: # def NormalizeLongitude(longitude): # """Wraps decimal degrees longitude to [-180.0, 180.0].""" # q, r = divmod(longitude, 360.0) # if r > 180.0 or (r == 180.0 and q <= -1.0): # return r - 360.0 # return r # def NormalizeLatLng(latitude, longitude): # """Wraps decimal degrees latitude and longitude to # [-90.0, 90.0] and [-180.0, 180.0], respectively.""" # r = latitude % 360.0 # if r <= 90.0: # return r, NormalizeLongitude(longitude) # elif r >= 270.0: # return r - 360, NormalizeLongitude(longitude) # else: # return 180 - r, NormalizeLongitude(longitude + 180.0) # assert 180.0 == NormalizeLongitude(180.0) # assert -180.0 == NormalizeLongitude(-180.0) # assert -179.0 == NormalizeLongitude(181.0) # assert (0.0, 0.0) == NormalizeLatLng(360.0, 0.0) # assert (0.0, 0.0) == NormalizeLatLng(-360.0, 0.0) # assert (85.0, 180.0) == NormalizeLatLng(95.0, 0.0) # assert (-85.0, -170.0) == NormalizeLatLng(-95.0, 10.0) # assert (90.0, 10.0) == NormalizeLatLng(90.0, 10.0) # assert (-90.0, -10.0) == NormalizeLatLng(-90.0, -10.0) # assert (0.0, -170.0) == NormalizeLatLng(-180.0, 10.0) # assert (0.0, -170.0) == NormalizeLatLng(180.0, 10.0) # assert (-90.0, 10.0) == NormalizeLatLng(270.0, 10.0) # assert (90.0, 10.0) == NormalizeLatLng(-270.0, 10.0) # The code in logs/storage/validator/logs_validator_traits.cc treats this type # as if it were annotated as ST_LOCATION. # Corresponds to the JSON property `latLng` # @return [Google::Apis::VisionV1::LatLng] attr_accessor :lat_lng def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @lat_lng = args[:lat_lng] if args.key?(:lat_lng) end end # class SafeSearchAnnotation include Google::Apis::Core::Hashable # Likelihood that this is a medical image. # Corresponds to the JSON property `medical` # @return [String] attr_accessor :medical # Spoof likelihood. The likelihood that an modification # was made to the image's canonical version to make it appear # funny or offensive. # Corresponds to the JSON property `spoof` # @return [String] attr_accessor :spoof # Violence likelihood. # Corresponds to the JSON property `violence` # @return [String] attr_accessor :violence # Represents the adult content likelihood for the image. # Corresponds to the JSON property `adult` # @return [String] attr_accessor :adult def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @medical = args[:medical] if args.key?(:medical) @spoof = args[:spoof] if args.key?(:spoof) @violence = args[:violence] if args.key?(:violence) @adult = args[:adult] if args.key?(:adult) end end # Client image to perform Google Cloud Vision API tasks over. class Image include Google::Apis::Core::Hashable # External image source (Google Cloud Storage image location). # Corresponds to the JSON property `source` # @return [Google::Apis::VisionV1::ImageSource] attr_accessor :source # Image content, represented as a stream of bytes. # Note: as with all `bytes` fields, protobuffers use a pure binary # representation, whereas JSON representations use base64. # Corresponds to the JSON property `content` # @return [String] attr_accessor :content def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @source = args[:source] if args.key?(:source) @content = args[:content] if args.key?(:content) end end # Set of dominant colors and their corresponding scores. class DominantColorsAnnotation include Google::Apis::Core::Hashable # RGB color values with their score and pixel fraction. # Corresponds to the JSON property `colors` # @return [Array<Google::Apis::VisionV1::ColorInfo>] attr_accessor :colors def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @colors = args[:colors] if args.key?(:colors) end end # Users describe the type of Google Cloud Vision API tasks to perform over # images by using *Feature*s. Each Feature indicates a type of image # detection task to perform. Features encode the Cloud Vision API # vertical to operate on and the number of top-scoring results to return. class Feature include Google::Apis::Core::Hashable # The feature type. # Corresponds to the JSON property `type` # @return [String] attr_accessor :type # Maximum number of results of this type. # Corresponds to the JSON property `maxResults` # @return [Fixnum] attr_accessor :max_results def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @type = args[:type] if args.key?(:type) @max_results = args[:max_results] if args.key?(:max_results) end end # Response to a batch image annotation request. class BatchAnnotateImagesResponse include Google::Apis::Core::Hashable # Individual responses to image annotation requests within the batch. # Corresponds to the JSON property `responses` # @return [Array<Google::Apis::VisionV1::AnnotateImageResponse>] attr_accessor :responses def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @responses = args[:responses] if args.key?(:responses) end end # Stores image properties, such as dominant colors. class ImageProperties include Google::Apis::Core::Hashable # Set of dominant colors and their corresponding scores. # Corresponds to the JSON property `dominantColors` # @return [Google::Apis::VisionV1::DominantColorsAnnotation] attr_accessor :dominant_colors def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @dominant_colors = args[:dominant_colors] if args.key?(:dominant_colors) end end # An object representing a latitude/longitude pair. This is expressed as a pair # of doubles representing degrees latitude and degrees longitude. Unless # specified otherwise, this must conform to the # <a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84 # standard</a>. Values must be within normalized ranges. # Example of normalization code in Python: # def NormalizeLongitude(longitude): # """Wraps decimal degrees longitude to [-180.0, 180.0].""" # q, r = divmod(longitude, 360.0) # if r > 180.0 or (r == 180.0 and q <= -1.0): # return r - 360.0 # return r # def NormalizeLatLng(latitude, longitude): # """Wraps decimal degrees latitude and longitude to # [-90.0, 90.0] and [-180.0, 180.0], respectively.""" # r = latitude % 360.0 # if r <= 90.0: # return r, NormalizeLongitude(longitude) # elif r >= 270.0: # return r - 360, NormalizeLongitude(longitude) # else: # return 180 - r, NormalizeLongitude(longitude + 180.0) # assert 180.0 == NormalizeLongitude(180.0) # assert -180.0 == NormalizeLongitude(-180.0) # assert -179.0 == NormalizeLongitude(181.0) # assert (0.0, 0.0) == NormalizeLatLng(360.0, 0.0) # assert (0.0, 0.0) == NormalizeLatLng(-360.0, 0.0) # assert (85.0, 180.0) == NormalizeLatLng(95.0, 0.0) # assert (-85.0, -170.0) == NormalizeLatLng(-95.0, 10.0) # assert (90.0, 10.0) == NormalizeLatLng(90.0, 10.0) # assert (-90.0, -10.0) == NormalizeLatLng(-90.0, -10.0) # assert (0.0, -170.0) == NormalizeLatLng(-180.0, 10.0) # assert (0.0, -170.0) == NormalizeLatLng(180.0, 10.0) # assert (-90.0, 10.0) == NormalizeLatLng(270.0, 10.0) # assert (90.0, 10.0) == NormalizeLatLng(-270.0, 10.0) # The code in logs/storage/validator/logs_validator_traits.cc treats this type # as if it were annotated as ST_LOCATION. class LatLng include Google::Apis::Core::Hashable # The latitude in degrees. It must be in the range [-90.0, +90.0]. # Corresponds to the JSON property `latitude` # @return [Float] attr_accessor :latitude # The longitude in degrees. It must be in the range [-180.0, +180.0]. # Corresponds to the JSON property `longitude` # @return [Float] attr_accessor :longitude def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @latitude = args[:latitude] if args.key?(:latitude) @longitude = args[:longitude] if args.key?(:longitude) end end # A 3D position in the image, used primarily for Face detection landmarks. # A valid Position must have both x and y coordinates. # The position coordinates are in the same scale as the original image. class Position include Google::Apis::Core::Hashable # Y coordinate. # Corresponds to the JSON property `y` # @return [Float] attr_accessor :y # X coordinate. # Corresponds to the JSON property `x` # @return [Float] attr_accessor :x # Z coordinate (or depth). # Corresponds to the JSON property `z` # @return [Float] attr_accessor :z def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @y = args[:y] if args.key?(:y) @x = args[:x] if args.key?(:x) @z = args[:z] if args.key?(:z) end end end end end
41.882306
118
0.608377
ff4577edc7498600a60bf5706a7efbda79b6f06c
1,155
#-- # Ruby Whois # # An intelligent pure Ruby WHOIS client and parser. # # Copyright (c) 2009-2018 Simone Carletti <weppos@weppos.net> #++ require_relative 'base_afilias2' module Whois class Parsers # Parser for the whois.nic.xxx server. class WhoisNicXxx < BaseAfilias2 self.scanner = Scanners::BaseAfilias, { pattern_disclaimer: /^The WHOIS information|^The data in this record|^This service is|^Uniregistry reserves/, pattern_reserved: /^>>> Registry Reserved/, } property_supported :created_on do node("Creation Date") do |value| parse_time(value) end end property_supported :updated_on do node("Updated Date") do |value| parse_time(value) end end property_supported :expires_on do node("Registry Expiry Date") do |value| parse_time(value) end end property_supported :status do if reserved? :reserved else super() end end # NEWPROPERTY def reserved? !!node("status:reserved") end end end end
18.934426
119
0.600866
ac03d7ee10f49c2c7666fc266ee4fdd7bf3c9d92
1,333
module SimpleAudioPlayerHelper class NotImplemented < Exception; end def simple_audio_player(dom_id, file, config = {}) result = content_tag(:p, 'Alternative content', :id => dom_id) result += javascript_tag("AudioPlayer.embed('#{dom_id}', { soundFile: '#{file}' });") end # Load WPAudioPlayer files and init the library def simple_audio_player_include_tag(config = {}) force = config.delete(:force) || false config.reverse_merge!(@simple_audio_player_config) simple_audio_player_library_tag + "\n" + simple_audio_player_init_tag(config) if @uses_simple_audio_player or force end # Load javascript (uncompressed when in development mode) def simple_audio_player_library_tag javascript_include_tag development_mode? ? 'simple_audio_player/audio-player.js' : 'simple_audio_player/audio-player-uncompressed.js' end # Load the simple audio player configuration specified in the controller def simple_audio_player_init_tag(config = {}) # TODO: remove invalid config options # Transform the ruby config hash to a javascript styled config hash javascript_tag "AudioPlayer.setup('/flash_files/simple_audio_player/player.swf', #{config.to_json});" end private # Check if we are in development mode def development_mode? RAILS_ENV == 'development' end end
37.027778
137
0.750188
08dceb7cf10f17b444c27b684e70369b3313b579
636
# typed: ignore require "test_helper" module Ektar class MembershipTest < ActiveSupport::TestCase test "membership role is member by default improved" do membership = ektar_memberships(:alternate_membership) assert_equal membership.role, "member" end test "membership is active by default" do membership = ektar_memberships(:user_membership) assert membership.active? end test "membership can be deactivated" do membership = ektar_memberships(:user_membership) assert membership.active? membership.active = false refute membership.active? end end end
21.2
59
0.715409
1c7aacbffba1fd415b550447d3c94709d7e7209d
719
module FactoryTestHelper # # If these aren't defined, autotest can hang indefinitely # and you won't know why. # # I think that there is a way to tell Factory Bot to use # "save" instead of "save!" which would have removed the # need for this MOSTLY. There are a few exceptions. FactoryBot.factories.collect(&:name).each do |object| # # define a method that is commonly used in these class level tests # I'd actually prefer to not do this, but is very helpful. # define_method "create_#{object}" do |*args| options = args.extract_options! new_object = FactoryBot.build(object,options) new_object.save new_object end end end ActiveSupport::TestCase.send(:include, FactoryTestHelper)
28.76
68
0.72879
e2addcb8af9e98e4a583535eaeb5ff453e88bec1
1,493
module Fix module Protocol # # Maps the FIX message type codes to message classes # module MessageClassMapping # The actual code <-> class mapping MAPPING = { '0' => :heartbeat, 'A' => :logon, '1' => :test_request, '2' => :resend_request, '3' => :reject, '4' => :sequence_reset, '5' => :logout, '8' => :execution_report, '9' => :order_cancel_reject, 'D' => :new_order_single, 'F' => :order_cancel_request, 'H' => :order_status_request, 'V' => :market_data_request, 'W' => :market_data_snapshot, 'X' => :market_data_incremental_refresh, 'Y' => :market_data_request_reject, 'j' => :business_message_reject }.freeze # # Returns the message class associated to a message code # # @param msg_type [Integer] The FIX message type code # @return [Class] The FIX message class # def self.get(msg_type) Messages.const_get(FP.camelcase(MAPPING[msg_type])) if MAPPING.key?(msg_type) end # # Returns the message code associated to a message class # # @param klass [Class] The FIX message class # @return [Integer] The FIX message type code # def self.reverse_get(klass) key = klass.name.split('::').last.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase.to_sym MAPPING.find { |p| p[1] == key }[0] end end end end
29.27451
91
0.558607
034b2effee8a3cc89703f90d67b44a78ede6c0b2
9,042
# frozen_string_literal: true # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! require "helper" require "gapic/grpc/service_stub" require "google/iam/v1/iam_policy_pb" require "google/iam/v1/iam_policy_services_pb" require "google/cloud/kms/v1/iam_policy" class ::Google::Cloud::Kms::V1::IAMPolicy::ClientTest < Minitest::Test class ClientStub attr_accessor :call_rpc_count, :requests def initialize response, operation, &block @response = response @operation = operation @block = block @call_rpc_count = 0 @requests = [] end def call_rpc *args, **kwargs @call_rpc_count += 1 @requests << @block&.call(*args, **kwargs) yield @response, @operation if block_given? @response end end def test_set_iam_policy # Create GRPC objects. grpc_response = ::Google::Iam::V1::Policy.new grpc_operation = GRPC::ActiveCall::Operation.new nil grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure grpc_options = {} # Create request parameters for a unary method. resource = "hello world" policy = {} set_iam_policy_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:| assert_equal :set_iam_policy, name assert_kind_of ::Google::Iam::V1::SetIamPolicyRequest, request assert_equal "hello world", request["resource"] assert_equal Gapic::Protobuf.coerce({}, to: ::Google::Iam::V1::Policy), request["policy"] refute_nil options end Gapic::ServiceStub.stub :new, set_iam_policy_client_stub do # Create client client = ::Google::Cloud::Kms::V1::IAMPolicy::Client.new do |config| config.credentials = grpc_channel end # Use hash object client.set_iam_policy({ resource: resource, policy: policy }) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use named arguments client.set_iam_policy resource: resource, policy: policy do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use protobuf object client.set_iam_policy ::Google::Iam::V1::SetIamPolicyRequest.new(resource: resource, policy: policy) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use hash object with options client.set_iam_policy({ resource: resource, policy: policy }, grpc_options) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use protobuf object with options client.set_iam_policy(::Google::Iam::V1::SetIamPolicyRequest.new(resource: resource, policy: policy), grpc_options) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Verify method calls assert_equal 5, set_iam_policy_client_stub.call_rpc_count end end def test_get_iam_policy # Create GRPC objects. grpc_response = ::Google::Iam::V1::Policy.new grpc_operation = GRPC::ActiveCall::Operation.new nil grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure grpc_options = {} # Create request parameters for a unary method. resource = "hello world" options = {} get_iam_policy_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:| assert_equal :get_iam_policy, name assert_kind_of ::Google::Iam::V1::GetIamPolicyRequest, request assert_equal "hello world", request["resource"] assert_equal Gapic::Protobuf.coerce({}, to: ::Google::Iam::V1::GetPolicyOptions), request["options"] refute_nil options end Gapic::ServiceStub.stub :new, get_iam_policy_client_stub do # Create client client = ::Google::Cloud::Kms::V1::IAMPolicy::Client.new do |config| config.credentials = grpc_channel end # Use hash object client.get_iam_policy({ resource: resource, options: options }) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use named arguments client.get_iam_policy resource: resource, options: options do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use protobuf object client.get_iam_policy ::Google::Iam::V1::GetIamPolicyRequest.new(resource: resource, options: options) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use hash object with options client.get_iam_policy({ resource: resource, options: options }, grpc_options) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use protobuf object with options client.get_iam_policy(::Google::Iam::V1::GetIamPolicyRequest.new(resource: resource, options: options), grpc_options) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Verify method calls assert_equal 5, get_iam_policy_client_stub.call_rpc_count end end def test_test_iam_permissions # Create GRPC objects. grpc_response = ::Google::Iam::V1::TestIamPermissionsResponse.new grpc_operation = GRPC::ActiveCall::Operation.new nil grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure grpc_options = {} # Create request parameters for a unary method. resource = "hello world" permissions = ["hello world"] test_iam_permissions_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:| assert_equal :test_iam_permissions, name assert_kind_of ::Google::Iam::V1::TestIamPermissionsRequest, request assert_equal "hello world", request["resource"] assert_equal ["hello world"], request["permissions"] refute_nil options end Gapic::ServiceStub.stub :new, test_iam_permissions_client_stub do # Create client client = ::Google::Cloud::Kms::V1::IAMPolicy::Client.new do |config| config.credentials = grpc_channel end # Use hash object client.test_iam_permissions({ resource: resource, permissions: permissions }) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use named arguments client.test_iam_permissions resource: resource, permissions: permissions do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use protobuf object client.test_iam_permissions ::Google::Iam::V1::TestIamPermissionsRequest.new(resource: resource, permissions: permissions) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use hash object with options client.test_iam_permissions({ resource: resource, permissions: permissions }, grpc_options) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use protobuf object with options client.test_iam_permissions(::Google::Iam::V1::TestIamPermissionsRequest.new(resource: resource, permissions: permissions), grpc_options) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Verify method calls assert_equal 5, test_iam_permissions_client_stub.call_rpc_count end end def test_configure grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure client = block_config = config = nil Gapic::ServiceStub.stub :new, nil do client = ::Google::Cloud::Kms::V1::IAMPolicy::Client.new do |config| config.credentials = grpc_channel end end config = client.configure do |c| block_config = c end assert_same block_config, config assert_kind_of ::Google::Cloud::Kms::V1::IAMPolicy::Client::Configuration, config end end
36.459677
168
0.710905
1a2184ea3c528e7b54b1d7b27deaea510d013b94
623
require File.expand_path("../Abstract/abstract-php-extension", __dir__) class Php71Opcache < AbstractPhp71Extension init desc "OPcache improves PHP performance" homepage "https://php.net/manual/en/book.opcache.php" revision 20 url PHP_SRC_TARBALL sha256 PHP_CHECKSUM[:sha256] depends_on "pcre" def extension_type "zend_extension" end def install Dir.chdir "ext/opcache" safe_phpize system "./configure", "--prefix=#{prefix}", phpconfig system "make" prefix.install "modules/opcache.so" write_config_file if build.with? "config-file" end end
21.482759
71
0.693419
ff19ccad86b4df79564392b4a95eb0926d7c16a3
283
=begin Swaggy Jenkins Jenkins API clients generated from Swagger / Open API specification OpenAPI spec version: 1.1.1 Contact: blah@cliffano.com Generated by: https://github.com/openapitools/openapi-generator.git =end class SwapSpaceMonitorMemoryUsage2 < ApplicationRecord end
17.6875
67
0.812721
795c763c1cd838704be78d5ba5650be94f58c37b
1,189
# frozen_string_literal: true require 'opal/nodes/base' require 'opal/nodes/literal' require 'opal/nodes/variables' require 'opal/nodes/constants' require 'opal/nodes/call' require 'opal/nodes/csend' require 'opal/nodes/call_special' require 'opal/nodes/module' require 'opal/nodes/class' require 'opal/nodes/singleton_class' require 'opal/nodes/inline_args' require 'opal/nodes/args/normarg' require 'opal/nodes/args/optarg' require 'opal/nodes/args/mlhsarg' require 'opal/nodes/args/restarg' require 'opal/nodes/args/kwarg' require 'opal/nodes/args/kwoptarg' require 'opal/nodes/args/kwrestarg' require 'opal/nodes/args/post_kwargs' require 'opal/nodes/args/post_args' require 'opal/nodes/iter' require 'opal/nodes/def' require 'opal/nodes/defs' require 'opal/nodes/if' require 'opal/nodes/logic' require 'opal/nodes/definitions' require 'opal/nodes/yield' require 'opal/nodes/rescue' require 'opal/nodes/case' require 'opal/nodes/super' require 'opal/nodes/top' require 'opal/nodes/while' require 'opal/nodes/hash' require 'opal/nodes/array' require 'opal/nodes/defined' require 'opal/nodes/masgn' require 'opal/nodes/arglist' require 'opal/nodes/x_string' require 'opal/nodes/lambda'
28.309524
37
0.79058
03971ab398cd5e54ad1f2141abe173ba302c99aa
611
require "rails_helper" RSpec.describe Jobs::Scheduler, type: :model do describe "ActiveModel validations" do it { expect(subject).to validate_presence_of(:job) } it { expect(subject).to validate_presence_of(:time) } it { expect(subject).to respond_to(:enabled?) } end describe "ActiveModel associations" do it { expect(subject).to belong_to(:job) } end xit "can run it now" xit "can run it at" xit "can set a recurrent" xit "can stop recurrency" xit "can see last run timestamp" xit "can see last run status" xit "can see all versions" xit "can see last version" end
26.565217
57
0.698854
6ab8e338ffe7aa70b917194aeecf0b0cfd805e6f
1,248
# # Be sure to run `pod lib lint WPInjection.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'WPInjection' s.version = '0.9.1' s.summary = '简单易用的轻量依赖注入框架' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC TODO: Add long description of the pod here. DESC s.homepage = 'https://github.com/codernash/WPInjection' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'stevepeng13' => 'stevepeng13@outlook.com' } s.source = { :git => 'https://github.com/codernash/WPInjection.git', :tag => s.version.to_s } s.ios.deployment_target = '9.0' s.source_files = 'WPInjection/Classes/**/*' s.dependency 'WPDelegates' end
35.657143
105
0.641026
1a1065b4c69abfc149165358a2f6afb768384977
144
# frozen_string_literal: true json.ancestors @relations.ancestors json.descendants @relations.descendants json.current_doc @relations.search_id
28.8
39
0.861111
11107f5345a9911a76afd49b750e5d532b89d492
8,110
# frozen_string_literal: true require "project_types/script/test_helper" describe Script::Layers::Infrastructure::Languages::AssemblyScriptTaskRunner do include TestHelpers::FakeFS let(:ctx) { TestHelpers::FakeContext.new } let(:script_id) { "id" } let(:script_name) { "foo" } let(:extension_point_config) do { "assemblyscript" => { "package": "@shopify/extension-point-as-fake", "version": "*", }, } end let(:extension_point_type) { "discount" } let(:language) { "assemblyscript" } let(:as_task_runner) { Script::Layers::Infrastructure::Languages::AssemblyScriptTaskRunner.new(ctx, script_name) } let(:command_runner) { Script::Layers::Infrastructure::CommandRunner } let(:package_json) do { scripts: { build: "shopify-scripts-toolchain-as build --src src/shopify_main.ts -b script.wasm -- --lib node_modules", }, } end describe ".build" do subject { as_task_runner.build } it "should raise an error if no build script is defined" do File.expects(:read).with("package.json").once.returns(JSON.generate(package_json.delete(:scripts))) assert_raises(Script::Layers::Infrastructure::Errors::BuildScriptNotFoundError) do subject end end it "should raise an error if the generated web assembly is not found" do ctx.write("package.json", JSON.generate(package_json)) ctx .expects(:capture2e) .with("npm run build") .once .returns(["output", mock(success?: true)]) assert_raises(Script::Layers::Infrastructure::Errors::WebAssemblyBinaryNotFoundError) { subject } end describe "when script.wasm exists" do let(:wasm) { "some compiled code" } let(:wasmfile) { "build/script.wasm" } before do ctx.write("package.json", JSON.generate(package_json)) ctx.mkdir_p(File.dirname(wasmfile)) ctx.write(wasmfile, wasm) end it "triggers the compilation process" do ctx .expects(:capture2e) .with("npm run build") .once .returns(["output", mock(success?: true)]) assert ctx.file_exist?(wasmfile) assert_equal wasm, subject refute ctx.file_exist?(wasmfile) end end it "should raise error without command output on failure" do output = "error_output" File.expects(:read).with("package.json").once.returns(JSON.generate(package_json)) File.expects(:read).never ctx .stubs(:capture2e) .returns([output, mock(success?: false)]) assert_raises(Script::Layers::Infrastructure::Errors::SystemCallFailureError, output) do subject end end end describe ".dependencies_installed?" do subject { as_task_runner.dependencies_installed? } before do FileUtils.mkdir_p("node_modules") end it "should return true if node_modules folder exists" do assert subject end it "should return false if node_modules folder does not exists" do Dir.stubs(:exist?).returns(false) refute subject end end describe ".library_version" do subject { as_task_runner.library_version(extension_point_config["assemblyscript"][:package]) } describe "when the package is in the dependencies list" do it "should return a valid version number" do command_runner.any_instance.stubs(:call) .with("npm -s list --json") .returns( { "dependencies" => { extension_point_config["assemblyscript"][:package] => { "version" => "1.3.7", }, }, }.to_json ) assert_equal "1.3.7", subject end end describe "when the package is not in the dependencies list" do it "should return an error" do command_runner.any_instance.stubs(:call) .with("npm -s list --json") .returns( { "dependencies" => {}, }.to_json, ) assert_raises Script::Layers::Infrastructure::Errors::APILibraryNotFoundError do subject end end end describe "when CommandRunner raises SystemCallFailureError" do describe "when error is not json" do it "should re-raise SystemCallFailureError" do cmd = "npm -s list --json" command_runner.any_instance.stubs(:call) .with(cmd) .raises(Script::Layers::Infrastructure::Errors::SystemCallFailureError.new( out: "some non-json parsable error output", cmd: cmd )) assert_raises Script::Layers::Infrastructure::Errors::SystemCallFailureError do subject end end end describe "when error is json, but doesn't contain the expected structure" do it "should re-raise SystemCallFailureError" do cmd = "npm -s list --json" command_runner.any_instance.stubs(:call) .with(cmd) .raises(Script::Layers::Infrastructure::Errors::SystemCallFailureError.new( out: { "not what we expected" => {}, }.to_json, cmd: cmd )) assert_raises Script::Layers::Infrastructure::Errors::SystemCallFailureError do subject end end end describe "when error contains expected versioning data" do it "should rescue SystemCallFailureError if the library version is present" do cmd = "npm -s list --json" command_runner.any_instance.stubs(:call) .with(cmd) .raises(Script::Layers::Infrastructure::Errors::SystemCallFailureError.new( out: { "dependencies" => { extension_point_config["assemblyscript"][:package] => { "version" => "1.3.7", }, }, }.to_json, cmd: cmd )) assert_equal "1.3.7", subject end end end end describe ".install_dependencies" do subject { as_task_runner.install_dependencies } describe "when node version is above minimum" do it "should install using npm" do ctx.expects(:capture2e) .with("node", "--version") .returns(["v14.5.1", mock(success?: true)]) ctx.expects(:capture2e) .with("npm install --no-audit --no-optional --legacy-peer-deps --loglevel error") .returns([nil, mock(success?: true)]) subject end end describe "when node version is below minimum" do it "should raise error" do ctx.expects(:capture2e) .with("node", "--version") .returns(["v14.4.0", mock(success?: true)]) assert_raises Script::Layers::Infrastructure::Errors::DependencyInstallError do subject end end end describe "when capture2e fails" do it "should raise error" do msg = "error message" ctx.expects(:capture2e).returns([msg, mock(success?: false)]) assert_raises Script::Layers::Infrastructure::Errors::DependencyInstallError, msg do subject end end end end describe ".metadata" do subject { as_task_runner.metadata } describe "when metadata file is present and valid" do let(:metadata_json) do JSON.dump( { schemaVersions: { example: { major: "1", minor: "0" }, }, }, ) end it "should return a proper metadata object" do File.expects(:read).with("build/metadata.json").once.returns(metadata_json) ctx .expects(:file_exist?) .with("build/metadata.json") .once .returns(true) assert subject end end describe "when metadata file is missing" do it "should raise an exception" do assert_raises(Script::Layers::Domain::Errors::MetadataNotFoundError) do subject end end end end end
30.037037
116
0.599014
01eced9d776c55c9204e87ce611cc0185af36b5b
494
class CreateEmployeeGrades < ActiveRecord::Migration def self.up create_table :employee_grades do |t| t.string :name t.integer :priority t.boolean :status t.integer :max_hours_day t.integer :max_hours_week end create_default end def self.down drop_table :employee_grades end def self.create_default EmployeeGrade.create :name => 'Fedena Admin',:priority => 0 ,:status => true,:max_hours_day=>nil,:max_hours_week=>nil end end
23.52381
121
0.690283
bfa60b2142d34be6940d74c5d6f27efa46bc2822
904
module DataAbstraction::SensorData class EarthMagnetometer < Generic STANDARD_UNIT = "nT" def initialize(data, meta_values = {}, unit = STANDARD_UNIT) super(data, meta_values, unit) @values = Array.new @values[0] = MagneticValue.new(data['values'][0].to_f, @unit) @values[1] = MagneticValue.new(data['values'][1].to_f, @unit) @values[2] = MagneticValue.new(data['values'][2].to_f, @unit) end def build_part "\"values\":[#{@values[0].value},#{@values[1].value},#{@values[2].value}],\"unit\":\"#{@unit}\"" end def self.unit_class MagneticValue end def self.standard_unit STANDARD_UNIT end def self.dummy super({ 'data_class_name' => self.name.split('::').last, 'data' => { 'values' => [ 30, 40, 50], 'unit' => 'nT' } }) end end end
30.133333
102
0.55531
26699105f55f74647f991170bef245246edfe33d
140
class AddClassroomIdToPresentations < ActiveRecord::Migration def change add_column :presentations, :classroom_id, :integer end end
23.333333
61
0.8
62292b0824acc5a1556d8b329334e0dd504573ad
75
require "omniauth-firmafon/version" require 'omniauth/strategies/firmafon'
25
38
0.84
08a41e0af100328124c3bdbcb04cfabd2311cc5c
491
covers 'facets/kernel/try' test_case Kernel do method :try do test do example = Struct.new(:name).new("bob") example.try(:name).assert == "bob" end test "without argument" do example = Struct.new(:name).new("bob") example.try.name.assert == "bob" end end end test_case NilClass do method :try do test do nil.try(:name).assert == nil end test "without argument" do nil.try.name.assert == nil end end end
13.638889
44
0.596741
e95892ec0e47386700bef09c45ac0d898ec6eb2e
861
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "kasoba/version" Gem::Specification.new do |s| s.name = "kasoba" s.version = Kasoba::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Lacides Charris", "Guillermo Iguaran"] s.email = ["lacidescharris@hotmail.es", "guilleiguaran@gmail.com"] s.homepage = "https://github.com/guilleiguaran/kasoba" s.summary = %q{Interactive tool for large scale code refactors} s.description = %q{Kasoba is a tool meant to assist programmers with large-scale code refactors.} s.rubyforge_project = "kasoba" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] end
39.136364
99
0.643438
21fa23ec8e701f2726e5e70b14ae5448885ff9bf
868
module Tanker module Pagination autoload :WillPaginate, 'tanker/pagination/will_paginate' autoload :Kaminari, 'tanker/pagination/kaminari' def self.create(results, total_hits, options = {}, categories = {}) begin backend = Tanker.configuration[:pagination_backend].to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } # classify pagination backend name page = Object.const_get(:Tanker).const_get(:Pagination).const_get(backend).create(results, total_hits, options) page.extend Categories page.categories = categories page rescue NameError raise(BadConfiguration, "Unknown pagination backend") end end module Categories def categories @categories end def categories=(val) @categories = val end end end end
28.933333
168
0.640553
017cac1de2ce60540c77fca2f9f1e2c0601a5460
15,416
# frozen_string_literal: true describe Facter::FactManager do let(:internal_manager) { instance_spy(Facter::InternalFactManager) } let(:external_manager) { instance_spy(Facter::ExternalFactManager) } let(:cache_manager) { instance_spy(Facter::CacheManager) } let(:fact_loader) { instance_double(Facter::FactLoader) } let(:logger) { instance_spy(Facter::Log) } def stub_query_parser(withs, returns) allow(Facter::QueryParser).to receive(:parse).with(*withs).and_return(returns) end def stub_internal_manager(withs, returns) allow(internal_manager).to receive(:resolve_facts).with(withs).and_return(returns) end def stub_external_manager(withs, returns) allow(external_manager).to receive(:resolve_facts).with(withs).and_return(returns) end def stub_cache_manager(withs, returns) allow(cache_manager).to receive(:resolve_facts).with(withs).and_return([withs, Array(returns)]) allow(cache_manager).to receive(:cache_facts) end before do Singleton.__init__(Facter::FactManager) Singleton.__init__(Facter::FactLoader) allow(Facter::Log).to receive(:new).and_return(logger) allow(Facter::InternalFactManager).to receive(:new).and_return(internal_manager) allow(Facter::ExternalFactManager).to receive(:new).and_return(external_manager) allow(Facter::CacheManager).to receive(:new).and_return(cache_manager) allow(Facter::FactLoader).to receive(:new).and_return(fact_loader) end describe '#resolve_facts' do let(:os) { 'os' } let(:os_klass) { instance_double(Facts::Linux::Os::Name) } let(:user_query) { [] } let(:loaded_facts) do [ instance_double(Facter::LoadedFact, name: 'os.name', klass: os_klass, type: :core), instance_double(Facter::LoadedFact, name: 'custom_fact', klass: nil, type: :custom) ] end let(:searched_facts) do [ instance_double( Facter::SearchedFact, name: os, fact_class: os_klass, user_query: '', type: :core ), instance_double( Facter::SearchedFact, name: 'my_custom_fact', fact_class: nil, user_query: '', type: :custom ) ] end let(:resolved_fact) { mock_resolved_fact(os, 'Ubuntu', '') } before do allow(Facter::FactLoader.instance).to receive(:load).and_return(loaded_facts) stub_query_parser([user_query, loaded_facts], searched_facts) stub_internal_manager(searched_facts, [resolved_fact]) stub_external_manager(searched_facts, nil) stub_cache_manager(searched_facts, []) end it 'resolved all facts' do resolved_facts = Facter::FactManager.instance.resolve_facts(user_query) expect(resolved_facts).to eq([resolved_fact]) end end describe '#resolve_fact' do context 'with custom fact' do let(:user_query) { 'custom_fact' } let(:fact_name) { 'custom_fact' } let(:custom_fact) { instance_double(Facter::LoadedFact, name: fact_name, klass: nil, type: :custom) } let(:loaded_facts) { [custom_fact] } let(:searched_facts) do [ instance_double( Facter::SearchedFact, name: fact_name, fact_class: nil, user_query: '', type: :custom ) ] end let(:resolved_fact) { mock_resolved_fact(fact_name, 'custom', '', :custom) } let(:cached_fact) { mock_resolved_fact(fact_name, 'cached_custom', '', :custom) } context 'when is found in custom_dir/fact_name.rb' do before do # mock custom_fact_by_filename to return resolved_fact allow(fact_loader).to receive(:load_custom_fact).and_return(loaded_facts) stub_query_parser([[user_query], loaded_facts], searched_facts) stub_internal_manager(searched_facts, [resolved_fact]) stub_external_manager(searched_facts, [resolved_fact]) stub_cache_manager(searched_facts, []) # mock core_or_external_fact to return nil allow(fact_loader).to receive(:load_internal_facts).and_return([]) allow(fact_loader).to receive(:load_external_facts).and_return([]) stub_query_parser([[user_query], []], []) stub_internal_manager([], []) stub_external_manager([], []) stub_cache_manager([], []) end it 'tries to load it from fact_name.rb' do Facter::FactManager.instance.resolve_fact(user_query) expect(logger).to have_received(:debug) .with("Searching fact: #{user_query} in file: #{user_query}.rb") end it 'loads core and external facts' do Facter::FactManager.instance.resolve_fact(user_query) expect(logger).to have_received(:debug) .with("Searching fact: #{user_query} in core facts and external facts") end it 'does not load all custom facts' do Facter::FactManager.instance.resolve_fact(user_query) expect(logger).not_to have_received(:debug) .with("Searching fact: #{user_query} in all custom facts") end it 'resolves fact' do resolved_facts = Facter::FactManager.instance.resolve_fact(user_query) expect(resolved_facts).to eql([resolved_fact]) end end context 'when is not found in custom_dir/fact_name.rb' do before do # mock custom_fact_by_filename to return nil allow(fact_loader).to receive(:load_custom_fact).and_return([]) stub_query_parser([[user_query], []], []) stub_external_manager(searched_facts, []) stub_cache_manager([], []) # mock core_or_external_fact to return nil allow(fact_loader).to receive(:load_internal_facts).and_return([]) allow(fact_loader).to receive(:load_external_facts).and_return([]) stub_query_parser([[user_query], []], []) stub_internal_manager([], []) stub_external_manager([], []) stub_cache_manager([], []) # mock all_custom_facts to return resolved_fact allow(fact_loader).to receive(:load_custom_facts).and_return(loaded_facts) stub_query_parser([[user_query], loaded_facts], searched_facts) stub_external_manager(searched_facts, [resolved_fact]) stub_cache_manager(searched_facts, []) end it 'tries to load it from fact_name.rb' do Facter::FactManager.instance.resolve_fact(user_query) expect(logger).to have_received(:debug) .with("Searching fact: #{user_query} in file: #{user_query}.rb") end it 'loads core and external facts' do Facter::FactManager.instance.resolve_fact(user_query) expect(logger).to have_received(:debug) .with("Searching fact: #{user_query} in core facts and external facts") end it 'loads all custom facts' do Facter::FactManager.instance.resolve_fact(user_query) expect(logger).to have_received(:debug) .with("Searching fact: #{user_query} in all custom facts") end it 'resolves fact' do resolved_facts = Facter::FactManager.instance.resolve_fact(user_query) expect(resolved_facts).to eql([resolved_fact]) end end context 'when fact is cached' do before do # mock custom_fact_by_filename to return cached_fact allow(fact_loader).to receive(:load_custom_fact).and_return(loaded_facts) stub_query_parser([[user_query], loaded_facts], searched_facts) stub_internal_manager(searched_facts, []) stub_external_manager(searched_facts, []) stub_cache_manager(searched_facts, cached_fact) # mock core_or_external_fact to return nil allow(fact_loader).to receive(:load_internal_facts).and_return([]) allow(fact_loader).to receive(:load_external_facts).and_return([]) stub_query_parser([[user_query], []], []) stub_internal_manager([], []) stub_external_manager([], []) stub_cache_manager([], []) end it 'returns the cached fact' do resolved_facts = Facter::FactManager.instance.resolve_fact(user_query) expect(resolved_facts).to eql([cached_fact]) end end end context 'with core fact' do let(:user_query) { 'os.name' } let(:os_klass) { instance_double(Facts::Linux::Os::Name) } let(:bool_klass) { instance_double(Facts::Linux::FipsEnabled) } let(:nil_klass) { instance_double(Facts::Linux::Virtual) } let(:core_fact) { instance_double(Facter::LoadedFact, name: 'os.name', klass: os_klass, type: :core) } let(:bool_core_fact) { instance_double(Facter::LoadedFact, name: 'fips_enabled', klass: bool_klass, type: :core) } let(:nil_core_fact) { instance_double(Facter::LoadedFact, name: 'virtual', klass: nil_klass, type: :core) } let(:loaded_facts) { [core_fact, bool_core_fact, nil_core_fact] } let(:searched_facts) do [ instance_double( Facter::SearchedFact, name: 'os', fact_class: os_klass, user_query: '', type: :core ), instance_double( Facter::SearchedFact, name: 'fips_enabled', fact_class: bool_klass, user_query: '', type: :core ), instance_double( Facter::SearchedFact, name: 'virtual', fact_class: nil_klass, user_query: '', type: :core ) ] end let(:resolved_fact) { mock_resolved_fact('os.name', 'darwin', '', :core) } before do # mock custom_fact_by_filename to return nil allow(fact_loader).to receive(:load_custom_fact).and_return([]) stub_query_parser([[user_query], []], []) stub_external_manager(searched_facts, []) stub_cache_manager([], []) # mock core_or_external_fact to return the core resolved_fact allow(fact_loader).to receive(:load_internal_facts).and_return(loaded_facts) allow(fact_loader).to receive(:load_external_facts).and_return([]) stub_query_parser([[user_query], loaded_facts], searched_facts) stub_internal_manager(searched_facts, [resolved_fact]) stub_external_manager([], []) stub_cache_manager(searched_facts, []) end it 'tries to load it from fact_name.rb' do Facter::FactManager.instance.resolve_fact(user_query) expect(logger).to have_received(:debug) .with("Searching fact: #{user_query} in file: #{user_query}.rb") end it 'loads core and external facts' do Facter::FactManager.instance.resolve_fact(user_query) expect(logger).to have_received(:debug) .with("Searching fact: #{user_query} in core facts and external facts") end it 'does not load all custom facts' do Facter::FactManager.instance.resolve_fact(user_query) expect(logger).not_to have_received(:debug) .with("Searching fact: #{user_query} in all custom facts") end it 'resolves fact' do resolved_facts = Facter::FactManager.instance.resolve_fact(user_query) expect(resolved_facts).to eql([resolved_fact]) end context 'when nil' do let(:user_query) { 'virtual' } let(:resolved_fact) { mock_resolved_fact('virtual', nil, '', :core) } before do # mock all custom facts to return [] allow(fact_loader).to receive(:load_custom_facts).and_return([]) end it 'does not resolve fact' do resolved_facts = Facter::FactManager.instance.resolve_fact(user_query) expect(resolved_facts).to be_empty end end context 'when boolean false' do let(:user_query) { 'fips_enabled' } let(:resolved_fact) { mock_resolved_fact('fips_enabled', false, '', :core) } it 'resolves fact to false' do resolved_facts = Facter::FactManager.instance.resolve_fact(user_query) expect(resolved_facts.first.value).to be(false) end end end context 'with non existent fact' do let(:user_query) { 'non_existent' } let(:fact_name) { 'non_existent' } let(:custom_fact) { instance_double(Facter::LoadedFact, name: 'custom_fact', klass: nil, type: :custom) } let(:loaded_facts) { [custom_fact] } let(:resolved_fact) { mock_resolved_fact(fact_name, 'custom', '', :custom) } before do # mock custom_fact_by_filename to return nil allow(fact_loader).to receive(:load_custom_fact).and_return([]) stub_query_parser([[user_query], []], []) stub_external_manager([], []) stub_cache_manager([], []) # mock core_or_external_fact to return nil allow(fact_loader).to receive(:load_internal_facts).and_return([]) allow(fact_loader).to receive(:load_external_facts).and_return([]) stub_query_parser([[user_query], []], []) stub_internal_manager([], []) stub_external_manager([], []) stub_cache_manager([], []) # mock all_custom_facts to return nil allow(fact_loader).to receive(:load_custom_facts).and_return([]) stub_query_parser([[user_query], []], []) stub_external_manager([], []) stub_cache_manager([], []) end it 'tries to load it from fact_name.rb' do Facter::FactManager.instance.resolve_fact(user_query) expect(logger).to have_received(:debug) .with("Searching fact: #{user_query} in file: #{user_query}.rb") end it 'loads core and external facts' do Facter::FactManager.instance.resolve_fact(user_query) expect(logger).to have_received(:debug) .with("Searching fact: #{user_query} in core facts and external facts") end it 'loads all custom facts' do Facter::FactManager.instance.resolve_fact(user_query) expect(logger).to have_received(:debug) .with("Searching fact: #{user_query} in all custom facts") end it 'resolves fact' do resolved_facts = Facter::FactManager.instance.resolve_fact(user_query) expect(resolved_facts).to eql([]) end end end describe '#resolve_core' do let(:user_query) { [] } let(:ubuntu_os_name) { class_double(Facts::Linux::Os::Name) } let(:loaded_facts) do instance_double(Facter::LoadedFact, name: 'os.name', klass: ubuntu_os_name, type: :core) end let(:searched_fact) do instance_double( Facter::SearchedFact, name: 'os', fact_class: ubuntu_os_name, user_query: '', type: :core ) end let(:resolved_fact) { mock_resolved_fact('os', 'Ubuntu', '') } it 'resolves all core facts' do allow(fact_loader).to receive(:load_internal_facts).and_return(loaded_facts) allow(fact_loader).to receive(:internal_facts).and_return(loaded_facts) allow(fact_loader).to receive(:load_external_facts).and_return([]) stub_query_parser([user_query, loaded_facts], [searched_fact]) stub_internal_manager([searched_fact], [resolved_fact]) stub_cache_manager([searched_fact], []) resolved_facts = Facter::FactManager.instance.resolve_core(user_query) expect(resolved_facts).to eq([resolved_fact]) end end end
37.236715
120
0.650493
08b6ec4ebc2a58e628f1f5c8e5a7db7389703d11
558
require 'active_support/core_ext/hash/indifferent_access' module ActiveRecord::Turntable class Config include Singleton def self.[](key) instance[key] end def [](key) self.class.load!(ActiveRecord::Base.turntable_config_file) unless @config @config[key] end def self.load!(config_file, env = (defined?(Rails) ? Rails.env : 'development')) instance.load!(config_file, env) end def load!(config_file, env) @config = YAML.load_file(config_file).with_indifferent_access[env] end end end
22.32
84
0.681004
18b647d5d1ee9625d45233e3b42ef471e15a892e
865
cask "iina-plus" do version "0.6.6,22042822" sha256 "584d29420fe82cdf3980bc7df4b54a052f6fbef4a31f64d0e837a85a985af1af" url "https://github.com/xjbeta/iina-plus/releases/download/#{version.csv.first}(#{version.csv.second})/iina+.#{version.csv.first}.dmg" name "IINA+" desc "Extra danmaku support for iina (iina 弹幕支持)" homepage "https://github.com/xjbeta/iina-plus" livecheck do url "https://github.com/xjbeta/iina-plus/releases/latest" strategy :page_match do |page| match = page.match(/(\d+(?:\.\d+)+)\((\d+)\)/i) next if match.blank? "#{match[1]},#{match[2]}" end end app "iina+.app" zap trash: [ "~/Library/Application Support/com.xjbeta.iina-plus", "~/Library/Caches/com.xjbeta.iina-plus", "~/Library/Preferences/com.xjbeta.iina-plus.plist", "~/Library/WebKit/com.xjbeta.iina-plus", ] end
29.827586
136
0.669364
ed944a3d407431041aa5c952839b3e27b19ad213
146
module Linter class Ruby < Base FILE_REGEXP = /.+(\.rb|\.rake)\z/ private def job_name "RubocopReviewJob" end end end
12.166667
37
0.589041
4a596f08108527e3e85d22b1f9487cfb5217d140
1,572
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. require "csv" module Arrow class CSVReader def initialize(csv) @csv = csv end def read values_set = [] @csv.each do |row| if row.is_a?(CSV::Row) row = row.collect(&:last) end row.each_with_index do |value, i| values = (values_set[i] ||= []) values << value end end return nil if values_set.empty? arrays = values_set.collect.with_index do |values, i| ArrayBuilder.build(values) end if @csv.headers names = @csv.headers else names = arrays.size.times.collect(&:to_s) end raw_table = {} names.each_with_index do |name, i| raw_table[name] = arrays[i] end Table.new(raw_table) end end end
28.581818
62
0.658397
edb0c11aa6f8ddf7446302ce01f7aa256f943712
674
module Hammock module ActionControllerPatches MixInto = ActionController::Rescue def self.included base base.send :include, InstanceMethods base.send :extend, ClassMethods # base.class_eval { # alias_method_chain :clean_backtrace, :truncation # } end module ClassMethods end module InstanceMethods private def clean_backtrace_with_truncation exception if backtrace = clean_backtrace_without_truncation(exception) backtrace.take_while {|line| line['perform_action_without_filters'].nil? }.push("... and so on") end end end end end
20.424242
68
0.649852
eda4151550266c3090615d1fe2d6b83ee58d9bbe
703
require 'sinatra/base' require './controllers/application' require './controllers/account' require './controllers/item' require './controllers/category' require './models/category' require './models/account' require './models/item' require './models/location' require './controllers/location' require './controllers/setting' require './controllers/sell' require './controllers/search' map('/') {run ApplicationController} map('/login') {run AccountsController} map('/dash') {run ItemsController} map('/categories') {run CategoriesController} map('/locations') {run LocationsController} map('/settings') {run SettingsController} map('/sell') {run SalesController} map('/search') {run SearchController}
29.291667
45
0.756757
7a6aa4ed34c8146ccfda475f24511337fdff451a
146
require "test_helper" class StimulantTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::Stimulant::VERSION end end
18.25
39
0.794521
d5d7349d449653fe53114a631f3a8bc7f99cd7c7
657
require "geny/command" require "geny/registry" require "geny/actions/geny" RSpec.describe Geny::Actions::Geny do let(:command) { instance_double(Geny::Command) } let(:registry) { instance_double(Geny::Registry, find!: command) } subject(:geny) { described_class.new(registry: registry) } describe "#run" do it "runs a command with arguments" do expect(command).to receive(:run).with(["--name", "foo"]) geny.run "cmd", "--name", "foo" end end describe "#invoke" do it "invokes a command with options" do expect(command).to receive(:invoke).with(name: "foo") geny.invoke "cmd", name: "foo" end end end
27.375
68
0.660578
f8404589d3bdaf82581b7d7730808b9e64b5a6ef
1,328
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require File.expand_path(File.dirname(__FILE__) + "/../lib/connection_content") require 'fileutils' describe ActiveRecord::ConnectionAdapters::MysqlAdapter do before(:each) do @connection = ActiveRecord::Base.connection end describe :load_content_from do it 'should load from uncompressed file' do @connection.load_content_from("#{File.dirname(__FILE__)}/data/content.sql") end it 'should load from compressed file' do @connection.load_content_from("#{File.dirname(__FILE__)}/data/content.sql.gz") end end describe :dump_content_to do before(:each) do @tmpdir = File.join(File.dirname(__FILE__), 'tmp') FileUtils.mkdir_p @tmpdir end it 'should dump to uncompressed file' do pathname = File.join(@tmpdir, 'content.sql') @connection.dump_content_to(pathname) File.exists?(pathname).should == true @connection.load_content_from(pathname) FileUtils.rm_r @tmpdir end it 'should dump to compressed file' do pathname = File.join(@tmpdir, 'content.sql.gz') @connection.dump_content_to(pathname) File.exists?(pathname).should == true @connection.load_content_from(pathname) FileUtils.rm_r @tmpdir end end end
30.883721
84
0.696536
3863e582899668b65a16bcccc55090b73c04358a
3,792
puts "\noptimize position:\n\n" class Position attr_accessor :x, :y, :z def initialize( x, y, z ) @x = x @y = y @z = z end end position_values = [] position_base_values = [] position_identical = 0 File.readlines( 'scripts/position_values.txt' ).each do |line| values = line.split( ',' ) position = Position.new( values[0].to_i, values[1].to_i, values[2].to_i ) position_values.push position position_base = Position.new( values[3].to_i, values[4].to_i, values[5].to_i ) if position.x == position_base.x && position.y == position_base.y && position.z == position_base.z position_identical += 1 end position_base_values.push position_base #puts "#{position.x},#{position.y},#{position.z},#{position_base.x},#{position_base.y},#{position_base.z}" end class PositionBandwidthEstimate attr_accessor :small_bits_xy, :large_bits_xy, :small_bits_z, :large_bits_z, :total_bits def initialize small_bits_xy, large_bits_xy, small_bits_z, large_bits_z @small_bits_xy = small_bits_xy @large_bits_xy = large_bits_xy @small_bits_z = small_bits_z @large_bits_z = large_bits_z @total_bits = 0 end def evaluate position_values, position_base_values bits = 0 small_threshold_xy = ( 1 << ( @small_bits_xy - 1 ) ) - 1; large_threshold_xy = ( 1 << ( @large_bits_xy - 1 ) ) - 1 + small_threshold_xy; small_threshold_z = ( 1 << ( @small_bits_z - 1 ) ) - 1; large_threshold_z = ( 1 << ( @large_bits_z - 1 ) ) - 1 + small_threshold_z; position_values.each_index do |i| position = position_values[i] base_position = position_base_values[i] dx = position.x - base_position.x dy = position.y - base_position.y dz = position.z - base_position.z if dx.abs >= large_threshold_xy || dy.abs >= large_threshold_xy || dz.abs >= large_threshold_z bits += 1 + 18 + 18 + 14 else small_x = dx.abs < small_threshold_xy small_y = dy.abs < small_threshold_xy small_z = dz.abs < small_threshold_z bits += 1 + 3 if small_x bits += small_bits_xy else bits += large_bits_xy end if small_y bits += small_bits_xy else bits += large_bits_xy end if small_z bits += small_bits_z else bits += large_bits_z end end end @total_bits = bits end def name "#{small_bits_xy}-#{large_bits_xy}-#{small_bits_z}-#{large_bits_z}" end end position_bandwidth_estimates = [] for small_bits_xy in 2..6 for large_bits_xy in 8..10 for small_bits_z in 2..6 for large_bits_z in 8..10 bandwidth_estimate = PositionBandwidthEstimate.new( small_bits_xy, large_bits_xy, small_bits_z, large_bits_z ) puts bandwidth_estimate.name bandwidth_estimate.evaluate position_values, position_base_values position_bandwidth_estimates.push bandwidth_estimate end end end end position_bandwidth_estimates.sort! { |a,b| a.total_bits <=> b.total_bits } absolute_position_bits = ( 1 + 18 + 18 + 14 ) * position_values.size puts puts "num position samples: #{position_values.size}" puts puts "absolute position: #{absolute_position_bits} bits" puts for i in 0..9 bandwidth_estimate = position_bandwidth_estimates[i] puts "compression #{bandwidth_estimate.name}: #{bandwidth_estimate.total_bits} (#{(bandwidth_estimate.total_bits/absolute_position_bits.to_f*100.0).round(1)})" end best = position_bandwidth_estimates[0] puts "\naverage bits per-position: #{(best.total_bits/position_values.size.to_f).round(2)}" puts
28.727273
161
0.649262
913ed6640a22383bf0315c146ade4820d82e7e11
1,478
class Gssdp < Formula desc "GUPnP library for resource discovery and announcement over SSDP" homepage "https://wiki.gnome.org/GUPnP/" url "https://download.gnome.org/sources/gssdp/1.0/gssdp-1.0.2.tar.xz" sha256 "a1e17c09c7e1a185b0bd84fd6ff3794045a3cd729b707c23e422ff66471535dc" revision 1 bottle do cellar :any sha256 "c8ac9c7c755749b7a6ea9790efab2311c9fc3d62a1af62b719968f14a7c25b62" => :high_sierra sha256 "3786f067d3b19ce3021618aaf434fd325862f90d03b7fd5ac12f6f37f8715e42" => :sierra sha256 "7927b712f8f9570c0a7e21593786bd41edf0daf2e14b7998886af9a00a8c2ab0" => :el_capitan end depends_on "pkg-config" => :build depends_on "intltool" => :build depends_on "gettext" depends_on "glib" depends_on "libsoup" def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <libgssdp/gssdp.h> int main(int argc, char *argv[]) { GType type = gssdp_client_get_type(); return 0; } EOS gettext = Formula["gettext"] glib = Formula["glib"] flags = %W[ -I#{gettext.opt_include} -I#{glib.opt_include}/glib-2.0 -I#{glib.opt_lib}/glib-2.0/include -I#{include}/gssdp-1.0 -D_REENTRANT -L#{lib} -lgssdp-1.0 ] system ENV.cc, "test.c", "-o", "test", *flags system "./test" end end
28.980392
93
0.663058
875792f35f23b44b911a05518bb1f8d180863034
233
development: bucket: <%= @name %>_development access_key_id: secret_access_key: test: bucket: <%= @name %>_test access_key_id: secret_access_key: production: bucket: <%= @name %> access_key_id: secret_access_key:
15.533333
34
0.695279
1c17672a69aed33712f151ab45c74e8f490d4697
209
class CreateTableAnswers < ActiveRecord::Migration[5.2] def change create_table :answers do |t| t.string :text t.boolean :is_correct, :default => false t.integer :question_id end end end
20.9
55
0.698565
1cd2fb07694db191481afa7787d2791b9cc8ee02
1,249
#!/usr/bin/env ruby # Test to see if Struct can be inherited from usefully. BEGIN { base = File.dirname( File.dirname(File.expand_path(__FILE__)) ) $LOAD_PATH.unshift "#{base}/lib" require "#{base}/utils.rb" include UtilityFunctions } try( "to subclass Struct as ConfigStruct" ) { class ConfigStruct < Struct def to_h rhash = {} self.members.collect {|name| name.to_sym}.each {|sym| val = self.send(sym) case val when ConfigStruct rhash[ sym ] = val.to_h else rhash[ sym ] = val end } return rhash end end } try( "to make ConfigStruct derivatives" ) { ArrowConfig = ConfigStruct.new( "ArrowConfig", :templates, :apps ) TemplateConfig = ConfigStruct.new( "ArrowTemplateConfig", :path, :cache ) AppsConfig = ConfigStruct.new( "ArrowAppsConfig", :path ) } tconf, aconf, conf = nil, nil, nil try( "to make some ConfigStruct derivative objects" ) { tconf = TemplateConfig.new( "/www:/www/templates", true ) aconf = AppsConfig.new( "/www/apps" ) conf = ArrowConfig.new( tconf, aconf ) [tconf, aconf, conf] } try( "conf.templates.path", binding ) try( "conf.templates.cache", binding ) try( "conf.apps.path", binding ) try( "to dump the toplevel configstruct to a hash" ) { conf.to_h }
23.12963
74
0.678943
6a0d36a1b8e7a83b7ec3bb49b7ea0c94d4a2b47f
1,981
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) require 'enumerator' describe "Enumerable#each_slice" do before :each do @enum = EnumerableSpecs::Numerous.new(7,6,5,4,3,2,1) @sliced = [[7,6,5],[4,3,2],[1]] end it "passes element groups to the block" do acc = [] @enum.each_slice(3){|g| acc << g}.should be_nil acc.should == @sliced end it "raises an Argument Error if there is not a single parameter > 0" do lambda{ @enum.each_slice(0){} }.should raise_error(ArgumentError) lambda{ @enum.each_slice(-2){} }.should raise_error(ArgumentError) lambda{ @enum.each_slice{} }.should raise_error(ArgumentError) lambda{ @enum.each_slice(2,2){} }.should raise_error(ArgumentError) end it "tries to convert n to an Integer using #to_int" do acc = [] @enum.each_slice(3.3){|g| acc << g}.should == nil acc.should == @sliced obj = mock('to_int') obj.should_receive(:to_int).and_return(3) @enum.each_slice(obj){|g| break g.length}.should == 3 end it "works when n is >= full length" do full = @enum.to_a acc = [] @enum.each_slice(full.length){|g| acc << g} acc.should == [full] acc = [] @enum.each_slice(full.length+1){|g| acc << g} acc.should == [full] end it "yields only as much as needed" do cnt = EnumerableSpecs::EachCounter.new(1, 2, :stop, "I said stop!", :got_it) cnt.each_slice(2) {|g| break 42 if g[0] == :stop }.should == 42 cnt.times_yielded.should == 4 end ruby_version_is "1.8.7" do it "returns an enumerator if no block" do e = @enum.each_slice(3) e.should be_an_instance_of(enumerator_class) e.to_a.should == @sliced end it "gathers whole arrays as elements when each yields multiple" do multi = EnumerableSpecs::YieldsMulti.new multi.each_slice(2).to_a.should == [[[1, 2], [3, 4, 5]], [[6, 7, 8, 9]]] end end end
31.444444
80
0.635033
e9ecd955a83ea60e1ecf5fa0d9c7ad69afc39ab1
2,892
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::ImportExport::Mgmt::V2016_11_01 module Models # # Contains the job information. # class JobResponse include MsRestAzure # @return [String] Specifies the resource identifier of the job. attr_accessor :id # @return [String] Specifies the name of the job. attr_accessor :name # @return [String] Specifies the type of the job resource. attr_accessor :type # @return [String] Specifies the Azure location where the job is created. attr_accessor :location # @return Specifies the tags that are assigned to the job. attr_accessor :tags # @return [JobDetails] Specifies the job properties attr_accessor :properties # # Mapper for JobResponse class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'JobResponse', type: { name: 'Composite', class_name: 'JobResponse', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, location: { client_side_validation: true, required: false, serialized_name: 'location', type: { name: 'String' } }, tags: { client_side_validation: true, required: false, serialized_name: 'tags', type: { name: 'Object' } }, properties: { client_side_validation: true, required: false, serialized_name: 'properties', type: { name: 'Composite', class_name: 'JobDetails' } } } } } end end end end
27.542857
79
0.4713
6a8774a6763e0b57074cf012c3a0edc67ea1a28a
4,734
# frozen_string_literal: true # Cloud Foundry Java Buildpack # Copyright 2013-2018 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'spec_helper' require 'component_helper' require 'fileutils' require 'java_buildpack/container/tomcat' require 'java_buildpack/container/tomcat/tomcat_access_logging_support' require 'java_buildpack/container/tomcat/tomcat_geode_store' require 'java_buildpack/container/tomcat/tomcat_insight_support' require 'java_buildpack/container/tomcat/tomcat_instance' require 'java_buildpack/container/tomcat/tomcat_lifecycle_support' require 'java_buildpack/container/tomcat/tomcat_logging_support' require 'java_buildpack/container/tomcat/tomcat_redis_store' describe JavaBuildpack::Container::Tomcat do include_context 'with component help' let(:component) { StubTomcat.new context } let(:configuration) do { 'access_logging_support' => access_logging_support_configuration, 'external_configuration' => tomcat_external_configuration, 'geode_store' => geode_store_configuration, 'lifecycle_support' => lifecycle_support_configuration, 'logging_support' => logging_support_configuration, 'redis_store' => redis_store_configuration, 'tomcat' => tomcat_configuration } end let(:access_logging_support_configuration) { instance_double('logging-support-configuration') } let(:lifecycle_support_configuration) { instance_double('lifecycle-support-configuration') } let(:logging_support_configuration) { instance_double('logging-support-configuration') } let(:geode_store_configuration) { instance_double('geode_store_configuration') } let(:redis_store_configuration) { instance_double('redis-store-configuration') } let(:tomcat_configuration) { { 'external_configuration_enabled' => false } } let(:tomcat_external_configuration) { instance_double('tomcat_external_configuration') } it 'detects WEB-INF', app_fixture: 'container_tomcat' do expect(component).to be_supports end it 'does not detect when WEB-INF is absent', app_fixture: 'container_main' do expect(component).not_to be_supports end it 'does not detect when WEB-INF is present in a Java main application', app_fixture: 'container_main_with_web_inf' do expect(component).not_to be_supports end it 'creates submodules' do allow(JavaBuildpack::Container::TomcatAccessLoggingSupport) .to receive(:new).with(sub_configuration_context(access_logging_support_configuration)) allow(JavaBuildpack::Container::TomcatGeodeStore) .to receive(:new).with(sub_configuration_context(geode_store_configuration)) allow(JavaBuildpack::Container::TomcatInstance) .to receive(:new).with(sub_configuration_context(tomcat_configuration)) allow(JavaBuildpack::Container::TomcatInsightSupport).to receive(:new).with(context) allow(JavaBuildpack::Container::TomcatLifecycleSupport) .to receive(:new).with(sub_configuration_context(lifecycle_support_configuration)) allow(JavaBuildpack::Container::TomcatLoggingSupport) .to receive(:new).with(sub_configuration_context(logging_support_configuration)) allow(JavaBuildpack::Container::TomcatRedisStore) .to receive(:new).with(sub_configuration_context(redis_store_configuration)) component.sub_components context end it 'returns command' do expect(component.command).to eq("test-var-2 test-var-1 JAVA_OPTS=$JAVA_OPTS #{java_home.as_env_var} exec " \ '$PWD/.java-buildpack/tomcat/bin/catalina.sh run') end context do let(:tomcat_configuration) { { 'external_configuration_enabled' => true } } it 'creates submodule TomcatExternalConfiguration' do allow(JavaBuildpack::Container::TomcatExternalConfiguration) .to receive(:new).with(sub_configuration_context(tomcat_external_configuration)) component.sub_components context end end end class StubTomcat < JavaBuildpack::Container::Tomcat public :command, :sub_components, :supports? end def sub_configuration_context(configuration) c = context.clone c[:configuration] = configuration c end
37.872
112
0.765104
9140abd83c591eedb1ecc43b43e7573ab1392502
1,224
# # Be sure to run `pod spec lint SNetwork.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| s.name = "SNetwork" s.version = "0.0.1" s.summary = "Simple and lightweight networking for your App" s.description = <<-DESC This pod helps you make simple network requests. DESC s.homepage = 'https://github.com/kurtulusahmet/SNetwork.git' s.license = 'MIT' s.author = { "kurtulusahmettemel" => "kurtulusahmettemel@gmail.com" } s.social_media_url = "https://twitter.com/_kurtulusahmet" s.source = { :git => "https://github.com/kurtulusahmet/SNetwork.git", :tag => "#{s.version}" } s.framework = "XCTest" s.requires_arc = true s.ios.deployment_target = '9.0' s.source_files = 'SNetwork/**/*.{c,h,hh,m,mm,swift}' s.dependency 'Alamofire', '~> 4.7' s.swift_version = '4.2' s.pod_target_xcconfig = { 'SWIFT_VERSION' => '4.2' } end
34
106
0.64134
f81e127588ca5e4c7016a60db7d82184ded87c27
160
class Hash def symbolize_keys inject({}) do |options, (key, value)| options[(key.to_sym rescue key) || key] = value options end end end
17.777778
53
0.6125
210bfbd5701cdda4dc61149d8e0c2f82e635275f
451
# frozen_string_literal: true require 'yaml' require_relative 'env/version' module RuboCop # Rubocop Cop for checking ENV module Env class Error < StandardError; end PROJECT_ROOT = Pathname.new(__dir__).parent.parent.expand_path.freeze CONFIG_DEFAULT = PROJECT_ROOT.join('config', 'default.yml').freeze CONFIG = YAML.safe_load(CONFIG_DEFAULT.read).freeze private_constant(:CONFIG_DEFAULT, :PROJECT_ROOT) end end
26.529412
75
0.745011
28803164fcfb29d079f76598b4b75b5069fb65b7
2,016
class ProfilesController < Profiles::ApplicationController include ActionView::Helpers::SanitizeHelper before_action :user before_action :authorize_change_username!, only: :update_username skip_before_action :require_email, only: [:show, :update] def show end def applications @applications = current_user.oauth_applications @authorized_tokens = current_user.oauth_authorized_tokens @authorized_anonymous_tokens = @authorized_tokens.reject(&:application) @authorized_apps = @authorized_tokens.map(&:application).uniq - [nil] end def update user_params.except!(:email) if @user.ldap_user? if @user.update_attributes(user_params) flash[:notice] = "Profile was successfully updated" else messages = @user.errors.full_messages.uniq.join('. ') flash[:alert] = "Failed to update profile. #{messages}" end respond_to do |format| format.html { redirect_back_or_default(default: { action: 'show' }) } end end def reset_private_token if current_user.reset_authentication_token! flash[:notice] = "Token was successfully updated" end redirect_to profile_account_path end def audit_log @events = AuditEvent.where(entity_type: "User", entity_id: current_user.id). order("created_at DESC"). page(params[:page]). per(PER_PAGE) end def update_username @user.update_attributes(username: user_params[:username]) respond_to do |format| format.js end end private def user @user = current_user end def authorize_change_username! return render_404 unless @user.can_change_username? end def user_params params.require(:user).permit( :avatar, :bio, :email, :hide_no_password, :hide_no_ssh_key, :hide_project_limit, :linkedin, :location, :name, :password, :password_confirmation, :public_email, :skype, :twitter, :username, :website_url ) end end
23.172414
80
0.687004
f8c37d6b24cabe597f01544696611590bb2345f7
2,432
class Span < ApplicationRecord belongs_to :application belongs_to :host belongs_to :grouping, :primary_key => :uuid, :polymorphic => true belongs_to :layer belongs_to :trace, :primary_key => :trace_key, :foreign_key => :trace_key belongs_to :parent, :primary_key => :uuid, :class_name => "Span" has_many :children, :primary_key => :uuid, :foreign_key => :parent_id, :class_name => "Span" has_many :log_entries, :primary_key => :uuid has_one :database_call, :primary_key => :uuid has_one :backtrace, :as => :backtraceable, :primary_key => :uuid has_one :error, :primary_key => :uuid, :class_name => "ErrorDatum" delegate :name, :to => :layer, :prefix => true def tags payload end def has_error? tag("error") == true end def tag(key) if payload.is_a?(Hash) payload[key.to_s] else nil end end def source @log_entry ||= log_entries.where(:event => "source").first || LogEntry.new if @log_entry.fields @log_entry.fields.fetch("stack", nil) || @log_entry.fields.fetch(":stack", nil) else nil end end def is_root? parent_id == nil end def is_query?(uuid) grouping_type.eql?("DatabaseCall") && grouping_id.to_s.eql?(uuid) end def end timestamp.to_f + duration.to_f end def exclusive_duration duration - children.inject(0.0) { |sum, child| sum + child.duration } end def ancestors ancestors = [] metric = self while parent = metric.parent ancestors << parent metric = parent end ancestors end def send_chain(arr) Array(arr).inject({}) { |o, a| o.merge(a => self.send(a)) } end def dump_attribute_tree(attributes = [:id]) if children.present? [ self.send_chain(attributes), :children => children.map {|c| c.dump_attribute_tree(attributes) }.flatten ] else [self.send_chain(attributes)] end end # Returns if the current node is the parent of the given node. # If this is a new record, we can use started_at values to detect parenting. # However, if it was already saved, we lose microseconds information from # timestamps and we must rely solely in id and parent_id information. def parent_of?(span) start = (timestamp - span.timestamp) * 1000.0 start <= 0 && (start + duration >= span.duration) end def child_of?(span) span.parent_of?(self) end end
24.079208
94
0.648849
ab61d3ec91fc4c32be59cdd1261a08e0f143c614
557
cask "quarto" do version "0.3.118" sha256 "b8d87cf3ce36157c483b438a44f1012b588b422de3f607f92329b19cdbfc77ee" url "https://github.com/quarto-dev/quarto-cli/releases/download/v#{version}/quarto-#{version}-macos.pkg", verified: "github.com/quarto-dev/quarto-cli/" name "quarto" desc "Scientific and technical publishing system built on Pandoc" homepage "https://www.quarto.org/" depends_on macos: ">= :el_capitan" pkg "quarto-#{version}-macos.pkg" uninstall pkgutil: "org.rstudio.quarto" zap trash: "~/Library/Caches/quarto" end
29.315789
107
0.736086
ff0d2de682ed718bc564eabfc001e0f71cf1e2d1
1,547
#!/usr/bin/env ruby require 'test/unit' # Unit test for io/tcpserver.rb require_relative '../../io/tcpfns' require_relative '../../io/tcpserver' class TestTCPDbgServer < Test::Unit::TestCase include Trepanning::TCPPacking def test_basic server = Trepan::TCPDbgServer.new({ :open => false, :port => 1027, :host => 'localhost' }) server.open threads = [] msgs = %w(one two three) Thread.new do msgs.each do |msg| begin line = server.read_msg.chomp assert_equal(msg, line) rescue EOFError puts 'Got EOF' break end end end threads << Thread.new do begin t = TCPSocket.new('localhost', 1027) msgs.each do |msg| begin t.puts(pack_msg(msg)) rescue EOFError puts "Got EOF" break rescue Exception => e puts "Got #{e}" break end end t.close rescue Errno::ECONNREFUSED skip "Can't open client port 1027" end end threads.each {|t| t.join } server.close end end
28.648148
66
0.401422
f793e300b2ac5561862e0cbda8d70c683799b41b
551
# frozen_string_literal: true module Resolvers module AccessGrants class UserCollectionResolver < GraphQL::Schema::Resolver include SearchObject.module(:graphql) include Resolvers::PageBasedPagination include Resolvers::SimplyOrdered type Types::UserCollectionAccessGrantType.connection_type, null: false scope do if object.respond_to?(:access_grants) object.access_grants.with_preloads.for_collections.for_users else AccessGrant.none end end end end end
23.956522
76
0.711434
abf4ab7325b090dea471b64747d63a49e912ac37
3,256
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::DataMigration::Mgmt::V2018_07_15_preview module Models # # Results for schema comparison between the source and target # class SchemaComparisonValidationResult include MsRestAzure # @return [SchemaComparisonValidationResultType] List of schema # differences between the source and target databases attr_accessor :schema_differences # @return [ValidationError] List of errors that happened while performing # schema compare validation attr_accessor :validation_errors # @return [Hash{String => Integer}] Count of source database objects attr_accessor :source_database_object_count # @return [Hash{String => Integer}] Count of target database objects attr_accessor :target_database_object_count # # Mapper for SchemaComparisonValidationResult class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'SchemaComparisonValidationResult', type: { name: 'Composite', class_name: 'SchemaComparisonValidationResult', model_properties: { schema_differences: { client_side_validation: true, required: false, serialized_name: 'schemaDifferences', type: { name: 'Composite', class_name: 'SchemaComparisonValidationResultType' } }, validation_errors: { client_side_validation: true, required: false, serialized_name: 'validationErrors', type: { name: 'Composite', class_name: 'ValidationError' } }, source_database_object_count: { client_side_validation: true, required: false, serialized_name: 'sourceDatabaseObjectCount', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'BignumElementType', type: { name: 'Number' } } } }, target_database_object_count: { client_side_validation: true, required: false, serialized_name: 'targetDatabaseObjectCount', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'BignumElementType', type: { name: 'Number' } } } } } } } end end end end
32.888889
79
0.523034
f745811bfcb7b9f81253dd37ea746f6b47c9d84f
289
require File.expand_path('../../../../spec_helper', __FILE__) describe "Gem::DependencyResolver#development_shallow" do it "needs to be reviewed for spec completeness" end describe "Gem::DependencyResolver#development_shallow=" do it "needs to be reviewed for spec completeness" end
28.9
61
0.771626
7ae28e8711ad987c32f92e39eba0742ae7be9403
1,499
# # The MIT License # Copyright (c) 2019- Nordic Institute for Interoperability Solutions (NIIS) # Copyright (c) 2018 Estonian Information System Authority (RIA), # Nordic Institute for Interoperability Solutions (NIIS), Population Register Centre (VRK) # Copyright (c) 2015-2017 Estonian Information System Authority (RIA), Population Register Centre (VRK) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # class FeedbackController < ApplicationController def index # NOP end end
46.84375
103
0.779186
e221477b34eb8ec4426dbf688459affc7fb52b70
1,635
module AbAdmin class Engine < ::Rails::Engine engine_name 'ab_admin' initializer 'ab_admin.assets_precompile', :group => :all do |app| app.config.assets.precompile += AbAdmin.assets end initializer 'ab_admin.setup' do ::Mime::Type.register 'application/vnd.ms-excel', :xlsx ActiveSupport.on_load :active_record do ActiveRecord::Base.send :include, ActiveModel::ForbiddenAttributesProtection ActiveRecord::Base.send :include, AbAdmin::CarrierWave::Glue ActiveRecord::Base.send :include, AbAdmin::Utils::Mysql ActiveRecord::Base.send :include, AbAdmin::Concerns::DeepCloneable ActiveRecord::Base.send :include, AbAdmin::Concerns::Utilities ActiveRecord::Base.send :include, AbAdmin::Concerns::Silencer ActiveRecord::Base.send :extend, AbAdmin::Concerns::Silencer ActiveRecord::Base.send :include, AbAdmin::Concerns::Validations ActiveRecord::Base.send :include, AbAdmin::Concerns::Fileuploads ActiveRecord::Base.send :extend, AbAdmin::Concerns::TranslationsMacro ActiveRecord::Base.send :extend, EnumField::EnumeratedAttribute end ActiveSupport.on_load :action_mailer do ActionMailer::Base.send :include, AbAdmin::Mailers::Helpers end ActiveSupport.on_load :action_view do ActionController::Base.helper AbAdmin::Views::Helpers ActionController::Base.helper AbAdmin::Views::AdminHelpers ActionController::Base.helper AbAdmin::Views::AdminNavigationHelpers ActionController::Base.helper AbAdmin::Views::ManagerHelpers end end end end
41.923077
84
0.715596
e95237dfe0295134e5111bc71b959c1f5c1ba35c
2,201
# coding: utf-8 require 'spec_helper' require 'support/editor' require 'support/playground_actions' RSpec.feature "Using third-party Rust tools", type: :feature, js: true do include PlaygroundActions before { visit '/' } scenario "formatting code" do editor.set 'fn main() { [1,2,3,4]; }' in_tools_menu { click_on("Rustfmt") } within('.editor') do expect(editor).to have_line '[1, 2, 3, 4];' end end scenario "linting code with Clippy" do editor.set code_with_lint_warnings in_tools_menu { click_on("Clippy") } within(".output-stderr") do expect(page).to have_content 'deny(clippy::eq_op)' expect(page).to have_content 'warn(clippy::zero_divided_by_zero)' end end def code_with_lint_warnings <<~EOF use itertools::Itertools; fn example() { let a = 0.0 / 0.0; println!("NaN is {}", a); } EOF end scenario "sanitize code with Miri" do editor.set code_with_undefined_behavior in_tools_menu { click_on("Miri") } within(".output-stderr") do expect(page).to have_content %r{pointer must be in-bounds at offset 1, but is outside bounds of alloc\d+ which has size 0}, wait: 10 end end def code_with_undefined_behavior <<~EOF fn main() { let mut a: [u8; 0] = []; unsafe { *a.get_unchecked_mut(1) = 1; } } EOF end scenario "expand macros with the nightly compiler" do editor.set code_that_uses_macros in_tools_menu { click_on("Expand macros") } within(".output-stdout") do # First-party expect(page).to have_content('core::fmt::Arguments::new_v1') # Third-party procedural macro expect(page).to have_content('block_on(async') # User-specified declarative macro expect(page).to have_content('fn created_by_macro() -> i32 { 42 }') end end def code_that_uses_macros <<~EOF macro_rules! demo { ($name:ident) => { fn $name() -> i32 { 42 } } } demo!(created_by_macro); #[tokio::main] async fn example() { println!("a value: {}", created_by_macro()); } EOF end def editor Editor.new(page) end end
22.459184
138
0.626079
398f43438295fbdbd92e446f0fb2dccc784b42fd
987
module Outpost class SessionsController < Outpost::BaseController skip_before_filter :require_login before_filter :get_authentication_attribute respond_to :html def new redirect_to outpost.root_path if current_user end def create if user = Outpost.user_class.authenticate( params[@authentication_attribute], params[:password]) session[:user_id] = user.id user.update_column(:last_login, Time.zone.now) redirect_to session[:return_to] || outpost.root_path, notice: "Logged in." session[:return_to] = nil else flash.now[:alert] = "Invalid login information." render :new end end def destroy @current_user = nil session[:user_id] = nil redirect_to outpost.login_path, notice: "Logged Out." end private def get_authentication_attribute @authentication_attribute = Outpost.config.authentication_attribute end end end
23.5
73
0.674772
9127eda68a454ec7674ff02b906ff3c158eaead6
155
class AddSlugToPosts < ActiveRecord::Migration[5.2] def change add_column :posts, :slug, :string add_index :posts, :slug, unique: true end end
22.142857
51
0.709677
ed611befd864d7ad5b70e46e2a96ee35c4931378
977
require "spec_helper" describe Paperclip::Processor do it "instantiates and call #make when sent #make to the class" do processor = double expect(processor).to receive(:make) expect(Paperclip::Processor).to receive(:new).with(:one, :two, :three).and_return(processor) Paperclip::Processor.make(:one, :two, :three) end context "Calling #convert" do it "runs the convert command with Terrapin" do Paperclip.options[:log_command] = false expect(Terrapin::CommandLine).to receive(:new).with("convert", "stuff", {}).and_return(double(run: nil)) Paperclip::Processor.new("filename").convert("stuff") end end context "Calling #identify" do it "runs the identify command with Terrapin" do Paperclip.options[:log_command] = false expect(Terrapin::CommandLine).to receive(:new).with("identify", "stuff", {}).and_return(double(run: nil)) Paperclip::Processor.new("filename").identify("stuff") end end end
36.185185
111
0.694985
e91e8bd1ebff83dda7544ac16afca6f9813b7597
1,019
# frozen_string_literal: true require 'zenaton/refinements/date' RSpec.describe Date do using Zenaton::Refinements describe '#to_zenaton' do subject { described_class.new(2018, 8, 1).to_zenaton } let(:expected) do { 'y' => 2018, 'm' => 8, 'd' => 1, 'sg' => 2299161.0 } end it { is_expected.to eq(expected) } end describe '.from_zenaton' do subject { described_class.from_zenaton(props) } let(:props) do { 'y' => 2018, 'm' => 8, 'd' => 1, 'sg' => 2299161.0 } end it { is_expected.to eq(described_class.new(2018, 8, 1)) } end describe 'json serialization' do let(:object) { described_class.new(2018, 8, 1) } let(:props) { object.to_zenaton } let(:json) { props.to_json } let(:decoded_props) { JSON.parse(json) } let(:new_object) { described_class.from_zenaton(decoded_props) } it 'is bijective' do expect(new_object).to eq(object) end end end
20.38
68
0.580962
79b54faa0bcb300215ca5770154d932dc3efaf5d
62
module Minitest module Tagz VERSION = "1.7.0" end end
10.333333
21
0.645161
1a3c980e7646a78cbb69ed8a1e24a713411e2eb3
128
# frozen_string_literal: true class RatingRequestIssue < RequestIssue # :nocov: def rating? true end # :nocov: end
12.8
39
0.695313
7933449619392b6a658eb4ed3dc8a1615371cb4b
6,322
# # Required `:let` examples: # # let(:tooltippable_component_selectors) { [["[data-describe='tooltip-icon']", etc] } # # let(:nested_toggle) { false } # shared_examples_for 'tooltippable components that activate a tooltip' do # it 'activates tooltips on tooltippable component' do # tooltippable_component_selectors.each do |selector| # maybe_open_dropdown_menu(maybe_open_dropdown: dropdown, dropdown_data_describe: dropdown_data_describe, nested_toggle: nested_toggle) # confirm_tooltip_presence(selector: selector) # end # end # end # RSpec.describe 'Activating a tooltip on all tooltippable components', type: :feature, js: true do # let(:tooltip_text) { ComponentAttributeDefaultsHelper::feature_spec_tooltip_text } # let(:typeface_component_css_selectors) { # ["h6[data-toggle='tooltip'][data-describe='tooltip-typeface-title']", # "h5[data-toggle='tooltip'][data-describe='tooltip-typeface-heading']", # "h6[data-toggle='tooltip'][data-describe='tooltip-typeface-subheading']", # "p.font-size-sm[data-toggle='tooltip'][data-describe='tooltip-typeface-caption']", # "p[data-toggle='tooltip'][data-describe='tooltip-typeface-body']"] } # let(:tested_additional_component_css_classes) { ['.fa', "h6[data-toggle='tooltip']"] } # let(:additional_component_css_classes) { [*typeface_component_css_selectors, *tested_additional_component_css_classes] } # before { visit tooltip_feature_spec_views_path } # # Do what we can to ensure we're not missing some # # new tooltippable components along the way. # it_behaves_like 'a page that contains all of the utility enhanced components', tested_method: :tooltip, component_suite: :nfg # describe 'activating the tooltip' do # let(:describe) { nil } # let(:element) { '' } # let(:dropdown_data_describe) { '' } # let(:nested_toggle) { false } # let(:dropdown) { false } # before { scroll_to_element("[data-describe=\'#{dropdown_data_describe}\']") if dropdown } # describe 'activating tooltips on typeface components' do # let(:tooltippable_component_selectors) { typeface_component_css_selectors } # it_behaves_like 'tooltippable components that activate a tooltip' # end # describe 'tooltips on badges' do # let(:tooltippable_component_selectors) { ["[data-describe='tooltip-badge']", "[data-describe='tooltip-badge-with-link']", "[data-describe='tooltip-badge-pill']", "[data-describe='tooltip-badge-pill-with-link']"] } # it_behaves_like 'tooltippable components that activate a tooltip' # end # describe 'tooltips on icons' do # let(:tooltippable_component_selectors) { ["[data-describe='tooltip-icon']", "[data-describe='tooltip-icon-with-text']"] } # it_behaves_like 'tooltippable components that activate a tooltip' # end # describe 'tooltips on buttons' do # let(:tooltippable_component_selectors) { ["[data-describe='tooltip-button']", # "[data-describe='tooltip-button-link']", # "[data-describe='tooltip-button-with-nil-modal']", # "[data-describe='disabled-button-wrapper'] [data-toggle='tooltip']"] } # it_behaves_like 'tooltippable components that activate a tooltip' # end # describe 'tooltips on dropdown items' do # let(:dropdown) { true } # let(:dropdown_data_describe) { 'dropdown-menu' } # let(:tooltippable_component_selectors) { ["[data-describe='tooltip-dropdown-item']", # "[data-describe='tooltip-dropdown-item-with-nil-modal']", # "[data-describe='disabled-dropdown-item-wrapper'] [data-toggle='tooltip']"] } # it_behaves_like 'tooltippable components that activate a tooltip' # end # describe 'tooltips on nav items' do # let(:tooltippable_component_selectors) { ["[data-describe='tooltip-nav-item']", # "[data-describe='tooltip-active-nav-item']", # "[data-describe='tooltip-nav-item-with-nil-modal']" # # "[data-describe='disabled-nav-item-wrapper'] [data-toggle='tooltip']" # ] } # it_behaves_like 'tooltippable components that activate a tooltip' # pending "[data-describe='disabled-nav-item-wrapper'] [data-toggle='tooltip'] does not yet work" # end # describe 'tooltips on slact actions' do # let(:tooltippable_component_selectors) { ["[data-describe='tooltip-slat-action']","[data-describe='tooltip-slat-action-with-href']","[data-describe='modal-slat-action-with-tooltip']","[data-describe='disabled-slat-action-wrapper'] [data-toggle='tooltip']" ] } # it 'activates tooltips on tooltippable slat action items' do # tooltippable_component_selectors.each do |selector| # page.find("[data-describe='slat-actions-menu'] .dropdown-toggle").click # sleep 0.25 # confirm_tooltip_presence(selector: selector) # page.find("body").click # end # end # end # describe 'tooltips on steps' do # let(:tooltippable_component_selectors) { [ "[data-describe='tooltip-step-visited']", # "[data-describe='tooltip-step-active']" # # "[data-toggle='disabled-tooltip-step-wrapper'] [data-toggle='tooltip']" # ] } # it_behaves_like 'tooltippable components that activate a tooltip' # pending "[data-toggle='disabled-tooltip-step-wrapper'] [data-toggle='tooltip'] doesn't work yet." # end # describe 'tooltips on progress' do # let(:tooltippable_component_selectors) { ["[data-describe='tooltip-progress']"] } # it_behaves_like 'tooltippable components that activate a tooltip' # end # end # end # private # def wait_for_tooltip # sleep 0.5 # end # def confirm_tooltip_presence(selector:) # page.find(selector).hover # wait_for_tooltip # expect(page).to have_css tooltip_id(selector: selector) # end
50.576
267
0.636033
bff5b1f63acc813154464ca1a480f4d5ac6bd775
643
class Plugins::CamaleonMandrill::AdminController < CamaleonCms::Apps::PluginsAdminController def settings @mandrill = current_site.get_meta('mandrill_config') end def save_settings current_site.set_meta('mandrill_config', { smtp_username: params[:mandrill][:smtp_username], smtp_password: params[:mandrill][:smtp_password], default_from: params[:mandrill][:default_from], }) flash[:notice] = "#{t('plugin.mandrill.messages.settings_saved')}" redirect_to action: :settings end end
33.842105
92
0.598756
7a21a8950a24a243121d8e2706cf4f57a0129fde
2,199
module Editframe class VideoClip attr_reader :layers def initialize(source, options = {}) @id = Util.uuid @form = {} @filters = [] @layers = [] @options = options || { } @resolution = { width: nil, height: nil } @trim = { start: 0, end: nil } @volume = 1.0 configure_source source end def filter(name, options = {}) @filters.push({ :name => name, :options => { **options } }) self end def resize(resolution) return unless !resolution.nil? set_resolution resolution self end def set_resolution(resolution) return unless !resolution.nil? values = resolution.split('x') @resolution = { width: values[0].to_i, height: values[1].to_i } self end def set_volume(volume) @volume = volume.to_f if volume > 1 then @volume = 1.0 end if volume < 1 then @volume = 0.0 end self end def trim(trim_start, trim_end) @trim[:start] = trim_start @trim[:end] = trim_end if @trim[:start] < 0 @trim[:start] = 0 end if @trim[:end] < 0 @trim.delete(:end) end self end def mute set_volume 0 self end def encode @form[:config] = Faraday::ParamPart.new(generate_config, 'application/json') Editframe::Video.encode_from_clip(@form) end private def configure_source(source) case source when String @form["url#{@id}"] = source when File @form["file#{@id}"] = Faraday::FilePart.new source, 'application/octet-stream' end @source = source end private def generate_config clip = { :id => @id, :filters => @filters, :volume => @volume } options = @options if !@trim[:end].nil? clip[:trim] = @trim end if (!@resolution[:width].nil?) and (!@resolution[:height].nil?) clip[:resolution] = @resolution end options.stringify_keys! options.deep_transform_keys! { |key| key.camelize :lower } { **options, :layers => @layers, :clip => clip }.to_json end end end
24.433333
86
0.55116
e9843c875e92f7f3b0bbb131efa5fb279a0408bd
2,428
module KMP3D module HTMLHelpers def tag(name, attributes={}) content = "#{yield}</#{name}>" if block_given? return "<#{name}#{attributes_to_html(attributes)}>#{content}" end def sidenav(index, callback_method, options=[]) tag(:div, :class => "sidenav") do sidenav_children(index, callback_method, options).join("") end end def select(selected_id, attributes={}, options=[]) tag(:select, attributes) do select_children(selected_id, options).join("") end end def checkbox(label, attributes={}, checked=false) attributes[:type] = "checkbox" attributes[:checked] = "true" if checked tag(:label) { tag(:input, attributes) + label } end def br "<br/>" end def callback(name="", args="") "window.location='skp:#{name}@#{args}';" end def on_scroll(id) "window.location='skp:#{id}Scroll@'" \ "+document.getElementById('#{id}').scrollTop;" end def scroll_onload "document.getElementById('types').scrollTop=#{@scroll_types};" \ "document.getElementById('table').scrollTop=#{@scroll_table};" end def toggle_select(row_id, selected) "var element = document.getElementById('row#{row_id}');" \ "if(#{selected}) { element.className = 'selected'; }" \ "else { element.className = ''; }" end def puts_js(js) "window.location='skp:puts@'+#{js};" end def append_row_html(row) "var table = document.getElementById('table');" \ "var index = table.innerHTML.lastIndexOf('</tr>') + 5;" \ "var start = table.innerHTML.slice(0, index);" \ "var end = table.innerHTML.slice(index);" \ "table.innerHTML = start + #{row.inspect} + end;" end private def sidenav_children(index, callback_method, options) i = 0 options.map do |option| opts = {:onmousedown => callback(callback_method, i)} opts[:class] = "selected" if i == index i += 1 tag(:button, opts) { option } end end def select_children(selected_id, options) i = 0 options.map do |option| opts = {:value => i} opts[:selected] = "selected" if i == selected_id i += 1 tag(:option, opts) { option } end end def attributes_to_html(attributes) attributes.map { |k, v| " #{k}=#{v.inspect}" } * "" end end end
27.280899
70
0.58402
1c5160bf57e15d19a78a0405819a203b8e282d81
795
class SessionsController < ApplicationController def new end def create user = User.find_by(email: params[:session][:email].downcase) if user && user.authenticate(params[:session][:password]) # success if user.activated? log_in user params[:session][:remember_me] == '1' ? remember(user) : forget(user) #redirect_to user redirect_back_or user else message = "Account not activated. " message += "Check your email for the activation link." flash[:warning] = message redirect_to root_url end else # failure flash.now[:danger] = "Invalid email/password combination" render 'new' end end def destroy log_out if logged_in? redirect_to root_url end end
25.645161
77
0.630189
26f7af3a4da0c7e035c85f9af80a269ea46df4ce
372
module Moneta module Api module Responses # Ответ на запрос получения информации по операции. # Transaction information response. class GetOperationDetailsByIdResponse include Moneta::Api::DataMapper # @return [Moneta::Api::Types::OperationInfo] property :operation, type: Types::OperationInfo end end end end
23.25
57
0.682796
9145493cca4d41e22a7329a5a1ef7b0bbf2c81f1
3,848
=begin #Datadog API V2 Collection #Collection of all Datadog Public endpoints. The version of the OpenAPI document: 1.0 Contact: support@datadoghq.com Generated by: https://github.com/DataDog/datadog-api-client-ruby/tree/master/.generator Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2020-Present Datadog, Inc. =end require 'date' require 'time' module DatadogAPIClient::V2 # Global query options that are used during the query. # Note: Only supply timezone or time offset, not both. Otherwise, the query fails. class RUMQueryOptions include BaseGenericModel # Whether the object has unparsed attributes # @!visibility private attr_accessor :_unparsed # The time offset (in seconds) to apply to the query. attr_accessor :time_offset # The timezone can be specified both as an offset, for example: "UTC+03:00". attr_accessor :timezone # Attribute mapping from ruby-style variable name to JSON key. # @!visibility private def self.attribute_map { :'time_offset' => :'time_offset', :'timezone' => :'timezone' } end # Returns all the JSON keys this model knows about # @!visibility private def self.acceptable_attributes attribute_map.values end # Attribute type mapping. # @!visibility private def self.openapi_types { :'time_offset' => :'Integer', :'timezone' => :'String' } end # List of attributes with nullable: true # @!visibility private def self.openapi_nullable Set.new([ ]) end # Initializes the object # @param attributes [Hash] Model attributes in the form of hash # @!visibility private def initialize(attributes = {}) if (!attributes.is_a?(Hash)) fail ArgumentError, "The input argument (attributes) must be a hash in `DatadogAPIClient::V2::RUMQueryOptions` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `DatadogAPIClient::V2::RUMQueryOptions`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect end h[k.to_sym] = v } if attributes.key?(:'time_offset') self.time_offset = attributes[:'time_offset'] end if attributes.key?(:'timezone') self.timezone = attributes[:'timezone'] else self.timezone = 'UTC' end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons # @!visibility private def list_invalid_properties invalid_properties = Array.new invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid # @!visibility private def valid? true end # Checks equality by comparing each attribute. # @param o [Object] Object to be compared # @!visibility private def ==(o) return true if self.equal?(o) self.class == o.class && time_offset == o.time_offset && timezone == o.timezone end # @see the `==` method # @param o [Object] Object to be compared # @!visibility private def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Integer] Hash code # @!visibility private def hash [time_offset, timezone].hash end end end
28.932331
215
0.663202
ed91cf00649a000a6cfb26e6d2cfe71e280528bb
823
cask "book-ends" do version "14.0.2" sha256 "ca8989518200773ba88facdd450f10f1f01436b4e3301279214d33176630f002" url "http://das-nas.myasustor.com/dapp-dmg/Bkends-#{version}.dmg" name "Bookends" desc "Reference management and bibliography software" homepage "https://www.sonnysoftware.com/" livecheck do url :homepage regex(/version\s*(\d+(?:\.\d+)+)/i) end depends_on macos: ">= :high_sierra" zap trash: [ "~/Library/Application Support/Bookends", "~/Library/Application Support/CrashReporter/Bookends_F55C8E1F-1E92-5D69-B336-4E6BBE2AB04C.plist", "~/Library/Cookies/com.sonnysoftware.bookends.binarycookies", "~/Library/Preferences/com.sonnysoftware.bookends.plist", "~/Library/Saved Application State/com.sonnysoftware.bookends.savedState", ] app "Bookends.app" end
30.481481
102
0.73147
f7276bb74aa36a8ba34d0fae6ce1f5ea90bb9965
178
json.extract! user, :id, :first_name, :last_name, :email, :biography, :purpose, :days, :active, :password_digest, :created_at, :updated_at json.url user_url(user, format: :json)
59.333333
138
0.735955
336e9a3e63551f35100604c2bb0fd22de0a392b8
3,743
require 'spec_helper' require 'fakefs/spec_helpers' module LicenseFinder describe GoVendor do include FakeFS::SpecHelpers let(:logger) { double(:logger, active: nil) } subject { GoVendor.new(options.merge(project_path: Pathname(project_path), logger: logger)) } before do allow(logger).to receive(:installed) allow(logger).to receive(:active) end context 'package manager' do before do FileUtils.mkdir_p File.join(fixture_path('all_pms'), 'vendor') end it_behaves_like "a PackageManager" it 'installed? should be true if go exists on the path' do allow(PackageManager).to receive(:command_exists?).with('go').and_return true expect(described_class.installed?).to eq(true) end it 'installed? should be false if go does not exists on the path' do allow(PackageManager).to receive(:command_exists?).with('go').and_return false expect(described_class.installed?).to eq(false) end end let(:project_path) { '/app' } let(:options) { {} } context 'when there are go files' do before do FileUtils.mkdir_p project_path FileUtils.touch File.join(project_path, 'main.go') FileUtils.mkdir_p File.join(project_path, 'vendor', 'github.com', 'foo', 'bar') end it 'detects the project as go vendor project' do expect(subject.active?).to be true end describe '#current_packages' do let(:go_deps) { ["github.com/foo/bar", true] } before do allow(subject).to receive(:capture).with(%q[go list -f '{{join .Deps "\n"}}' ./...]).and_return(go_deps) allow(subject).to receive(:capture).with(%q[git rev-list --max-count 1 HEAD]).and_return(["e0ff7ae205f\n", true]) end RSpec.shared_examples 'current_packages' do |parameter| it 'only returns the parent package' do packages = subject.current_packages expect(packages.count).to eq(1) expect(packages.first.name).to eq('github.com/foo/bar') end end include_examples 'current_packages' it 'uses the sha of the parent project as the dependency version' do packages = subject.current_packages expect(packages.first.version).to eq('vendored-e0ff7ae205f') end context 'when sub packages are being used' do let(:go_deps) { ["github.com/foo/bar\ngithub.com/foo/bar/baz", true] } include_examples 'current_packages' end context 'when only sub packages are being used' do let(:go_deps) { ["github.com/foo/bar/baz", true] } include_examples 'current_packages' end context 'when unvendored packages are being used' do let(:go_deps) { ["github.com/foo/bar\ntext/template/parse", true] } include_examples 'current_packages' end end end context 'when there are go files in subdirectories' do before do FileUtils.mkdir_p project_path FileUtils.mkdir_p File.join(project_path, 'vendor', 'github.com', 'foo', 'bar') FileUtils.touch File.join(project_path, 'vendor', 'github.com', 'foo', 'bar', 'main.go') end it 'detects the project as go vendor project' do expect(subject.active?).to be true end end context 'if no go files exist' do let(:project_path) { '/ruby_app' } before do FileUtils.mkdir_p File.join(project_path, 'vendor') end it 'should not mark the project active' do expect(subject.active?).to be false end end end end
30.185484
123
0.620091
ace2b7582699fd6d6daeb3898e60a903d27dcfc6
1,288
class Whitedb < Formula desc "Lightweight in-memory NoSQL database library" homepage "http://whitedb.org/" url "http://whitedb.org/whitedb-0.7.3.tar.gz" sha256 "10c4ccd754ed2d53dbdef9ec16c88c732aa73d923fc0ee114e7e3a78a812849d" bottle do cellar :any sha256 "9ec140c350c8233dcbd67def0607eb1cdb764fd3f14ac57ac3901eeeda554e0f" => :catalina sha256 "05673924ef2226616618002bcbcee6241db8f1ce34339ff38785fd4fe82cda43" => :mojave sha256 "3dc724386650bbbf608c4742d954c338e1927427e4c4f1a9c0d6255cc8deee5d" => :high_sierra sha256 "44639bc83668def2e81b68318dbdb5347f9262937ddb6cfdfd7303aae1ce05a6" => :sierra sha256 "c0f4e666e9cc755bbff0711a1494c9705928a34a565701147bae31793f505163" => :el_capitan sha256 "0fa38dca524c08f51fa724fb49df5a3ebdde46a3251b2a282d5343b36c4c249f" => :yosemite sha256 "ba756975f0dbdfa4259a5a4271414765644b0abe8c771d0c091238909f0968d2" => :mavericks end def install # https://github.com/priitj/whitedb/issues/15 ENV.append "CFLAGS", "-std=gnu89" system "./configure", "--prefix=#{prefix}" system "make" system "make", "install" end test do system "#{bin}/wgdb", "create", "512k" system "#{bin}/wgdb", "add", "42" system "#{bin}/wgdb", "select", "1" system "#{bin}/wgdb", "free" end end
37.882353
93
0.752329
03ff8c7ab514f31116df58ea51d0c552a235c970
1,626
# coding: utf-8 lib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "metanorma/iec/version" Gem::Specification.new do |spec| spec.name = "metanorma-iec" spec.version = Metanorma::Iec::VERSION spec.authors = ["Ribose Inc."] spec.email = ["open.source@ribose.com"] spec.summary = "metanorma-iec lets you write IEC standards "\ "in AsciiDoc." spec.description = <<~DESCRIPTION metanorma-iec lets you write IEC standards in AsciiDoc syntax. This gem is in active development. DESCRIPTION spec.homepage = "https://github.com/metanorma/metanorma-iec" spec.license = "BSD-2-Clause" spec.bindir = "bin" spec.require_paths = ["lib"] spec.files = `git ls-files`.split("\n") spec.test_files = `git ls-files -- {spec}/*`.split("\n") spec.required_ruby_version = Gem::Requirement.new(">= 2.5.0") spec.add_dependency "metanorma-iso", "~> 1.10.0" spec.add_dependency "ruby-jing" spec.add_development_dependency "byebug" spec.add_development_dependency "equivalent-xml", "~> 0.6" spec.add_development_dependency "guard", "~> 2.14" spec.add_development_dependency "guard-rspec", "~> 4.7" spec.add_development_dependency "iev", "~> 0.2.0" spec.add_development_dependency "rake", "~> 13.0" spec.add_development_dependency "rspec", "~> 3.6" spec.add_development_dependency "rubocop", "~> 1.5.2" spec.add_development_dependency "sassc", "2.4.0" spec.add_development_dependency "simplecov", "~> 0.15" spec.add_development_dependency "timecop", "~> 0.9" end
36.133333
69
0.678352
e8f98138488a3999945ef97f7f6f2565e898bc50
374
# frozen_string_literal: true module PageMeta class HashMetaTag < MetaTag def render return if content.empty? content.each_with_object([]) do |(attr, value), buffer| next if value.blank? attr = attr.to_s.tr("_", ":") buffer << helpers.tag(:meta, property: "#{base_name}:#{attr}", content: value) end.join end end end
22
86
0.617647
bbf43c6108ef54952c305e2ebdaada621b5a06da
14,532
require 'test_helper' class UploadsControllerTest < ActionDispatch::IntegrationTest context "The uploads controller" do setup do @user = create(:user) end context "image proxy action" do should "work" do url = "https://i.pximg.net/img-original/img/2017/11/21/17/06/44/65985331_p0.png" get_auth image_proxy_uploads_path, @user, params: { url: url } assert_response :success assert_equal("image/png", response.media_type) assert_equal(15_573, response.body.size) end end context "batch action" do context "for twitter galleries" do should "render" do skip "Twitter keys are not set" unless Danbooru.config.twitter_api_key get_auth batch_uploads_path, @user, params: {:url => "https://twitter.com/lvlln/status/567054278486151168"} assert_response :success end end context "for pixiv ugoira galleries" do should "render" do get_auth batch_uploads_path, @user, params: {:url => "https://www.pixiv.net/member_illust.php?mode=medium&illust_id=59523577"} assert_response :success assert_no_match(/59523577_ugoira0\.jpg/, response.body) end end context "for a blank source" do should "render" do get_auth batch_uploads_path, @user assert_response :success end end end context "new action" do should "render" do get_auth new_upload_path, @user assert_response :success end should "render with an url" do get_auth new_upload_path(url: "https://cdn.donmai.us/original/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg"), @user assert_response :success end end context "index action" do should "render as an anonymous user" do create(:completed_source_upload, uploader: @user) get uploads_path assert_response :success end should "render as an uploader" do create(:completed_source_upload, uploader: @user) get_auth uploads_path, @user assert_response :success end should "render as an admin" do create(:completed_source_upload, uploader: @user) get_auth uploads_path, create(:admin_user) assert_response :success end context "for a search" do setup do CurrentUser.user = @user @upload = create(:completed_source_upload, uploader: @user, source: "http://example.com/foobar") end should respond_to_search({}).with { [@upload] } should respond_to_search(source: "http://example.com/foobar").with { @upload } should respond_to_search(status: "completed").with { @upload } end end context "show action" do should "not show uploads to other users" do upload = create(:completed_source_upload, uploader: @user) get_auth upload_path(upload), create(:user) assert_response 403 end should "render a completed source upload for the uploader" do upload = create(:completed_source_upload, uploader: @user) get_auth upload_path(upload), @user assert_response :success end should "render a completed file upload for the uploader" do upload = create(:completed_file_upload, uploader: @user) get_auth upload_path(upload), @user assert_response :success end should "render a failed upload" do upload = create(:upload, uploader: @user, status: "error: Not an image or video") get_auth upload_path(upload), @user assert_response :success end should "render a pending upload" do upload = create(:upload, uploader: @user, status: "pending", source: "https://www.google.com") get_auth upload_path(upload), @user assert_response :success end should "render a processing upload" do upload = create(:upload, uploader: @user, status: "processing") get_auth upload_path(upload), @user assert_response :success end should "redirect a completed upload to the original post if it's a duplicate of an existing post" do @upload = create(:completed_file_upload, uploader: @user) @post = create(:post, md5: @upload.media_assets.first.md5, media_asset: @upload.media_assets.first) get_auth upload_path(@upload), @user assert_redirected_to @post end should "prefill the upload form with the URL parameters" do upload = create(:completed_source_upload, uploader: @user) get_auth upload_path(upload, post: { rating: "s" }), @user assert_response :success assert_select "#post_rating_s[checked]" end end context "create action" do should "fail if not given a file or a source" do assert_no_difference("Upload.count") do post_auth uploads_path(format: :json), @user assert_response 422 assert_equal(["No file or source given"], response.parsed_body.dig("errors", "base")) end end should "fail if given both a file and source" do assert_no_difference("Upload.count") do file = File.open("test/files/test.jpg") source = "https://files.catbox.moe/om3tcw.webm" post_auth uploads_path(format: :json), @user, params: { upload: { file: file, source: source }} end assert_response 422 assert_equal(["Can't give both a file and a source"], response.parsed_body.dig("errors", "base")) end should "fail if given an unsupported filetype" do file = Rack::Test::UploadedFile.new("test/files/ugoira.json") post_auth uploads_path(format: :json), @user, params: { upload: { file: file }} assert_response 201 assert_match("Not an image or video", Upload.last.status) end should "fail if the file size is too large" do skip "flaky test" Danbooru.config.stubs(:max_file_size).returns(1.kilobyte) file = Rack::Test::UploadedFile.new("test/files/test.jpg") post_auth uploads_path(format: :json), @user, params: { upload: { file: file }} perform_enqueued_jobs assert_response 201 assert_match("File size must be less than or equal to", Upload.last.status) Danbooru.config.unstub(:max_file_size) end context "for a corrupted image" do should "fail for a corrupted jpeg" do create_upload!("test/files/test-corrupt.jpg", user: @user) assert_match("corrupt", Upload.last.status) end should "fail for a corrupted gif" do create_upload!("test/files/test-corrupt.gif", user: @user) assert_match("corrupt", Upload.last.status) end # https://schaik.com/pngsuite/pngsuite_xxx_png.html should "fail for a corrupted png" do create_upload!("test/files/test-corrupt.png", user: @user) assert_match("corrupt", Upload.last.status) end end context "for a video longer than the video length limit" do should "fail for a regular user" do @source = "https://cdn.donmai.us/original/63/cb/63cb09f2526ef3ac14f11c011516ad9b.webm" post_auth uploads_path(format: :json), @user, params: { upload: { source: @source }} perform_enqueued_jobs assert_response 201 assert_match("Duration must be less than", Upload.last.status) end end # XXX fixme context "for a video longer than the video length limit" do should_eventually "work for an admin" do @source = "https://cdn.donmai.us/original/63/cb/63cb09f2526ef3ac14f11c011516ad9b.webm" post_auth uploads_path(format: :json), create(:admin_user), params: { upload: { source: @source }} perform_enqueued_jobs assert_response 201 assert_equal("completed", Upload.last.status) end end context "when re-uploading a media asset stuck in the 'processing' state" do should "mark the asset as failed" do asset = create(:media_asset, file: File.open("test/files/test.jpg"), status: "processing") file = Rack::Test::UploadedFile.new("test/files/test.jpg") post_auth uploads_path, @user, params: { upload: { file: file }} upload = Upload.last assert_redirected_to upload assert_match("Upload failed, try again", upload.reload.status) assert_equal("failed", asset.reload.status) end end should "work for a source URL containing unicode characters" do source1 = "https://cdn.donmai.us/original/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg?one=東方&two=a%20b" source2 = "https://cdn.donmai.us/original/d3/4e/d34e4cf0a437a5d65f8e82b7bcd02606.jpg?one=%E6%9D%B1%E6%96%B9&two=a%20b" upload = assert_successful_upload(source1, user: @user) assert_equal(source2, upload.source) end context "uploading a file from your computer" do should_upload_successfully("test/files/test.jpg") should_upload_successfully("test/files/test.png") should_upload_successfully("test/files/test-static-32x32.gif") should_upload_successfully("test/files/test-animated-86x52.gif") should_upload_successfully("test/files/test-300x300.mp4") should_upload_successfully("test/files/test-512x512.webm") # should_upload_successfully("test/files/compressed.swf") end context "uploading a file from a source" do should_upload_successfully("https://www.artstation.com/artwork/04XA4") should_upload_successfully("https://dantewontdie.artstation.com/projects/YZK5q") should_upload_successfully("https://cdna.artstation.com/p/assets/images/images/006/029/978/large/amama-l-z.jpg") should_upload_successfully("https://www.deviantart.com/aeror404/art/Holiday-Elincia-424551484") should_upload_successfully("https://noizave.deviantart.com/art/test-no-download-697415967") should_upload_successfully("https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/intermediary/f/8b472d70-a0d6-41b5-9a66-c35687090acc/d23jbr4-8a06af02-70cb-46da-8a96-42a6ba73cdb4.jpg/v1/fill/w_786,h_1017,q_70,strp/silverhawks_quicksilver_by_edsfox_d23jbr4-pre.jpg") should_upload_successfully("https://www.hentai-foundry.com/pictures/user/Afrobull/795025/kuroeda") should_upload_successfully("https://pictures.hentai-foundry.com/a/Afrobull/795025/Afrobull-795025-kuroeda.png") should_upload_successfully("https://yande.re/post/show/482880") should_upload_successfully("https://files.yande.re/image/7ecfdead705d7b956b26b1d37b98d089/yande.re%20482880.jpg") should_upload_successfully("https://konachan.com/post/show/270916") should_upload_successfully("https://konachan.com/image/ca12cdb79a66d242e95a6f958341bf05/Konachan.com%20-%20270916.png") should_upload_successfully("http://lohas.nicoseiga.jp/o/910aecf08e542285862954017f8a33a8c32a8aec/1433298801/4937663") should_upload_successfully("http://seiga.nicovideo.jp/seiga/im4937663") should_upload_successfully("https://seiga.nicovideo.jp/image/source/9146749") should_upload_successfully("https://seiga.nicovideo.jp/watch/mg389884") should_upload_successfully("https://dic.nicovideo.jp/oekaki/52833.png") should_upload_successfully("https://lohas.nicoseiga.jp/o/971eb8af9bbcde5c2e51d5ef3a2f62d6d9ff5552/1589933964/3583893") should_upload_successfully("http://lohas.nicoseiga.jp/priv/3521156?e=1382558156&h=f2e089256abd1d453a455ec8f317a6c703e2cedf") should_upload_successfully("http://lohas.nicoseiga.jp/priv/b80f86c0d8591b217e7513a9e175e94e00f3c7a1/1384936074/3583893") should_upload_successfully("http://lohas.nicoseiga.jp/material/5746c5/4459092") # XXX should_upload_successfully("https://dcdn.cdn.nimg.jp/priv/62a56a7f67d3d3746ae5712db9cac7d465f4a339/1592186183/10466669") # XXX should_upload_successfully("https://dcdn.cdn.nimg.jp/nicoseiga/lohas/o/8ba0a9b2ea34e1ef3b5cc50785bd10cd63ec7e4a/1592187477/10466669") should_upload_successfully("http://nijie.info/view.php?id=213043") should_upload_successfully("https://nijie.info/view_popup.php?id=213043") should_upload_successfully("https://pic.nijie.net/03/nijie_picture/728995_20170505014820_0.jpg") should_upload_successfully("https://pawoo.net/web/statuses/1202176") if Danbooru.config.pawoo_client_id.present? # XXX should_upload_successfully("https://img.pawoo.net/media_attachments/files/000/128/953/original/4c0a06087b03343f.png") if Danbooru.config.pawoo_client_id.present? # XXX should_upload_successfully("https://www.pixiv.net/en/artworks/64476642") should_upload_successfully("https://www.pixiv.net/member_illust.php?mode=medium&illust_id=62247364") should_upload_successfully("https://i.pximg.net/img-original/img/2017/08/18/00/09/21/64476642_p0.jpg") should_upload_successfully("https://noizave.tumblr.com/post/162206271767") should_upload_successfully("https://media.tumblr.com/3bbfcbf075ddf969c996641b264086fd/tumblr_os2buiIOt51wsfqepo1_1280.png") should_upload_successfully("https://twitter.com/noizave/status/875768175136317440") should_upload_successfully("https://pbs.twimg.com/media/DCdZ_FhUIAAYKFN?format=jpg&name=medium") should_upload_successfully("https://pbs.twimg.com/profile_banners/2371694594/1581832507/1500x500") should_upload_successfully("https://twitter.com/zeth_total/status/1355597580814585856") # XXX should_upload_successfully("https://video.twimg.com/tweet_video/EWHWVrmVcAAp4Vw.mp4") should_upload_successfully("https://www.weibo.com/5501756072/J2UNKfbqV") should_upload_successfully("https://wx1.sinaimg.cn/mw690/0060kO5aly1gezsyt5xvhj30ok0sgtc9.jpg") should_upload_successfully("https://art.ngfiles.com/images/1254000/1254722_natthelich_pandora.jpg") should_upload_successfully("https://art.ngfiles.com/comments/57000/iu_57615_7115981.jpg") should_upload_successfully("https://www.newgrounds.com/art/view/puddbytes/costanza-at-bat") should_upload_successfully("https://kmyama.fanbox.cc/posts/104708") should_upload_successfully("https://downloads.fanbox.cc/images/post/104708/wsF73EC5Fq0CIK84W0LGYk2p.jpeg") end end end end
44.036364
275
0.694536
1d24dd319e7633853d433446e46ee696c655e9a8
139
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_contraq_session'
34.75
77
0.805755
4a21858d4135dbd13bcd219c35e4493f2245ab35
148
require 'test_helper' class Api::V1::SourcesControllerTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end end
18.5
70
0.72973
21b900746f8492a8941eeeabf53e30f71704d8e6
173
Rails.application.config.content_security_policy do |policy| policy.connect_src :self, :https, 'http://localhost:3035', 'ws://localhost:3035' if Rails.env.development? end
57.666667
108
0.780347
799a82d760a582dd4ef23bfa84f91e8b940aa048
253
module FidorApi class Collection module KaminariSupport def last_page? current_page == total_pages end def next_page current_page + 1 end def limit_value per_page end end end end
14.055556
35
0.592885
7a15e88cea5594029eb07675ec5ef9c46b636563
168
# frozen_string_literal: true module Webhooks class ConfiguredWebhookAction include Dry::Transaction def call(params) Success(true) end end end
14
31
0.720238
01a3943aff52045532ee98fadce863835f264a5c
1,021
require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) require "sanitycheck" module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end
37.814815
99
0.731636
7ab9806c248f6db36127d0c64642aca47871c0d5
791
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :omniauthable, :omniauth_providers => [:google_oauth2] has_many :pacientes, dependent: :destroy def self.from_omniauth(auth) # Either create a User record or update it based on the provider (Google) and the UID where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.token = auth.credentials.token user.expires = auth.credentials.expires user.expires_at = auth.credentials.expires_at user.refresh_token = auth.credentials.refresh_token end end end
39.55
92
0.730721
b9d8c15c2ba41dfe87e47849239da79f2b69e4fa
1,440
require 'git_utils' require 'r10k_utils' require 'master_manipulator' test_name 'CODEMGMT-84 - C59271 - Attempt to Deploy with Invalid r10k Config' #Init env_path = on(master, puppet('config print environmentpath')).stdout.rstrip git_repo_path = '/git_repos' git_control_remote = File.join(git_repo_path, 'environments.git') git_provider = ENV['GIT_PROVIDER'] || 'shellgit' r10k_fqp = get_r10k_fqp(master) r10k_config_path = get_r10k_config_file_path(master) r10k_config_bak_path = "#{r10k_config_path}.bak" #In-line files r10k_conf = <<-CONF cachedir: '/var/cache/r10k' git: provider: '#{git_provider}' sources: broken: dir: "#{env_path}" remote: "#{git_control_remote}" CONF #Verification if get_puppet_version(master) < 4.0 error_message_regex = /ERROR.*can\'t\ convert\ nil\ into\ String/ else error_message_regex = /ERROR.* -> no implicit conversion of nil into String/ end #Teardown teardown do step 'Restore Original "r10k" Config' on(master, "mv #{r10k_config_bak_path} #{r10k_config_path}") end #Setup step 'Backup a Valid "r10k" Config' on(master, "mv #{r10k_config_path} #{r10k_config_bak_path}") step 'Update the "r10k" Config' create_remote_file(master, r10k_config_path, r10k_conf) #Tests step 'Attempt to Deploy via r10k' on(master, "#{r10k_fqp} deploy environment -v", :acceptable_exit_codes => 1) do |result| assert_match(error_message_regex, result.stderr, 'Expected message not found!') end
27.692308
88
0.755556
1a422449fd5d22f5a0d7a93bb56d946167971ead
1,043
# frozen_string_literal: true require 'test_helper' class OrgThrityDayActivityDecoratorTest < ActiveSupport::TestCase describe 'project_count_text' do it 'should return "S" for small orgs' do ota = create(:org_thirty_day_activity).decorate stub_orgs_projects_count(10) ota.project_count_text.must_equal 'S' end it 'should return "M" for medium orgs' do ota = create(:org_thirty_day_activity).decorate stub_orgs_projects_count(20) ota.project_count_text.must_equal 'M' end it 'should return "L" for large orgs' do ota = create(:org_thirty_day_activity).decorate stub_orgs_projects_count(55) ota.project_count_text.must_equal 'L' end it 'should return "N/A" with no projects' do ota = create(:org_thirty_day_activity).decorate stub_orgs_projects_count ota.project_count_text.must_equal 'N/A' end end private def stub_orgs_projects_count(count = 0) Organization.any_instance.stubs(:projects_count).returns(count) end end
27.447368
67
0.725791
21a7920dcc7cb91961904332de5974ca086e2302
147
require File.expand_path('../../../spec_helper', __FILE__) describe "FileTest.grpowned?" do it "needs to be reviewed for spec completeness" end
24.5
58
0.734694
28ddff1ca8816dfbce64c50f77da5a8655fa95fe
12,379
module Cryptopals module CtrSubstitutions include AES include Xor SAMPLES = %w[ SSBoYXZlIG1ldCB0aGVtIGF0IGNsb3NlIG9mIGRheQ== Q29taW5nIHdpdGggdml2aWQgZmFjZXM= RnJvbSBjb3VudGVyIG9yIGRlc2sgYW1vbmcgZ3JleQ== RWlnaHRlZW50aC1jZW50dXJ5IGhvdXNlcy4= SSBoYXZlIHBhc3NlZCB3aXRoIGEgbm9kIG9mIHRoZSBoZWFk T3IgcG9saXRlIG1lYW5pbmdsZXNzIHdvcmRzLA== T3IgaGF2ZSBsaW5nZXJlZCBhd2hpbGUgYW5kIHNhaWQ= UG9saXRlIG1lYW5pbmdsZXNzIHdvcmRzLA== QW5kIHRob3VnaHQgYmVmb3JlIEkgaGFkIGRvbmU= T2YgYSBtb2NraW5nIHRhbGUgb3IgYSBnaWJl VG8gcGxlYXNlIGEgY29tcGFuaW9u QXJvdW5kIHRoZSBmaXJlIGF0IHRoZSBjbHViLA== QmVpbmcgY2VydGFpbiB0aGF0IHRoZXkgYW5kIEk= QnV0IGxpdmVkIHdoZXJlIG1vdGxleSBpcyB3b3JuOg== QWxsIGNoYW5nZWQsIGNoYW5nZWQgdXR0ZXJseTo= QSB0ZXJyaWJsZSBiZWF1dHkgaXMgYm9ybi4= VGhhdCB3b21hbidzIGRheXMgd2VyZSBzcGVudA== SW4gaWdub3JhbnQgZ29vZCB3aWxsLA== SGVyIG5pZ2h0cyBpbiBhcmd1bWVudA== VW50aWwgaGVyIHZvaWNlIGdyZXcgc2hyaWxsLg== V2hhdCB2b2ljZSBtb3JlIHN3ZWV0IHRoYW4gaGVycw== V2hlbiB5b3VuZyBhbmQgYmVhdXRpZnVsLA== U2hlIHJvZGUgdG8gaGFycmllcnM/ VGhpcyBtYW4gaGFkIGtlcHQgYSBzY2hvb2w= QW5kIHJvZGUgb3VyIHdpbmdlZCBob3JzZS4= VGhpcyBvdGhlciBoaXMgaGVscGVyIGFuZCBmcmllbmQ= V2FzIGNvbWluZyBpbnRvIGhpcyBmb3JjZTs= SGUgbWlnaHQgaGF2ZSB3b24gZmFtZSBpbiB0aGUgZW5kLA== U28gc2Vuc2l0aXZlIGhpcyBuYXR1cmUgc2VlbWVkLA== U28gZGFyaW5nIGFuZCBzd2VldCBoaXMgdGhvdWdodC4= VGhpcyBvdGhlciBtYW4gSSBoYWQgZHJlYW1lZA== QSBkcnVua2VuLCB2YWluLWdsb3Jpb3VzIGxvdXQu SGUgaGFkIGRvbmUgbW9zdCBiaXR0ZXIgd3Jvbmc= VG8gc29tZSB3aG8gYXJlIG5lYXIgbXkgaGVhcnQs WWV0IEkgbnVtYmVyIGhpbSBpbiB0aGUgc29uZzs= SGUsIHRvbywgaGFzIHJlc2lnbmVkIGhpcyBwYXJ0 SW4gdGhlIGNhc3VhbCBjb21lZHk7 SGUsIHRvbywgaGFzIGJlZW4gY2hhbmdlZCBpbiBoaXMgdHVybiw= VHJhbnNmb3JtZWQgdXR0ZXJseTo= QSB0ZXJyaWJsZSBiZWF1dHkgaXMgYm9ybi4= ] SAMPLES2 = %w[ SSdtIHJhdGVkICJSIi4uLnRoaXMgaXMgYSB3YXJuaW5nLCB5YSBiZXR0ZXIgdm9pZCAvIFBvZXRzIGFyZSBwYXJhbm9pZCwgREoncyBELXN0cm95ZWQ= Q3V6IEkgY2FtZSBiYWNrIHRvIGF0dGFjayBvdGhlcnMgaW4gc3BpdGUtIC8gU3RyaWtlIGxpa2UgbGlnaHRuaW4nLCBJdCdzIHF1aXRlIGZyaWdodGVuaW4nIQ== QnV0IGRvbid0IGJlIGFmcmFpZCBpbiB0aGUgZGFyaywgaW4gYSBwYXJrIC8gTm90IGEgc2NyZWFtIG9yIGEgY3J5LCBvciBhIGJhcmssIG1vcmUgbGlrZSBhIHNwYXJrOw== WWEgdHJlbWJsZSBsaWtlIGEgYWxjb2hvbGljLCBtdXNjbGVzIHRpZ2h0ZW4gdXAgLyBXaGF0J3MgdGhhdCwgbGlnaHRlbiB1cCEgWW91IHNlZSBhIHNpZ2h0IGJ1dA== U3VkZGVubHkgeW91IGZlZWwgbGlrZSB5b3VyIGluIGEgaG9ycm9yIGZsaWNrIC8gWW91IGdyYWIgeW91ciBoZWFydCB0aGVuIHdpc2ggZm9yIHRvbW9ycm93IHF1aWNrIQ== TXVzaWMncyB0aGUgY2x1ZSwgd2hlbiBJIGNvbWUgeW91ciB3YXJuZWQgLyBBcG9jYWx5cHNlIE5vdywgd2hlbiBJJ20gZG9uZSwgeWEgZ29uZSE= SGF2ZW4ndCB5b3UgZXZlciBoZWFyZCBvZiBhIE1DLW11cmRlcmVyPyAvIFRoaXMgaXMgdGhlIGRlYXRoIHBlbmFsdHksYW5kIEknbSBzZXJ2aW4nIGE= RGVhdGggd2lzaCwgc28gY29tZSBvbiwgc3RlcCB0byB0aGlzIC8gSHlzdGVyaWNhbCBpZGVhIGZvciBhIGx5cmljYWwgcHJvZmVzc2lvbmlzdCE= RnJpZGF5IHRoZSB0aGlydGVlbnRoLCB3YWxraW5nIGRvd24gRWxtIFN0cmVldCAvIFlvdSBjb21lIGluIG15IHJlYWxtIHlhIGdldCBiZWF0IQ== VGhpcyBpcyBvZmYgbGltaXRzLCBzbyB5b3VyIHZpc2lvbnMgYXJlIGJsdXJyeSAvIEFsbCB5YSBzZWUgaXMgdGhlIG1ldGVycyBhdCBhIHZvbHVtZQ== VGVycm9yIGluIHRoZSBzdHlsZXMsIG5ldmVyIGVycm9yLWZpbGVzIC8gSW5kZWVkIEknbSBrbm93bi15b3VyIGV4aWxlZCE= Rm9yIHRob3NlIHRoYXQgb3Bwb3NlIHRvIGJlIGxldmVsIG9yIG5leHQgdG8gdGhpcyAvIEkgYWluJ3QgYSBkZXZpbCBhbmQgdGhpcyBhaW4ndCB0aGUgRXhvcmNpc3Qh V29yc2UgdGhhbiBhIG5pZ2h0bWFyZSwgeW91IGRvbid0IGhhdmUgdG8gc2xlZXAgYSB3aW5rIC8gVGhlIHBhaW4ncyBhIG1pZ3JhaW5lIGV2ZXJ5IHRpbWUgeWEgdGhpbms= Rmxhc2hiYWNrcyBpbnRlcmZlcmUsIHlhIHN0YXJ0IHRvIGhlYXI6IC8gVGhlIFItQS1LLUktTSBpbiB5b3VyIGVhcjs= VGhlbiB0aGUgYmVhdCBpcyBoeXN0ZXJpY2FsIC8gVGhhdCBtYWtlcyBFcmljIGdvIGdldCBhIGF4IGFuZCBjaG9wcyB0aGUgd2Fjaw== U29vbiB0aGUgbHlyaWNhbCBmb3JtYXQgaXMgc3VwZXJpb3IgLyBGYWNlcyBvZiBkZWF0aCByZW1haW4= TUMncyBkZWNheWluZywgY3V6IHRoZXkgbmV2ZXIgc3RheWVkIC8gVGhlIHNjZW5lIG9mIGEgY3JpbWUgZXZlcnkgbmlnaHQgYXQgdGhlIHNob3c= VGhlIGZpZW5kIG9mIGEgcmh5bWUgb24gdGhlIG1pYyB0aGF0IHlvdSBrbm93IC8gSXQncyBvbmx5IG9uZSBjYXBhYmxlLCBicmVha3MtdGhlIHVuYnJlYWthYmxl TWVsb2RpZXMtdW5tYWthYmxlLCBwYXR0ZXJuLXVuZXNjYXBhYmxlIC8gQSBob3JuIGlmIHdhbnQgdGhlIHN0eWxlIEkgcG9zc2Vz SSBibGVzcyB0aGUgY2hpbGQsIHRoZSBlYXJ0aCwgdGhlIGdvZHMgYW5kIGJvbWIgdGhlIHJlc3QgLyBGb3IgdGhvc2UgdGhhdCBlbnZ5IGEgTUMgaXQgY2FuIGJl SGF6YXJkb3VzIHRvIHlvdXIgaGVhbHRoIHNvIGJlIGZyaWVuZGx5IC8gQSBtYXR0ZXIgb2YgbGlmZSBhbmQgZGVhdGgsIGp1c3QgbGlrZSBhIGV0Y2gtYS1za2V0Y2g= U2hha2UgJ3RpbGwgeW91ciBjbGVhciwgbWFrZSBpdCBkaXNhcHBlYXIsIG1ha2UgdGhlIG5leHQgLyBBZnRlciB0aGUgY2VyZW1vbnksIGxldCB0aGUgcmh5bWUgcmVzdCBpbiBwZWFjZQ== SWYgbm90LCBteSBzb3VsJ2xsIHJlbGVhc2UhIC8gVGhlIHNjZW5lIGlzIHJlY3JlYXRlZCwgcmVpbmNhcm5hdGVkLCB1cGRhdGVkLCBJJ20gZ2xhZCB5b3UgbWFkZSBpdA== Q3V6IHlvdXIgYWJvdXQgdG8gc2VlIGEgZGlzYXN0cm91cyBzaWdodCAvIEEgcGVyZm9ybWFuY2UgbmV2ZXIgYWdhaW4gcGVyZm9ybWVkIG9uIGEgbWljOg== THlyaWNzIG9mIGZ1cnkhIEEgZmVhcmlmaWVkIGZyZWVzdHlsZSEgLyBUaGUgIlIiIGlzIGluIHRoZSBob3VzZS10b28gbXVjaCB0ZW5zaW9uIQ== TWFrZSBzdXJlIHRoZSBzeXN0ZW0ncyBsb3VkIHdoZW4gSSBtZW50aW9uIC8gUGhyYXNlcyB0aGF0J3MgZmVhcnNvbWU= WW91IHdhbnQgdG8gaGVhciBzb21lIHNvdW5kcyB0aGF0IG5vdCBvbmx5IHBvdW5kcyBidXQgcGxlYXNlIHlvdXIgZWFyZHJ1bXM7IC8gSSBzaXQgYmFjayBhbmQgb2JzZXJ2ZSB0aGUgd2hvbGUgc2NlbmVyeQ== VGhlbiBub25jaGFsYW50bHkgdGVsbCB5b3Ugd2hhdCBpdCBtZWFuIHRvIG1lIC8gU3RyaWN0bHkgYnVzaW5lc3MgSSdtIHF1aWNrbHkgaW4gdGhpcyBtb29k QW5kIEkgZG9uJ3QgY2FyZSBpZiB0aGUgd2hvbGUgY3Jvd2QncyBhIHdpdG5lc3MhIC8gSSdtIGEgdGVhciB5b3UgYXBhcnQgYnV0IEknbSBhIHNwYXJlIHlvdSBhIGhlYXJ0 UHJvZ3JhbSBpbnRvIHRoZSBzcGVlZCBvZiB0aGUgcmh5bWUsIHByZXBhcmUgdG8gc3RhcnQgLyBSaHl0aG0ncyBvdXQgb2YgdGhlIHJhZGl1cywgaW5zYW5lIGFzIHRoZSBjcmF6aWVzdA== TXVzaWNhbCBtYWRuZXNzIE1DIGV2ZXIgbWFkZSwgc2VlIGl0J3MgLyBOb3cgYW4gZW1lcmdlbmN5LCBvcGVuLWhlYXJ0IHN1cmdlcnk= T3BlbiB5b3VyIG1pbmQsIHlvdSB3aWxsIGZpbmQgZXZlcnkgd29yZCdsbCBiZSAvIEZ1cmllciB0aGFuIGV2ZXIsIEkgcmVtYWluIHRoZSBmdXJ0dXJl QmF0dGxlJ3MgdGVtcHRpbmcuLi53aGF0ZXZlciBzdWl0cyB5YSEgLyBGb3Igd29yZHMgdGhlIHNlbnRlbmNlLCB0aGVyZSdzIG5vIHJlc2VtYmxhbmNl WW91IHRoaW5rIHlvdSdyZSBydWZmZXIsIHRoZW4gc3VmZmVyIHRoZSBjb25zZXF1ZW5jZXMhIC8gSSdtIG5ldmVyIGR5aW5nLXRlcnJpZnlpbmcgcmVzdWx0cw== SSB3YWtlIHlhIHdpdGggaHVuZHJlZHMgb2YgdGhvdXNhbmRzIG9mIHZvbHRzIC8gTWljLXRvLW1vdXRoIHJlc3VzY2l0YXRpb24sIHJoeXRobSB3aXRoIHJhZGlhdGlvbg== Tm92b2NhaW4gZWFzZSB0aGUgcGFpbiBpdCBtaWdodCBzYXZlIGhpbSAvIElmIG5vdCwgRXJpYyBCLidzIHRoZSBqdWRnZSwgdGhlIGNyb3dkJ3MgdGhlIGp1cnk= WW8gUmFraW0sIHdoYXQncyB1cD8gLyBZbywgSSdtIGRvaW5nIHRoZSBrbm93bGVkZ2UsIEUuLCBtYW4gSSdtIHRyeWluZyB0byBnZXQgcGFpZCBpbiBmdWxs V2VsbCwgY2hlY2sgdGhpcyBvdXQsIHNpbmNlIE5vcmJ5IFdhbHRlcnMgaXMgb3VyIGFnZW5jeSwgcmlnaHQ/IC8gVHJ1ZQ== S2FyYSBMZXdpcyBpcyBvdXIgYWdlbnQsIHdvcmQgdXAgLyBaYWtpYSBhbmQgNHRoIGFuZCBCcm9hZHdheSBpcyBvdXIgcmVjb3JkIGNvbXBhbnksIGluZGVlZA== T2theSwgc28gd2hvIHdlIHJvbGxpbicgd2l0aCB0aGVuPyBXZSByb2xsaW4nIHdpdGggUnVzaCAvIE9mIFJ1c2h0b3duIE1hbmFnZW1lbnQ= Q2hlY2sgdGhpcyBvdXQsIHNpbmNlIHdlIHRhbGtpbmcgb3ZlciAvIFRoaXMgZGVmIGJlYXQgcmlnaHQgaGVyZSB0aGF0IEkgcHV0IHRvZ2V0aGVy SSB3YW5uYSBoZWFyIHNvbWUgb2YgdGhlbSBkZWYgcmh5bWVzLCB5b3Uga25vdyB3aGF0IEknbSBzYXlpbic/IC8gQW5kIHRvZ2V0aGVyLCB3ZSBjYW4gZ2V0IHBhaWQgaW4gZnVsbA== VGhpbmtpbicgb2YgYSBtYXN0ZXIgcGxhbiAvICdDdXogYWluJ3QgbnV0aGluJyBidXQgc3dlYXQgaW5zaWRlIG15IGhhbmQ= U28gSSBkaWcgaW50byBteSBwb2NrZXQsIGFsbCBteSBtb25leSBpcyBzcGVudCAvIFNvIEkgZGlnIGRlZXBlciBidXQgc3RpbGwgY29taW4nIHVwIHdpdGggbGludA== U28gSSBzdGFydCBteSBtaXNzaW9uLCBsZWF2ZSBteSByZXNpZGVuY2UgLyBUaGlua2luJyBob3cgY291bGQgSSBnZXQgc29tZSBkZWFkIHByZXNpZGVudHM= SSBuZWVkIG1vbmV5LCBJIHVzZWQgdG8gYmUgYSBzdGljay11cCBraWQgLyBTbyBJIHRoaW5rIG9mIGFsbCB0aGUgZGV2aW91cyB0aGluZ3MgSSBkaWQ= SSB1c2VkIHRvIHJvbGwgdXAsIHRoaXMgaXMgYSBob2xkIHVwLCBhaW4ndCBudXRoaW4nIGZ1bm55IC8gU3RvcCBzbWlsaW5nLCBiZSBzdGlsbCwgZG9uJ3QgbnV0aGluJyBtb3ZlIGJ1dCB0aGUgbW9uZXk= QnV0IG5vdyBJIGxlYXJuZWQgdG8gZWFybiAnY3V6IEknbSByaWdodGVvdXMgLyBJIGZlZWwgZ3JlYXQsIHNvIG1heWJlIEkgbWlnaHQganVzdA== U2VhcmNoIGZvciBhIG5pbmUgdG8gZml2ZSwgaWYgSSBzdHJpdmUgLyBUaGVuIG1heWJlIEknbGwgc3RheSBhbGl2ZQ== U28gSSB3YWxrIHVwIHRoZSBzdHJlZXQgd2hpc3RsaW4nIHRoaXMgLyBGZWVsaW4nIG91dCBvZiBwbGFjZSAnY3V6LCBtYW4sIGRvIEkgbWlzcw== QSBwZW4gYW5kIGEgcGFwZXIsIGEgc3RlcmVvLCBhIHRhcGUgb2YgLyBNZSBhbmQgRXJpYyBCLCBhbmQgYSBuaWNlIGJpZyBwbGF0ZSBvZg== RmlzaCwgd2hpY2ggaXMgbXkgZmF2b3JpdGUgZGlzaCAvIEJ1dCB3aXRob3V0IG5vIG1vbmV5IGl0J3Mgc3RpbGwgYSB3aXNo J0N1eiBJIGRvbid0IGxpa2UgdG8gZHJlYW0gYWJvdXQgZ2V0dGluJyBwYWlkIC8gU28gSSBkaWcgaW50byB0aGUgYm9va3Mgb2YgdGhlIHJoeW1lcyB0aGF0IEkgbWFkZQ== U28gbm93IHRvIHRlc3QgdG8gc2VlIGlmIEkgZ290IHB1bGwgLyBIaXQgdGhlIHN0dWRpbywgJ2N1eiBJJ20gcGFpZCBpbiBmdWxs UmFraW0sIGNoZWNrIHRoaXMgb3V0LCB5byAvIFlvdSBnbyB0byB5b3VyIGdpcmwgaG91c2UgYW5kIEknbGwgZ28gdG8gbWluZQ== J0NhdXNlIG15IGdpcmwgaXMgZGVmaW5pdGVseSBtYWQgLyAnQ2F1c2UgaXQgdG9vayB1cyB0b28gbG9uZyB0byBkbyB0aGlzIGFsYnVt WW8sIEkgaGVhciB3aGF0IHlvdSdyZSBzYXlpbmcgLyBTbyBsZXQncyBqdXN0IHB1bXAgdGhlIG11c2ljIHVw QW5kIGNvdW50IG91ciBtb25leSAvIFlvLCB3ZWxsIGNoZWNrIHRoaXMgb3V0LCB5byBFbGk= VHVybiBkb3duIHRoZSBiYXNzIGRvd24gLyBBbmQgbGV0IHRoZSBiZWF0IGp1c3Qga2VlcCBvbiByb2NraW4n QW5kIHdlIG91dHRhIGhlcmUgLyBZbywgd2hhdCBoYXBwZW5lZCB0byBwZWFjZT8gLyBQZWFjZQ== ] EN_TRIGRAMS = %w[the and ing her hat his tha ere for ent ion ter was you ith ver all wit thi tio] def possible_bytes_at(bytes, alphabet, i) (0..255).select do |byte| r = bytes.map { |e| e[i] }.compact.map { |e| [e ^ byte].pack("c*") } r.all? { |e| alphabet.include?(e) } end end def possible_keystreams(cipherbytes, x1, x2, x3, x4) b1s = possible_bytes_at(cipherbytes, ALPHABET, x1) b2s = possible_bytes_at(cipherbytes, ALPHABET, x2) b3s = possible_bytes_at(cipherbytes, ALPHABET, x3) b4s = possible_bytes_at(cipherbytes, ALPHABET, x4) pks = [] b1s.each do |b1| b2s.each do |b2| b3s.each do |b3| b4s.each do |b4| pts = cipherbytes.select { |bytes| bytes.size >= x4 }.map { |bytes| xor(bytes.drop(x1).take(4), [b1, b2, b3, b4]).pack("c*") } count = pts.count { |s| EN_TRIGRAMS.count { |tri| s.downcase.include?(tri) } > 0 } pks << [count, [b1, b2, b3, b4]] if count > 0 end end end end pks end def statistical_attack key = random_bytes(16).pack("c*") ciphertexts = SAMPLES2.map { |s| aes_128_ctr(Base64.decode64(s), key) } size = ciphertexts.map(&:size).min cipherbytes = ciphertexts.map { |s| s.bytes.take(size) } key = probable_keys(cipherbytes.flatten, [size]).first decrypt(cipherbytes, key.bytes) end def encrypt key = random_bytes(16).pack("c*") ciphertexts = SAMPLES.map { |s| aes_128_ctr(Base64.decode64(s), key) } cipherbytes = ciphertexts.map(&:bytes) b1s = possible_bytes_at(cipherbytes, ("A".."Z").to_a, 0) b2s = possible_bytes_at(cipherbytes, ALPHABET, 1) b3s = possible_bytes_at(cipherbytes, ALPHABET, 2) b4s = possible_bytes_at(cipherbytes, ALPHABET, 3) b5s = possible_bytes_at(cipherbytes, ALPHABET, 4) b6s = possible_bytes_at(cipherbytes, ALPHABET, 5) pks = [] b1s.each do |b1| b2s.each do |b2| b3s.each do |b3| b4s.each do |b4| b5s.each do |b5| b6s.each do |b6| pts = cipherbytes.map { |bytes| xor(bytes.take(6), [b1, b2, b3, b4, b5, b6]).pack("c*") } count = pts.count { |s| EN_TRIGRAMS.count { |tri| s.downcase.include?(tri) } > 0 } pks << [count, [b1, b2, b3, b4, b5, b6]] if count > 13 end end end end end end keystream = pks.first.last bts = cipherbytes.select { |bytes| bytes.length > 22 } (6..(bts.map(&:size).max)).each_slice(4) do |x1, x2, x3, x4| c, keystream_bytes = possible_keystreams(bts, x1, x2, x3, x4).max { |x, y| x.first <=> y.first } keystream += keystream_bytes decrypt(bts, keystream) puts "="*100 end end def decrypt(cipherbytes, keystream_bytes) cipherbytes.map do |bytes| puts xor(bytes.take(keystream_bytes.size), keystream_bytes.take(bytes.size)).pack("c*").inspect end;0 end end end
62.837563
166
0.820179
f8a4509b15666e07893188e7deade822f35828b0
1,164
cask 'thunder' do version '3.3.9.4280' sha256 '197e6c77b36ca7647fd07eabc45acdf6d9a9161149ccde65a97d83e622902e0d' # down.sandai.net was verified as official when first introduced to the cask url "http://down.sandai.net/mac/thunder_#{version}.dmg" appcast 'https://static-xl9-ssl.xunlei.com/json/mac_download_url.json' name 'Thunder' name '迅雷' homepage 'https://mac.xunlei.com/' auto_updates true depends_on macos: '>= :yosemite' app 'Thunder.app' zap trash: [ '~/Library/Application Support/Thunder', '~/Library/Caches/com.xunlei.Thunder', '~/Library/Caches/com.xunlei.XLPlayer', '~/Library/Cookies/com.xunlei.Thunder.binarycookies', '~/Library/Preferences/com.xunlei.Thunder.loginSDK.plist', '~/Library/Preferences/com.xunlei.Thunder.plist', '~/Library/Preferences/com.xunlei.XLPlayer.plist', '~/Library/Saved Application State/com.xunlei.Thunder.savedState', '~/Library/Saved Application State/com.xunlei.XLPlayer.savedState', '~/Library/WebKit/com.xunlei.Thunder', ] end
38.8
82
0.652921