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
|
---|---|---|---|---|---|
6a8652ba09febab37118c70e9b51518c4faa957a | 1,812 | require "httpi/adapter/base"
require "httpi/response"
module HTTPI
module Adapter
# = HTTPI::Adapter::HTTPClient
#
# Adapter for the HTTPClient client.
# http://rubygems.org/gems/httpclient
class HTTPClient < Base
register :httpclient, :deps => %w(httpclient)
def initialize(request)
@request = request
@client = ::HTTPClient.new
end
attr_reader :client
# Executes arbitrary HTTP requests.
# @see HTTPI.request
def request(method)
setup_client
respond_with @client.request(method, @request.url, nil, @request.body, @request.headers)
rescue OpenSSL::SSL::SSLError
raise SSLError
end
private
def setup_client
basic_setup
setup_auth if @request.auth.http?
setup_ssl_auth if @request.auth.ssl?
end
def basic_setup
@client.proxy = @request.proxy if @request.proxy
@client.connect_timeout = @request.open_timeout if @request.open_timeout
@client.receive_timeout = @request.read_timeout if @request.read_timeout
end
def setup_auth
@client.set_auth @request.url, *@request.auth.credentials
end
def setup_ssl_auth
ssl = @request.auth.ssl
unless ssl.verify_mode == :none
@client.ssl_config.client_cert = ssl.cert
@client.ssl_config.client_key = ssl.cert_key
@client.ssl_config.add_trust_ca(ssl.ca_cert_file) if ssl.ca_cert_file
end
@client.ssl_config.verify_mode = ssl.openssl_verify_mode
@client.ssl_config.ssl_version = ssl.ssl_version if ssl.ssl_version
end
def respond_with(response)
Response.new response.code, Hash[*response.header.all.flatten], response.content
end
end
end
end
| 26.26087 | 96 | 0.654525 |
0153dd0c77d0d075e255ae5746db15d4caaf5695 | 728 | cask 'dusty' do
version '0.7.1'
sha256 '210489ae281460ab4c90e1c66998bbee8887020c73da699e356df6f26a482cb6'
url "https://github.com/gamechanger/dusty/releases/download/#{version}/dusty.tar.gz"
appcast 'https://github.com/gamechanger/dusty/releases.atom',
checkpoint: 'f91aefdc855b9b5f5534fb9c411311bad195cecb0df2796a43c79c66a6453abc'
name 'Dusty'
homepage 'https://github.com/gamechanger/dusty'
depends_on cask: 'docker-toolbox'
container type: :tar
installer script: 'brew-install.sh',
args: %W[#{staged_path}],
must_succeed: true,
sudo: true
binary 'dusty'
uninstall launchctl: 'com.gamechanger.dusty'
zap delete: '/etc/dusty'
end
| 30.333333 | 88 | 0.695055 |
3857eccbad73fd0938c2030bda04eec5a83998ea | 815 | # encoding: UTF-8
$:.push File.expand_path('../lib', __FILE__)
require 'nguyen/version'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'nguyen'
s.version = Nguyen::VERSION.dup
s.summary = 'Fill out PDF forms by XFDF/FDF via pdftk.'
s.description = 'Forms for Nguyên is Ruby library that could merge PDF fields by XFDF/FDF via pdftk.'
s.authors = 'Trung Lê'
s.email = '[email protected]'
s.homepage = 'http://github.com/ruby-journal/nguyen'
s.license = %q{MIT}
s.files = Dir['{lib}/**/*.rb', 'LICENSE', '*.md']
s.require_path = 'lib'
s.requirements << 'pdtk 1.44.1 or newer'
s.required_ruby_version = '>= 2.5.0'
s.add_runtime_dependency 'nokogiri', '~> 1.10'
s.add_development_dependency 'minitest'
end
| 32.6 | 103 | 0.63681 |
1c7e07726032e06df899057ec66aadbdc91f3f0c | 3,885 | class TclTk < Formula
desc "Tool Command Language"
homepage "https://www.tcl.tk/"
url "https://downloads.sourceforge.net/project/tcl/Tcl/8.6.9/tcl8.6.9-src.tar.gz"
mirror "https://ftp.osuosl.org/pub/blfs/conglomeration/tcl/tcl8.6.9-src.tar.gz"
version "8.6.9"
sha256 "ad0cd2de2c87b9ba8086b43957a0de3eb2eb565c7159d5f53ccbba3feb915f4e"
revision 1
bottle do
sha256 "4c12908cbfbcfd23e6b3c93d6ca3b9a691d302d4d02b39a9e07dfbce391ff094" => :mojave
sha256 "387d25e7b5ba5a24fed6f7db7153e2c5ce8f068ab1c8bcac4fd6f60043ee0c3f" => :high_sierra
sha256 "c602f2d305bc7eeac5915b9676bc513c52b7e270cb131bf504edde1b70046587" => :sierra
sha256 "00c333499fbae0aec6242ca7df0c2659b107220fe6432c6941d2e025acc26916" => :x86_64_linux
end
keg_only :provided_by_macos,
"tk installs some X11 headers and macOS provides an (older) Tcl/Tk"
depends_on "[email protected]"
unless OS.mac?
depends_on "linuxbrew/xorg/xorg"
depends_on "pkg-config" => :build
end
resource "critcl" do
url "https://github.com/andreas-kupries/critcl/archive/3.1.17.tar.gz"
sha256 "fff83b341fc07b8ff23bf1f645133bb4bffe4741da2e6f31155e522a74c228e4"
end
resource "tcllib" do
url "https://downloads.sourceforge.net/project/tcllib/tcllib/1.19/tcllib-1.19.tar.gz"
sha256 "01fe87cf1855b96866cf5394b6a786fd40b314022714b34110aeb6af545f6a9c"
end
resource "tcltls" do
url "https://core.tcl.tk/tcltls/uv/tcltls-1.7.16.tar.gz"
sha256 "6845000732bedf764e78c234cee646f95bb68df34e590c39434ab8edd6f5b9af"
end
resource "tk" do
url "https://downloads.sourceforge.net/project/tcl/Tcl/8.6.9/tk8.6.9.1-src.tar.gz"
mirror "https://fossies.org/linux/misc/tk8.6.9.1-src.tar.gz"
version "8.6.9.1"
sha256 "8fcbcd958a8fd727e279f4cac00971eee2ce271dc741650b1fc33375fb74ebb4"
# Upstream issue 7 Jan 2018 "Build failure with Aqua support on OS X 10.8 and 10.9"
# See https://core.tcl.tk/tcl/tktview/95a8293a2936e34cc8d0658c21e5214f1ca9b435
if MacOS.version == :mavericks
patch :p0 do
url "https://raw.githubusercontent.com/macports/macports-ports/0a883ad388b/x11/tk/files/patch-macosx-tkMacOSXXStubs.c.diff"
sha256 "2cdba6bbf2503307fe4f4d7200ad57c9926ebf0ff6ed3e65bf551067a30a04a9"
end
end
end
def install
args = %W[
--prefix=#{prefix}
--mandir=#{man}
--enable-threads
--enable-64bit
]
cd "unix" do
system "./configure", *args
system "make"
system "make", "install"
system "make", "install-private-headers"
ln_s bin/"tclsh#{version.to_f}", bin/"tclsh"
end
# Let tk finds our new tclsh
ENV.prepend_path "PATH", bin
resource("tk").stage do
cd "unix" do
system "./configure", *args, *("--enable-aqua=yes" if OS.mac?),
"--without-x", "--with-tcl=#{lib}"
system "make"
system "make", "install"
system "make", "install-private-headers"
ln_s bin/"wish#{version.to_f}", bin/"wish"
end
end
resource("critcl").stage do
system bin/"tclsh", "build.tcl", "install"
end
resource("tcllib").stage do
system "./configure", "--prefix=#{prefix}", "--mandir=#{man}"
system "make", "install"
if OS.mac?
ENV["SDKROOT"] = MacOS.sdk_path
end
system "make", "critcl"
cp_r "modules/tcllibc", "#{lib}/"
ln_s "#{lib}/tcllibc/macosx-x86_64-clang", "#{lib}/tcllibc/macosx-x86_64" if OS.mac?
end
resource("tcltls").stage do
system "./configure", "--with-ssl=openssl",
"--with-openssl-dir=#{Formula["[email protected]"].opt_prefix}",
"--prefix=#{prefix}",
"--mandir=#{man}"
system "make", "install"
end
end
test do
assert_equal "honk", pipe_output("#{bin}/tclsh", "puts honk\n").chomp
end
end
| 33.782609 | 131 | 0.663835 |
d5248add0edbb7331c330e71a7a3924d0aaa4823 | 3,698 | require 'spec_helper'
describe Mailigen::Api do
describe Mailigen::Api do
before(:all) do
@invalid_mailigen = invalid_mailigen_obj
@mailigen = valid_mailigen_obj
end
context "initialize with no api key" do
it "raise error" do
expect { Mailigen::Api.new }.to raise_error(Mailigen::NoApiKeyError)
end
end
context "initialize" do
it "returns object with api key" do
expect(@invalid_mailigen).not_to be(nil)
expect(@invalid_mailigen.api_key).to eq("fookey")
end
end
describe "api_url" do
context "secure" do
it "return url" do
obj = Mailigen::Api.new "fookey"
expect(obj.api_url).to eq("https://api.mailigen.com/1.5/?output=json")
end
end
end
if valid_mailigen_obj
describe "call" do
describe "ping" do
context "invalide mailigen key" do
it "returns error" do
resp = @invalid_mailigen.call :ping
expect(resp["code"]).to eq(104)
expect(resp["error"]).to eq("Invalid Mailigen API Key: fookey")
end
end
context "valide mailigen key" do
it "returns OK" do
resp = @mailigen.call :ping
expect(resp).to eq("Everything's Ok!")
end
end
end
describe "lists" do
before(:all) do
# Creates list
create_list_params = {title: "testListRspec", options: {permission_reminder: "Your in", notify_to: "[email protected]", subscription_notify: false}}
resp = @mailigen.call(:listCreate, create_list_params)
@list_id = resp
@lists_with_email = {
"0" => {EMAIL: "[email protected]", EMAIL_TYPE: 'plain', NAME: 'Foo'},
"1" => {EMAIL: "[email protected]", EMAIL_TYPE: 'html', NAME: 'Bar'},
"2" => {EMAIL: "[email protected]", EMAIL_TYPE: 'html', NAME: 'Foo Dublicate'}
}
end
after(:all) do
# Removes list
@mailigen.call :listDelete, {id: @list_id}
end
context "createList" do
it "returns list id" do
expect(@list_id).not_to be(nil)
end
end
context "lists" do
it "returns lists containg testListRspec" do
exists = false
resp = @mailigen.call :lists
selected_lists = resp.select { |list| list["name"] == "testListRspec" }
expect(selected_lists.size).to eq(1)
end
end
context "listMergeVars" do
it "returns array with vars" do
resp = @mailigen.call :listMergeVars, {id: @list_id}
expect(resp.size).to eq(3)
end
end
context "listMergeVarAdd" do
it "returns true" do
params = {id: @list_id, tag: "FOO", name: "FooName"}
resp = @mailigen.call :listMergeVarAdd, params
expect(resp).to eq("true")
end
end
context "listBatchSubscribe" do
it "returns success count and fail count" do
# Add name var
params = {id: @list_id, tag: "NAME", name: "Name of user"}
resp = @mailigen.call :listMergeVarAdd, params
params = {id: @list_id, batch: @lists_with_email, double_optin: false}
resp = @mailigen.call :listBatchSubscribe, params
expect(resp["success_count"]).to eq(3)
expect(resp["error_count"]).to eq(0)
end
end
end
end
end
end
end
| 28.015152 | 154 | 0.532991 |
39e46cf56b0dc6de1ef626e4f68c93a00261f1b3 | 1,149 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "fluent-plugin-cat-sweep"
spec.version = "0.2.0"
spec.authors = ["Civitaspo(takahiro.nakayama)", "Naotoshi Seo"]
spec.email = ["[email protected]", "[email protected]"]
spec.summary = %q{Fluentd plugin to cat files and move them.}
spec.description = spec.summary
spec.homepage = "https://github.com/civitaspo/fluent-plugin-cat-sweep"
spec.license = "MIT"
spec.files = `git ls-files`.split("\n")
spec.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
spec.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_runtime_dependency "fluentd", ">= 0.14.0"
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake"
spec.add_development_dependency "test-unit"
spec.add_development_dependency "test-unit-rr"
spec.add_development_dependency "pry"
spec.add_development_dependency "pry-nav"
end
| 39.62069 | 86 | 0.677111 |
e9501a30e4c1632a2dc0df1de8cd7a1ece9e9a3e | 1,447 | BksOnRails::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
#configure for gmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "gmail.com",
authentication: "plain",
enable_starttls_auto: true,
user_name: ENV["GMAIL_USERNAME"],
password: ENV["GMAIL_PASSWORD"]
}
end
| 35.292683 | 85 | 0.759502 |
f8ab609cec408f3bd25c17b7a71756ac9164dd61 | 1,298 | require 'bunny'
module Columbo
module Client
class AMQP
def initialize(connection_uri)
@connection_uri = connection_uri
end
def publish(event, options = {})
begin
publish_event(event, options)
true
rescue Exception => e
Columbo.logger.warn(e.message)
false
end
end
def publish!(event, options = {})
publish_event(event, options)
end
def exchange(name)
raise ArgumentError, 'Please provide a name for the AMQP exchange' if name.nil?
@channel = connection.create_channel
if block_given?
exchange_options = OpenStruct.new(arguments: {})
yield exchange_options
type = exchange_options.delete_field(:type)
@exchange = @channel.send(type, name, exchange_options.to_h)
else
raise ArgumentError, 'Please provide a block to configure the exchange'
end
end
private
def publish_event(event, options = {})
raise 'No exchange has been configurated for the Columbo Client' if @exchange.nil?
@exchange.publish(event.to_json, options)
end
def connection
@connection ||= Bunny.new(@connection_uri).start
end
end
end
end
| 24.037037 | 90 | 0.612481 |
bf985c5a0be6151033143ade2237400af087c76b | 3,771 | # encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
ENV['SKIP_RAILS'] = 'true'
require File.expand_path('../../../test_helper', __FILE__)
class NewRelic::Agent::RpmAgentTest < Test::Unit::TestCase # ActiveSupport::TestCase
def setup
NewRelic::Agent.manual_start
@agent = NewRelic::Agent.instance
@agent.stubs(:start_worker_thread)
end
def teardown
NewRelic::Agent.instance.shutdown
end
def test_agent_setup
assert(NewRelic::Agent.instance.class == NewRelic::Agent::Agent)
assert_raise(RuntimeError) do
NewRelic::Control.instance.init_plugin(:agent_enabled => false)
end
end
def test_public_apis
assert_raise(RuntimeError) do
NewRelic::Agent.set_sql_obfuscator(:unknown) { |sql| puts sql }
end
ignore_called = false
NewRelic::Agent.ignore_error_filter do |e|
ignore_called = true
nil
end
NewRelic::Agent.notice_error(StandardError.new("message"), :request_params => {:x => "y"})
assert(ignore_called)
end
def test_startup_shutdown
with_config(:agent_enabled => true) do
@agent = NewRelic::Agent::ShimAgent.instance
@agent.shutdown
assert (not @agent.started?)
@agent.start
assert [email protected]?
# this installs the real agent:
NewRelic::Agent.manual_start
@agent = NewRelic::Agent.instance
assert @agent != NewRelic::Agent::ShimAgent.instance
assert @agent.started?
@agent.shutdown
assert [email protected]?
@agent.start
assert @agent.started?
NewRelic::Agent.shutdown
end
end
def test_manual_start
NewRelic::Agent.instance.expects(:connect).once
NewRelic::Agent.instance.expects(:start_worker_thread).once
NewRelic::Agent.instance.instance_variable_set '@started', nil
NewRelic::Agent.manual_start :monitor_mode => true, :license_key => ('x' * 40)
NewRelic::Agent.shutdown
end
def test_post_fork_handler
NewRelic::Agent.manual_start :monitor_mode => true, :license_key => ('x' * 40)
NewRelic::Agent.after_fork
NewRelic::Agent.after_fork
NewRelic::Agent.shutdown
end
def test_manual_overrides
NewRelic::Agent.manual_start :app_name => "testjobs", :dispatcher_instance_id => "mailer"
assert_equal "testjobs", NewRelic::Agent.config.app_names[0]
assert_equal "mailer", NewRelic::Control.instance.local_env.dispatcher_instance_id
NewRelic::Agent.shutdown
end
def test_agent_restart
NewRelic::Agent.manual_start :app_name => "noapp", :dispatcher_instance_id => ""
NewRelic::Agent.manual_start :app_name => "testjobs", :dispatcher_instance_id => "mailer"
assert_equal "testjobs", NewRelic::Agent.config.app_names[0]
assert_equal "mailer", NewRelic::Control.instance.local_env.dispatcher_instance_id
NewRelic::Agent.shutdown
end
def test_set_record_sql
@agent.set_record_sql(false)
assert !NewRelic::Agent.is_sql_recorded?
NewRelic::Agent.disable_sql_recording do
assert_equal false, NewRelic::Agent.is_sql_recorded?
NewRelic::Agent.disable_sql_recording do
assert_equal false, NewRelic::Agent.is_sql_recorded?
end
assert_equal false, NewRelic::Agent.is_sql_recorded?
end
assert !NewRelic::Agent.is_sql_recorded?
@agent.set_record_sql(nil)
end
def test_agent_version_string
assert_match /\d\.\d+\.\d+/, NewRelic::VERSION::STRING
end
def test_record_transaction_should_reject_empty_arguments
assert_raises RuntimeError do
NewRelic::Agent.record_transaction 0.5
end
end
def test_record_transaction
NewRelic::Agent.record_transaction 0.5, 'uri' => "/users/create?foo=bar"
end
end
| 31.957627 | 94 | 0.719438 |
acef5e906bc098fb108c4a901f888a5549c6160c | 707 | Pod::Spec.new do |s|
s.name = "DRAutolayout"
s.version = "1.2"
s.summary = "Helper methods for autolayout."
s.homepage = "http://github.com/danramteke/DRAutolayout"
s.license = { :type => 'MIT', :file => 'LICENSE.txt' }
s.authors = { "Daniel Ramteke" => "[email protected]", "Paul Infield-Harm" => "[email protected]" }
s.source = { :git => "https://github.com/danramteke/DRAutolayout.git", :tag => "v#{s.version.to_s}" }
s.platform = :ios, '6.0'
s.source_files = 'DRAutolayout', 'DRAutolayout/**/*.{h,m}'
s.exclude_files = 'AutolayoutDemo'
s.public_header_files = 'DRAutolayout/**/*.h'
s.requires_arc = true
end
| 47.133333 | 134 | 0.619519 |
bb0fca242b8e6f9f2d27233f7caec064e3205358 | 253 | module DoorkeeperMongodb
module Shared
module Scopes
extend ActiveSupport::Concern
included do
field :scopes, type: String
end
def scopes=(value)
write_attribute :scopes, value
end
end
end
end
| 15.8125 | 38 | 0.628458 |
1d89a194ac15d37e97267013c495f47366e2e3c9 | 160 | class CreateEmployers < ActiveRecord::Migration[5.2]
def change
create_table :employers do |t|
t.string :name
t.timestamps
end
end
end
| 16 | 52 | 0.66875 |
6a1acce9c7459dd433a899b1edad887175a36da0 | 1,813 | # -*- encoding: utf-8 -*-
# stub: jekyll-mentions 1.4.1 ruby lib
Gem::Specification.new do |s|
s.name = "jekyll-mentions".freeze
s.version = "1.4.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["GitHub, Inc.".freeze]
s.date = "2018-08-08"
s.email = "[email protected]".freeze
s.homepage = "https://github.com/jekyll/jekyll-mentions".freeze
s.licenses = ["MIT".freeze]
s.required_ruby_version = Gem::Requirement.new(">= 2.3.0".freeze)
s.rubygems_version = "2.5.2.3".freeze
s.summary = "@mention support for your Jekyll site".freeze
s.installed_by_version = "2.5.2.3" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<html-pipeline>.freeze, ["~> 2.3"])
s.add_runtime_dependency(%q<jekyll>.freeze, ["~> 3.0"])
s.add_development_dependency(%q<rake>.freeze, ["~> 12.0"])
s.add_development_dependency(%q<rspec>.freeze, ["~> 3.0"])
s.add_development_dependency(%q<rubocop>.freeze, ["~> 0.57.2"])
else
s.add_dependency(%q<html-pipeline>.freeze, ["~> 2.3"])
s.add_dependency(%q<jekyll>.freeze, ["~> 3.0"])
s.add_dependency(%q<rake>.freeze, ["~> 12.0"])
s.add_dependency(%q<rspec>.freeze, ["~> 3.0"])
s.add_dependency(%q<rubocop>.freeze, ["~> 0.57.2"])
end
else
s.add_dependency(%q<html-pipeline>.freeze, ["~> 2.3"])
s.add_dependency(%q<jekyll>.freeze, ["~> 3.0"])
s.add_dependency(%q<rake>.freeze, ["~> 12.0"])
s.add_dependency(%q<rspec>.freeze, ["~> 3.0"])
s.add_dependency(%q<rubocop>.freeze, ["~> 0.57.2"])
end
end
| 40.288889 | 112 | 0.64203 |
7a835af2575442d0c25876093c4115fc85085a5f | 1,887 | # frozen_string_literal: true
module QA
module Page
module Component
module Select2
def select_item(item_text)
find('.select2-result-label', text: item_text, match: :prefer_exact).click
end
def has_item?(item_text)
has_css?('.select2-result-label', text: item_text, match: :prefer_exact)
end
def current_selection
find('.select2-chosen').text
end
def clear_current_selection_if_present
if has_css?('a > abbr.select2-search-choice-close', wait: 1.0)
find('a > abbr.select2-search-choice-close').click
end
end
def search_item(item_text)
find('.select2-input').set(item_text)
wait_for_search_to_complete
end
def search_and_select(item_text)
QA::Runtime::Logger.info "Searching and selecting: #{item_text}"
search_item(item_text)
raise QA::Page::Base::ElementNotFound, %Q(Couldn't find option named "#{item_text}") unless has_item?(item_text)
select_item(item_text)
end
def search_and_select_exact(item_text)
QA::Runtime::Logger.info "Searching and selecting: #{item_text}"
search_item(item_text)
raise QA::Page::Base::ElementNotFound, %Q(Couldn't find option named "#{item_text}") unless has_item?(item_text)
find('.select2-result-label', text: item_text, exact_text: true).click
end
def expand_select_list
find('span.select2-arrow').click
end
def wait_for_search_to_complete
Support::WaitForRequests.wait_for_requests
has_css?('.select2-active', wait: 1)
has_no_css?('.select2-active', wait: 30)
end
def dropdown_open?
find('.select2-focusser').disabled?
end
end
end
end
end
| 27.347826 | 122 | 0.618442 |
1d9909576e1af48247df74054d054db609559ce6 | 1,952 | Pod::Spec.new do |s|
s.name = 'Objective-LevelDB'
s.version = '2.0.7'
s.license = 'MIT'
s.summary = 'A feature-complete wrapper for LevelDB in Objective-C.'
s.description = 'This is a feature-complete wrapper for Google\'s LevelDB. LevelDB is a fast key-value store written by Google.'
s.homepage = 'https://github.com/matehat/Objective-LevelDB'
s.authors = 'Michael Hoisie', 'Mathieu D\'Amours'
s.ios.deployment_target = '5.0'
s.osx.deployment_target = '10.7'
s.source = { :git => 'https://github.com/gamy/Objective-LevelDB.git', :tag => 'v2.0.7', :submodules => true }
s.subspec 'leveldb' do |sp|
leveldb_obj_files = %w{ db/builder.cc db/c.cc db/db_impl.cc db/db_iter.cc db/dbformat.cc db/filename.cc db/log_reader.cc db/log_writer.cc db/memtable.cc db/repair.cc db/table_cache.cc db/version_edit.cc db/version_set.cc db/write_batch.cc table/block.cc table/block_builder.cc table/filter_block.cc table/format.cc table/iterator.cc table/merger.cc table/table.cc table/table_builder.cc table/two_level_iterator.cc util/arena.cc util/bloom.cc util/cache.cc util/coding.cc util/comparator.cc util/crc32c.cc util/env.cc util/env_posix.cc util/filter_policy.cc util/hash.cc util/histogram.cc util/logging.cc util/options.cc util/status.cc port/port_posix.cc }.map { |f| File.join "leveldb-library", f }
sp.source_files = 'leveldb-library/include/leveldb/*', *leveldb_obj_files
sp.header_dir = 'leveldb'
sp.preserve_path = 'leveldb-library'
sp.xcconfig = {
'CC' => 'clang',
'CXX' => 'clang++',
'HEADER_SEARCH_PATHS' => '"${PODS_ROOT}/Objective-LevelDB/leveldb-library"',
'GCC_PREPROCESSOR_DEFINITIONS' => 'LEVELDB_PLATFORM_POSIX=1 OS_MACOSX=1',
'OTHER_LDFLAGS' => '-lc++'
}
sp.requires_arc = false
end
s.source_files = 'Classes/*.{h,m,mm}'
s.dependency 'Objective-LevelDB/leveldb'
s.requires_arc = false
end
| 57.411765 | 704 | 0.693135 |
8735e82a37133d35527221604aa99fb237b317fb | 1,102 |
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "gvive/version"
Gem::Specification.new do |spec|
spec.name = "gvive"
spec.version = GVIVE::VERSION
spec.authors = ["Alfred Rowe"]
spec.email = ["[email protected]"]
spec.summary = %q{GVIVE Ruby SDK}
spec.description = %q{Identity Theft Protection SDK for GVIVE Web Service}
spec.homepage = "https://github.com/nukturnal/gvive"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.16.a"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "codeclimate-test-reporter", "~> 1.0.0"
spec.add_dependency "http", "~> 2.0"
end
| 35.548387 | 78 | 0.65245 |
33ca055e75ef920235f7e3538a48d7e40ee4ccc3 | 70 | module Docker
module Machine
VERSION = '0.1.0'.freeze
end
end
| 11.666667 | 28 | 0.671429 |
393a2ebc0c76260a435e4efe7e4e1b516edd57fc | 1,783 | class Pygobject3 < Formula
desc "GNOME Python bindings (based on GObject Introspection)"
homepage "https://wiki.gnome.org/Projects/PyGObject"
url "https://download.gnome.org/sources/pygobject/3.30/pygobject-3.30.4.tar.xz"
sha256 "2dc1a1a444b82955e65b81c2a2511ecf8032404beba4ef1d48144168f2f64c43"
bottle do
sha256 "c4004732688326f968423751c18861a21297e36bd628bd19e0c410747d60f07a" => :mojave
sha256 "342769a9ab3cbb29bd30368cb4ef7024821f45032f185c952dfdc9b32ccb4b39" => :high_sierra
sha256 "34cb3f702e580475d18bb44652fdcfb02041a1a7153246e2b710df17576b93e4" => :sierra
sha256 "0637f48a44cc5163e01cab0660b9e2ea490ef220e053fa40a1f74c2768ac9444" => :x86_64_linux
end
option "without-python", "Build without python3 support"
option "with-python@2", "Build with python2 support"
depends_on "meson" => :build
depends_on "ninja" => :build
depends_on "pkg-config" => :build
depends_on "python" => [:build, :recommended]
depends_on "gobject-introspection"
depends_on "py3cairo" if build.with? "python"
depends_on "python@2" => :optional
depends_on "py2cairo" if build.with? "python@2"
def install
Language::Python.each_python(build) do |python, version|
mkdir "build#{version}" do
system "meson", "--prefix=#{prefix}",
"-Dpycairo=true",
"-Dpython=#{python}",
".."
system "ninja", "-v"
system "ninja", "install"
end
end
end
test do
Pathname("test.py").write <<~EOS
import gi
assert("__init__" in gi.__file__)
EOS
Language::Python.each_python(build) do |python, pyversion|
ENV.prepend_path "PYTHONPATH", lib/"python#{pyversion}/site-packages"
system python, "test.py"
end
end
end
| 35.66 | 94 | 0.691531 |
4a8d8d9f1ab1cbf39d2a8206c81abd3d8c4f95e2 | 173 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
SUPPORT_DIR = File.join(__dir__, 'support')
Dir[File.join(SUPPORT_DIR, '/**/*.rb')].each { |file| require file }
| 34.6 | 68 | 0.682081 |
03eb0717a3e687637d559c73d6d405e28c976f08 | 965 | =begin
#Datadog API V1 Collection
#Collection of all Datadog Public endpoints.
The version of the OpenAPI document: 1.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
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 'spec_helper'
require 'json'
require 'date'
# Unit tests for DatadogAPIClient::V1::SLOTimeframe
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe DatadogAPIClient::V1::SLOTimeframe do
let(:instance) { DatadogAPIClient::V1::SLOTimeframe.new }
describe 'test an instance of SLOTimeframe' do
it 'should create an instance of SLOTimeframe' do
expect(instance).to be_instance_of(DatadogAPIClient::V1::SLOTimeframe)
end
end
end
| 30.15625 | 107 | 0.781347 |
e9a8965e307929856f5d2e37ad6e408d8a863476 | 166 | module Hobostove
module Models
class Message < Value.new(:id, :timestamp, :type, :user, :body)
def username
user.name
end
end
end
end
| 16.6 | 67 | 0.608434 |
39c06b6ab79fe76d3b1222ff9c72419ad554dcf6 | 2,816 | require 'conjur_client'
class OrgSpacePolicy
include ConjurApiModel
class OrgPolicyNotFound < RuntimeError
end
class SpacePolicyNotFound < RuntimeError
end
class SpaceLayerNotFound < RuntimeError
end
class << self
def ensure_exists(org_id, space_id, organization_name, space_name)
OrgSpacePolicy.new(org_id, space_id, organization_name, space_name).ensure_exists
end
def create(org_id, space_id, organization_name, space_name)
OrgSpacePolicy.new(org_id, space_id, organization_name, space_name).create
end
end
def initialize(org_id, space_id, organization_name, space_name)
@org_id = org_id
@space_id = space_id
@organization_name = organization_name
@space_name = space_name
end
def ensure_exists
ensure_org_policy
ensure_space_policy
ensure_space_layer
end
def create
if @organization_name.nil?
load_policy(template_create_org_space)
else
load_policy(template_create_org_space_with_annotations)
end
end
private
def ensure_org_policy
raise OrgPolicyNotFound, "Unable to find #{org_policy} policy branch." unless org_policy.exists?
end
def org_policy
ConjurClient.readonly_api.resource(org_policy_id)
end
def org_policy_id
"#{ConjurClient.account}:policy:#{policy_base}#{@org_id}"
end
def ensure_space_policy
raise SpacePolicyNotFound, "Unable to find #{space_policy} policy branch." unless space_policy.exists?
end
def space_policy
ConjurClient.readonly_api.resource(space_policy_id)
end
def space_policy_id
"#{ConjurClient.account}:policy:#{policy_base}#{@org_id}/#{@space_id}"
end
def ensure_space_layer
raise SpaceLayerNotFound, "Unable to find #{space_layer} layer in policy." unless space_layer.exists?
end
def space_layer
ConjurClient.readonly_api.resource(space_layer_id)
end
def space_layer_id
"#{ConjurClient.account}:layer:#{policy_base}#{@org_id}/#{@space_id}"
end
def template_create_org_space
<<~YAML
---
- !policy
id: #{@org_id}
body:
- !layer
- !policy
id: #{@space_id}
body:
- !layer
- !grant
role: !layer
member: !layer #{@space_id}
YAML
end
def template_create_org_space_with_annotations
<<~YAML
---
- !policy
id: #{@org_id}
annotations:
pcf/type: org
pcf/orgName: #{@organization_name}
body:
- !layer
- !policy
id: #{@space_id}
annotations:
pcf/type: space
pcf/orgName: #{@organization_name}
pcf/spaceName: #{@space_name}
body:
- !layer
- !grant
role: !layer
member: !layer #{@space_id}
YAML
end
end
| 21.661538 | 106 | 0.663707 |
b9e343cee9c1e123ba6ec42fb2bb41bda05c9fcf | 139 | require_relative '../../spec_helper'
require_relative 'shared/imag'
describe "Numeric#imag" do
it_behaves_like :numeric_imag, :imag
end
| 19.857143 | 38 | 0.776978 |
e81f0865c994a7bf23c5216066671279d6121f28 | 7,066 | #--
# DO NOT MODIFY!!!!
# This file is automatically generated by rex 1.0.5
# from lexical definition file "inlinetokenizer.rex".
#++
module CSSPool
module CSS
class InlineTokenizerBase < InlineParserBase
require 'strscan'
class ScanError < StandardError ; end
attr_reader :lineno
attr_reader :filename
attr_accessor :state
def scan_setup(str)
# @yydebug = true
@ss = StringScanner.new(str)
@lineno = 1
@state = nil
end
def action
yield
end
def scan_str(str)
scan_setup(str)
do_parse
end
alias :scan :scan_str
def load_file( filename )
@filename = filename
open(filename, "r") do |f|
scan_setup(f.read)
end
end
def scan_file( filename )
load_file(filename)
do_parse
end
def next_token
return if @ss.eos?
# skips empty actions
until token = _next_token or @ss.eos?; end
token
end
def _next_token
text = @ss.peek(1)
@lineno += 1 if text == "\n"
token = case @state
when nil
case
when (text = @ss.scan(/url\([\s]*("([^\n\r\f\\"]|\\\n|\r\n|\r|\f|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*"|'([^\n\r\f\\']|\\\n|\r\n|\r|\f|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*')[\s]*\)/))
action { [:URI, st(text)] }
when (text = @ss.scan(/url\([\s]*([!#\$%&*-~]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*[\s]*\)/))
action { [:URI, st(text)] }
when (text = @ss.scan(/U\+[0-9a-fA-F?]{1,6}(-[0-9a-fA-F]{1,6})?/))
action {[:UNICODE_RANGE, st(text)] }
when (text = @ss.scan(/[\s]*\/\*(.|[\s]*)*?\*\/[\s]*/))
action { next_token }
when (text = @ss.scan(/[-@]?([_A-Za-z]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f]|[.])*\(\s*/))
action { [:FUNCTION, st(text)] }
when (text = @ss.scan(/[\s]*@import[\s]*/))
action { [:IMPORT_SYM, st(text)] }
when (text = @ss.scan(/[\s]*@page[\s]*/))
action { [:PAGE_SYM, st(text)] }
when (text = @ss.scan(/[\s]*@charset[\s]*/))
action { [:CHARSET_SYM, st(text)] }
when (text = @ss.scan(/[\s]*@media[\s]*/))
action { [:MEDIA_SYM, st(text)] }
when (text = @ss.scan(/[\s]*!([\s]*|[\s]*\/\*(.|[\s]*)*?\*\/[\s]*)important[\s]*/))
action { [:IMPORTANT_SYM, st(text)] }
when (text = @ss.scan(/[\s]*[-@]?([_A-Za-z]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*/))
action { [:IDENT, st(text)] }
when (text = @ss.scan(/\#([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])+/))
action { [:HASH, st(text)] }
when (text = @ss.scan(/[\s]*~=[\s]*/))
action { [:INCLUDES, st(text)] }
when (text = @ss.scan(/[\s]*\|=[\s]*/))
action { [:DASHMATCH, st(text)] }
when (text = @ss.scan(/[\s]*\^=[\s]*/))
action { [:PREFIXMATCH, st(text)] }
when (text = @ss.scan(/[\s]*\$=[\s]*/))
action { [:SUFFIXMATCH, st(text)] }
when (text = @ss.scan(/[\s]*\*=[\s]*/))
action { [:SUBSTRINGMATCH, st(text)] }
when (text = @ss.scan(/[\s]*!=[\s]*/))
action { [:NOT_EQUAL, st(text)] }
when (text = @ss.scan(/[\s]*=[\s]*/))
action { [:EQUAL, st(text)] }
when (text = @ss.scan(/[\s]*\)/))
action { [:RPAREN, st(text)] }
when (text = @ss.scan(/[\s]*\[[\s]*/))
action { [:LSQUARE, st(text)] }
when (text = @ss.scan(/[\s]*\]/))
action { [:RSQUARE, st(text)] }
when (text = @ss.scan(/[\s]*\+[\s]*/))
action { [:PLUS, st(text)] }
when (text = @ss.scan(/[\s]*\{[\s]*/))
action { [:LBRACE, st(text)] }
when (text = @ss.scan(/[\s]*\}[\s]*/))
action { [:RBRACE, st(text)] }
when (text = @ss.scan(/[\s]*>[\s]*/))
action { [:GREATER, st(text)] }
when (text = @ss.scan(/[\s]*,[\s]*/))
action { [:COMMA, st(',')] }
when (text = @ss.scan(/[\s]*;[\s]*/))
action { [:SEMI, st(';')] }
when (text = @ss.scan(/\*/))
action { [:STAR, st(text)] }
when (text = @ss.scan(/[\s]*~[\s]*/))
action { [:TILDE, st(text)] }
when (text = @ss.scan(/\:not\([\s]*/))
action { [:NOT, st(text)] }
when (text = @ss.scan(/[\s]*([0-9]*\.[0-9]+|[0-9]+)em[\s]*/))
action { [:EMS, st(text)] }
when (text = @ss.scan(/[\s]*([0-9]*\.[0-9]+|[0-9]+)ex[\s]*/))
action { [:EXS, st(text)] }
when (text = @ss.scan(/[\s]*([0-9]*\.[0-9]+|[0-9]+)(px|cm|mm|in|pt|pc)[\s]*/))
action { [:LENGTH, st(text)] }
when (text = @ss.scan(/[\s]*([0-9]*\.[0-9]+|[0-9]+)(deg|rad|grad)[\s]*/))
action { [:ANGLE, st(text)] }
when (text = @ss.scan(/[\s]*([0-9]*\.[0-9]+|[0-9]+)(ms|s)[\s]*/))
action { [:TIME, st(text)] }
when (text = @ss.scan(/[\s]*([0-9]*\.[0-9]+|[0-9]+)[k]?hz[\s]*/))
action { [:FREQ, st(text)] }
when (text = @ss.scan(/[\s]*([0-9]*\.[0-9]+|[0-9]+)%[\s]*/))
action { [:PERCENTAGE, st(text)] }
when (text = @ss.scan(/[\s]*([0-9]*\.[0-9]+|[0-9]+)[\s]*/))
action { [:NUMBER, st(text)] }
when (text = @ss.scan(/[\s]*\/\/[\s]*/))
action { [:DOUBLESLASH, st(text)] }
when (text = @ss.scan(/[\s]*\/[\s]*/))
action { [:SLASH, st('/')] }
when (text = @ss.scan(/<!--/))
action { [:CDO, st(text)] }
when (text = @ss.scan(/-->/))
action { [:CDC, st(text)] }
when (text = @ss.scan(/[\s]*\-(?![-@]?([_A-Za-z]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*)[\s]*/))
action { [:MINUS, st(text)] }
when (text = @ss.scan(/[\s]*\+[\s]*/))
action { [:PLUS, st(text)] }
when (text = @ss.scan(/[\s]+/))
action { [:S, st(text)] }
when (text = @ss.scan(/("([^\n\r\f\\"]|\\\n|\r\n|\r|\f|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*"|'([^\n\r\f\\']|\\\n|\r\n|\r|\f|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*')/))
action { [:STRING, st(text)] }
when (text = @ss.scan(/("([^\n\r\f\\"]|\\\n|\r\n|\r|\f|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*|'([^\n\r\f\\']|\\\n|\r\n|\r|\f|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*)/))
action { [:INVALID, st(text)] }
when (text = @ss.scan(/./))
action { [st(text), st(text)] }
else
text = @ss.string[@ss.pos .. -1]
raise ScanError, "can not match: '" + text + "'"
end # if
else
raise ScanError, "undefined state: '" + state.to_s + "'"
end # case state
token
end # def _next_token
def st o
@st ||= Hash.new { |h,k| h[k] = k }
@st[o]
end # class
end
end
end
# vim: syntax=lex
| 30.721739 | 244 | 0.433484 |
03597e405d2e50f1ccb8971c114d622f8c87793b | 374 | require "sentry/configuration"
require "sentry/scope"
require "sentry/logger"
require "sentry/event"
require "sentry/client"
module Sentry
class Error < StandardError
end
def self.sys_command(command)
result = `#{command} 2>&1` rescue nil
return if result.nil? || result.empty? || ($CHILD_STATUS && $CHILD_STATUS.exitstatus != 0)
result.strip
end
end
| 20.777778 | 94 | 0.713904 |
0302837f352f7ca0dee005091e3986bb4590afa2 | 336 | class CreateStats < ActiveRecord::Migration
def self.up
create_table :stats do |t|
t.integer :process_id, :processing_time, :open_connections
t.string :kind, :info
t.datetime :created_at
end
add_index :stats, 'kind'
end
def self.down
# remove_index :stats, 'kind'
drop_table :stats
end
end
| 21 | 64 | 0.672619 |
01ff275204edd2f4c06233748bcef432f7d58cf8 | 279 | # frozen_string_literal: true
RSpec.shared_context 'with Rails 3', :rails3 do
let(:rails_version) { 3.0 }
end
RSpec.shared_context 'with Rails 4', :rails4 do
let(:rails_version) { 4.0 }
end
RSpec.shared_context 'with Rails 5', :rails5 do
let(:rails_version) { 5.0 }
end
| 19.928571 | 47 | 0.713262 |
d5081ee1eb991d3fbaf3d40fa8bae76f4c22b982 | 891 | module ArraySpecs
def self.frozen_array
@frozen_array ||= [1,2,3]
@frozen_array.freeze
@frozen_array
end
def self.recursive_array
a = [1, 'two', 3.0]
5.times { a << a }
a
end
def self.head_recursive_array
a = []
5.times { a << a }
a << 1 << 'two' << 3.0
a
end
def self.empty_recursive_array
a = []
a << a
a
end
class MyArray < Array; end
class Sexp < Array
def initialize(*args)
super(args)
end
end
class ToAryArray < Array
def to_ary() ["to_ary", "was", "called!"] end
end
class MyRange < Range; end
class AssocKey
def ==(other); other == 'it'; end
end
class D
def <=>(obj)
return 4 <=> obj unless obj.class == D
0
end
end
class SubArray < Array
attr_reader :special
def initialize(size=0)
@special = size
end
end
end
| 14.85 | 49 | 0.554433 |
08656503aefe9a9c51c8b2526ec25f3a61d1cd20 | 7,010 | module Frontend
module CommonModule
include ArrayLiquid
include ApplicationHelper
def set_tags
tags = []
unless params[:slug_tags].blank?
params[:slug_tags].split('/').each do |id|
tag = Tag.find_by(id: id)
tags << tag unless tag.nil?
end
end
ids = tags.map(&:id)
slugs = tags.map(&:slug)
[tags, ids, slugs]
end
def append_general_tags(liquid_options)
@variables['tags_group'] ||= array_to_liquid(TagsGroup.retrieve_groups)
tags = []
tags = liquid_options[0] if liquid_options
@variables['selected_tags'] = array_to_liquid(tags)
end
def append_language_variables
@variables['languages'] = Language.in_frontend
@variables['locale'] = I18n.default_locale.to_s
@variables['locale'] = session[:locale] unless session[:locale].blank?
end
def append_customer_variables
@variables['current_customer'] = current_customer
@variables['show_shopping_carts_path'] = Routes.show_shopping_carts_path
@variables['clear_shopping_carts_path'] = Routes.clear_shopping_carts_path
@variables['shipping_method_customers_shopping_orders_path'] = Routes.shipping_method_customers_shopping_orders_path
if customer_signed_in?
# Action form
@variables['customer_edit_registration_href'] = Routes.edit_customer_registration_path # DEPRECATED
@variables['customer_orders_href'] = Routes.orders_customers_path # DEPRECATED
@variables['customers_addresses_path'] = Routes.customers_addresses_path
else
# Action form
@variables['action_customer_sign_in_url'] = Routes.customer_session_path
@variables['action_customer_sign_up_url'] = Routes.customer_registration_path
# Links a
@variables['customer_forgot_password_href'] = Routes.new_customer_password_path
@variables['customer_sign_up_href'] = Routes.new_customer_registration_path
@variables['customer_new_session_href'] = Routes.new_customer_session_path
end
sc = ShoppingCart.retrieve(current_customer, session[:shopping_cart])
@variables['shopping_cart'] = sc.to_liquid
end
def append_message_variables
@variables['error_messages'] = []
if defined? resource
@variables['error_messages'] = resource.errors.full_messages unless resource.nil?
@variables['resource'] = resource
end
@variables['error_messages_title'] = Utils.get_error_title(@variables['error_messages'])
flash.each do |key, value|
@variables["#{key}_message"] = value
end
end
def append_link_variables
@variables['authenticity_token'] = form_authenticity_token
@variables['action_search_url'] = Routes.searches_path
end
def append_variables
@variables ||= {}
append_message_variables
append_language_variables
@liquid_options = {features: true, current_tags: set_tags}
@liquid_options[:current_category] = @category if @category
@liquid_options[:current_product] = @product if @product
@liquid_options[:current_commerce] = @my_site if @my_site
@variables['categories'] = array_to_liquid(Category.root_categories(@my_site.tree_category), @liquid_options)
append_general_tags(@liquid_options)
append_link_variables
append_customer_variables
end
def render_template(template, file_html)
body_code = template.reads_file(file_html)
body_code = Utils.replace_regex_include(@variables, template, body_code)
# First time filling descriptions
template_first = Liquid::Template.parse(body_code)
body_code = template_first.render(@variables)
@body_content = Utils.replace_regex_include(@variables, template, body_code)
@head_javascript = template.reads_file('common_js.js')
@head_css = template.reads_file('common_css.css')
html_code = render_to_string(text: '', layout: 'custom_template')
# Second time with descriptions
template_second = Liquid::Template.parse(html_code)
template_second.instance_assigns = template_first.instance_assigns
html_code = template_second.render(@variables)
html_code = Utils.replace_regex_include(@variables, template, html_code)
# Third time with descriptions
template_third = Liquid::Template.parse(html_code)
template_third.instance_assigns = template_second.instance_assigns
html_code = template_third.render(@variables)
html_code = Utils.replace_regex_include(@variables, template, html_code)
append_debug_variables(current_admin_user, @variables, html_code)
end
def retrieve_file_html(controller, action, args = [])
# Fixed errors like 404
if args.is_a?(Array) && args.any? && args[0].is_a?(String) && args[0].start_with?('errors/')
return "#{args[0]}.html"
end
file_html = "#{controller}/#{action}.html"
if %w(show tags).include?(action) && !@variables['show_action_name'].blank?
if !@render_template.nil? &&
@render_template.ok?("#{controller}/#{@variables['show_action_name']}.html")
file_html = "#{controller}/#{@variables['show_action_name']}.html"
end
end
if controller == 'registrations'
case action
when 'create' # Fixed route devise when fails sign up.
file_html = "#{controller}/new.html"
when 'update' # Fixed route devise when fails edit.
file_html = "#{controller}/edit.html"
end
end
# Fixed route pretty urls
if controller == 'dynamic_path' && action == 'show_path'
prefix = 'categories'
prefix = 'products' if @product.present?
if !@render_template || !@render_template.ok?("#{prefix}/#{@variables['show_action_name']}.html")
return "#{prefix}/show.html"
end
file_html = "#{prefix}/#{@variables['show_action_name']}.html"
end
file_html
end
def determine_layout
file_html = retrieve_file_html(controller_name, action_name)
if !@render_template.nil? && @render_template.ok?(file_html)
'custom_template'
else
case self.class.name
when 'CategoriesController', 'HomeController', 'ProductsController', 'SearchesController'
'searcher_and_side_bar'
when 'ShoppingCartsController', 'ShoppingOrdersController'
'shopping'
else
'application'
end
end
end
def render(*args)
append_variables
file_html = retrieve_file_html(controller_name, action_name, args)
has_custom_layout = args.is_a?(Array) && args.any? && args[0].is_a?(Hash) && args[0][:common_module]
if !@render_template.nil? && @render_template.ok?(file_html) && !has_custom_layout
render text: render_template(@render_template, file_html), common_module: true
else
super
end
end
end
end
| 35.583756 | 122 | 0.680599 |
6a6743f914d7d9c5312ac30e7eb001e42a3a6dc7 | 1,310 | # frozen_string_literal: true
require 'spec_helper'
describe 'Global search' do
let(:user) { create(:user) }
let(:project) { create(:project, namespace: user.namespace) }
before do
project.add_maintainer(user)
sign_in(user)
visit dashboard_projects_path
end
it 'increases usage ping searches counter' do
expect(Gitlab::UsageDataCounters::SearchCounter).to receive(:count).with(:navbar_searches)
expect(Gitlab::UsageDataCounters::SearchCounter).to receive(:count).with(:all_searches)
submit_search('foobar')
end
describe 'I search through the issues and I see pagination' do
before do
allow_next_instance_of(SearchService) do |instance|
allow(instance).to receive(:per_page).and_return(1)
end
create_list(:issue, 2, project: project, title: 'initial')
end
it "has a pagination" do
submit_search('initial')
select_search_scope('Issues')
expect(page).to have_selector('.gl-pagination .next')
end
end
it 'closes the dropdown on blur', :js do
fill_in 'search', with: "a"
dropdown = find('.js-dashboard-search-options')
expect(dropdown[:class]).to include 'show'
find('#search').send_keys(:backspace)
find('body').click
expect(dropdown[:class]).not_to include 'show'
end
end
| 25.686275 | 94 | 0.693893 |
f881fcfbe18899c2fac42954e5bfe44d6a0461fe | 84,487 | # 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
#
# 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 RunV1alpha1
# Not supported by Cloud Run ConfigMapEnvSource selects a ConfigMap to populate
# the environment variables with. The contents of the target ConfigMap's Data
# field will represent the key-value pairs as environment variables.
class ConfigMapEnvSource
include Google::Apis::Core::Hashable
# Not supported by Cloud Run LocalObjectReference contains enough information to
# let you locate the referenced object inside the same namespace.
# Corresponds to the JSON property `localObjectReference`
# @return [Google::Apis::RunV1alpha1::LocalObjectReference]
attr_accessor :local_object_reference
# The ConfigMap to select from.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# (Optional) Specify whether the ConfigMap must be defined
# Corresponds to the JSON property `optional`
# @return [Boolean]
attr_accessor :optional
alias_method :optional?, :optional
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@local_object_reference = args[:local_object_reference] if args.key?(:local_object_reference)
@name = args[:name] if args.key?(:name)
@optional = args[:optional] if args.key?(:optional)
end
end
# Not supported by Cloud Run Selects a key from a ConfigMap.
class ConfigMapKeySelector
include Google::Apis::Core::Hashable
# The key to select.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
# Not supported by Cloud Run LocalObjectReference contains enough information to
# let you locate the referenced object inside the same namespace.
# Corresponds to the JSON property `localObjectReference`
# @return [Google::Apis::RunV1alpha1::LocalObjectReference]
attr_accessor :local_object_reference
# The ConfigMap to select from.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# (Optional) Specify whether the ConfigMap or its key must be defined
# Corresponds to the JSON property `optional`
# @return [Boolean]
attr_accessor :optional
alias_method :optional?, :optional
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@key = args[:key] if args.key?(:key)
@local_object_reference = args[:local_object_reference] if args.key?(:local_object_reference)
@name = args[:name] if args.key?(:name)
@optional = args[:optional] if args.key?(:optional)
end
end
# Not supported by Cloud Run Adapts a ConfigMap into a volume. The contents of
# the target ConfigMap's Data field will be presented in a volume as files using
# the keys in the Data field as the file names, unless the items element is
# populated with specific mappings of keys to paths.
class ConfigMapVolumeSource
include Google::Apis::Core::Hashable
# (Optional) Integer representation of mode bits to use on created files by
# default. Must be a value between 01 and 0777 (octal). If 0 or not set, it will
# default to 0644. Directories within the path are not affected by this setting.
# Notes * Internally, a umask of 0222 will be applied to any non-zero value. *
# This is an integer representation of the mode bits. So, the octal integer
# value should look exactly as the chmod numeric notation with a leading zero.
# Some examples: for chmod 777 (a=rwx), set to 0777 (octal) or 511 (base-10).
# For chmod 640 (u=rw,g=r), set to 0640 (octal) or 416 (base-10). For chmod 755 (
# u=rwx,g=rx,o=rx), set to 0755 (octal) or 493 (base-10). * This might be in
# conflict with other options that affect the file mode, like fsGroup, and the
# result can be other mode bits set.
# Corresponds to the JSON property `defaultMode`
# @return [Fixnum]
attr_accessor :default_mode
# (Optional) If unspecified, each key-value pair in the Data field of the
# referenced Secret will be projected into the volume as a file whose name is
# the key and content is the value. If specified, the listed keys will be
# projected into the specified paths, and unlisted keys will not be present. If
# a key is specified that is not present in the Secret, the volume setup will
# error unless it is marked optional.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::RunV1alpha1::KeyToPath>]
attr_accessor :items
# Name of the config.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# (Optional) Specify whether the Secret or its keys must be defined.
# Corresponds to the JSON property `optional`
# @return [Boolean]
attr_accessor :optional
alias_method :optional?, :optional
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@default_mode = args[:default_mode] if args.key?(:default_mode)
@items = args[:items] if args.key?(:items)
@name = args[:name] if args.key?(:name)
@optional = args[:optional] if args.key?(:optional)
end
end
# A single application container. This specifies both the container to run, the
# command to run in the container and the arguments to supply to it. Note that
# additional arguments may be supplied by the system to the container at runtime.
class Container
include Google::Apis::Core::Hashable
# (Optional) Arguments to the entrypoint. The docker image's CMD is used if this
# is not provided. Variable references $(VAR_NAME) are expanded using the
# container's environment. If a variable cannot be resolved, the reference in
# the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with
# a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded,
# regardless of whether the variable exists or not. More info: https://
# kubernetes.io/docs/tasks/inject-data-application/define-command-argument-
# container/#running-a-command-in-a-shell
# Corresponds to the JSON property `args`
# @return [Array<String>]
attr_accessor :args
#
# Corresponds to the JSON property `command`
# @return [Array<String>]
attr_accessor :command
# (Optional) List of environment variables to set in the container.
# Corresponds to the JSON property `env`
# @return [Array<Google::Apis::RunV1alpha1::EnvVar>]
attr_accessor :env
# (Optional) List of sources to populate environment variables in the container.
# The keys defined within a source must be a C_IDENTIFIER. All invalid keys will
# be reported as an event when the container is starting. When a key exists in
# multiple sources, the value associated with the last source will take
# precedence. Values defined by an Env with a duplicate key will take precedence.
# Cannot be updated.
# Corresponds to the JSON property `envFrom`
# @return [Array<Google::Apis::RunV1alpha1::EnvFromSource>]
attr_accessor :env_from
# Only supports containers from Google Container Registry or Artifact Registry
# URL of the Container image. More info: https://kubernetes.io/docs/concepts/
# containers/images
# Corresponds to the JSON property `image`
# @return [String]
attr_accessor :image
# (Optional) Image pull policy. One of Always, Never, IfNotPresent. Defaults to
# Always if :latest tag is specified, or IfNotPresent otherwise. More info:
# https://kubernetes.io/docs/concepts/containers/images#updating-images
# Corresponds to the JSON property `imagePullPolicy`
# @return [String]
attr_accessor :image_pull_policy
# Not supported by Cloud Run Probe describes a health check to be performed
# against a container to determine whether it is alive or ready to receive
# traffic.
# Corresponds to the JSON property `livenessProbe`
# @return [Google::Apis::RunV1alpha1::Probe]
attr_accessor :liveness_probe
# (Optional) Name of the container specified as a DNS_LABEL. Currently unused in
# Cloud Run. More info: https://kubernetes.io/docs/concepts/overview/working-
# with-objects/names/#dns-label-names
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# (Optional) List of ports to expose from the container. Only a single port can
# be specified. The specified ports must be listening on all interfaces (0.0.0.0)
# within the container to be accessible. If omitted, a port number will be
# chosen and passed to the container through the PORT environment variable for
# the container to listen on.
# Corresponds to the JSON property `ports`
# @return [Array<Google::Apis::RunV1alpha1::ContainerPort>]
attr_accessor :ports
# Not supported by Cloud Run Probe describes a health check to be performed
# against a container to determine whether it is alive or ready to receive
# traffic.
# Corresponds to the JSON property `readinessProbe`
# @return [Google::Apis::RunV1alpha1::Probe]
attr_accessor :readiness_probe
# ResourceRequirements describes the compute resource requirements.
# Corresponds to the JSON property `resources`
# @return [Google::Apis::RunV1alpha1::ResourceRequirements]
attr_accessor :resources
# Not supported by Cloud Run SecurityContext holds security configuration that
# will be applied to a container. Some fields are present in both
# SecurityContext and PodSecurityContext. When both are set, the values in
# SecurityContext take precedence.
# Corresponds to the JSON property `securityContext`
# @return [Google::Apis::RunV1alpha1::SecurityContext]
attr_accessor :security_context
# Not supported by Cloud Run Probe describes a health check to be performed
# against a container to determine whether it is alive or ready to receive
# traffic.
# Corresponds to the JSON property `startupProbe`
# @return [Google::Apis::RunV1alpha1::Probe]
attr_accessor :startup_probe
# (Optional) Path at which the file to which the container's termination message
# will be written is mounted into the container's filesystem. Message written is
# intended to be brief final status, such as an assertion failure message. Will
# be truncated by the node if greater than 4096 bytes. The total message length
# across all containers will be limited to 12kb. Defaults to /dev/termination-
# log.
# Corresponds to the JSON property `terminationMessagePath`
# @return [String]
attr_accessor :termination_message_path
# (Optional) Indicate how the termination message should be populated. File will
# use the contents of terminationMessagePath to populate the container status
# message on both success and failure. FallbackToLogsOnError will use the last
# chunk of container log output if the termination message file is empty and the
# container exited with an error. The log output is limited to 2048 bytes or 80
# lines, whichever is smaller. Defaults to File. Cannot be updated.
# Corresponds to the JSON property `terminationMessagePolicy`
# @return [String]
attr_accessor :termination_message_policy
# (Optional) Volume to mount into the container's filesystem. Only supports
# SecretVolumeSources. Pod volumes to mount into the container's filesystem.
# Corresponds to the JSON property `volumeMounts`
# @return [Array<Google::Apis::RunV1alpha1::VolumeMount>]
attr_accessor :volume_mounts
# (Optional) Container's working directory. If not specified, the container
# runtime's default will be used, which might be configured in the container
# image.
# Corresponds to the JSON property `workingDir`
# @return [String]
attr_accessor :working_dir
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@args = args[:args] if args.key?(:args)
@command = args[:command] if args.key?(:command)
@env = args[:env] if args.key?(:env)
@env_from = args[:env_from] if args.key?(:env_from)
@image = args[:image] if args.key?(:image)
@image_pull_policy = args[:image_pull_policy] if args.key?(:image_pull_policy)
@liveness_probe = args[:liveness_probe] if args.key?(:liveness_probe)
@name = args[:name] if args.key?(:name)
@ports = args[:ports] if args.key?(:ports)
@readiness_probe = args[:readiness_probe] if args.key?(:readiness_probe)
@resources = args[:resources] if args.key?(:resources)
@security_context = args[:security_context] if args.key?(:security_context)
@startup_probe = args[:startup_probe] if args.key?(:startup_probe)
@termination_message_path = args[:termination_message_path] if args.key?(:termination_message_path)
@termination_message_policy = args[:termination_message_policy] if args.key?(:termination_message_policy)
@volume_mounts = args[:volume_mounts] if args.key?(:volume_mounts)
@working_dir = args[:working_dir] if args.key?(:working_dir)
end
end
# ContainerPort represents a network port in a single container.
class ContainerPort
include Google::Apis::Core::Hashable
# (Optional) Port number the container listens on. This must be a valid port
# number, 0 < x < 65536.
# Corresponds to the JSON property `containerPort`
# @return [Fixnum]
attr_accessor :container_port
# (Optional) If specified, used to specify which protocol to use. Allowed values
# are "http1" and "h2c".
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# (Optional) Protocol for port. Must be "TCP". Defaults to "TCP".
# Corresponds to the JSON property `protocol`
# @return [String]
attr_accessor :protocol
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@container_port = args[:container_port] if args.key?(:container_port)
@name = args[:name] if args.key?(:name)
@protocol = args[:protocol] if args.key?(:protocol)
end
end
# A generic empty message that you can re-use to avoid defining duplicated empty
# messages in your APIs. A typical example is to use it as the request or the
# response type of an API method. For instance: service Foo ` rpc Bar(google.
# protobuf.Empty) returns (google.protobuf.Empty); `
class Empty
include Google::Apis::Core::Hashable
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
end
end
# Not supported by Cloud Run EnvFromSource represents the source of a set of
# ConfigMaps
class EnvFromSource
include Google::Apis::Core::Hashable
# Not supported by Cloud Run ConfigMapEnvSource selects a ConfigMap to populate
# the environment variables with. The contents of the target ConfigMap's Data
# field will represent the key-value pairs as environment variables.
# Corresponds to the JSON property `configMapRef`
# @return [Google::Apis::RunV1alpha1::ConfigMapEnvSource]
attr_accessor :config_map_ref
# (Optional) An optional identifier to prepend to each key in the ConfigMap.
# Must be a C_IDENTIFIER.
# Corresponds to the JSON property `prefix`
# @return [String]
attr_accessor :prefix
# Not supported by Cloud Run SecretEnvSource selects a Secret to populate the
# environment variables with. The contents of the target Secret's Data field
# will represent the key-value pairs as environment variables.
# Corresponds to the JSON property `secretRef`
# @return [Google::Apis::RunV1alpha1::SecretEnvSource]
attr_accessor :secret_ref
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@config_map_ref = args[:config_map_ref] if args.key?(:config_map_ref)
@prefix = args[:prefix] if args.key?(:prefix)
@secret_ref = args[:secret_ref] if args.key?(:secret_ref)
end
end
# EnvVar represents an environment variable present in a Container.
class EnvVar
include Google::Apis::Core::Hashable
# Name of the environment variable. Must be a C_IDENTIFIER.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# (Optional) Variable references $(VAR_NAME) are expanded using the previous
# defined environment variables in the container and any route environment
# variables. If a variable cannot be resolved, the reference in the input string
# will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie:
# $$(VAR_NAME). Escaped references will never be expanded, regardless of whether
# the variable exists or not. Defaults to "".
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
# EnvVarSource represents a source for the value of an EnvVar.
# Corresponds to the JSON property `valueFrom`
# @return [Google::Apis::RunV1alpha1::EnvVarSource]
attr_accessor :value_from
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
@value = args[:value] if args.key?(:value)
@value_from = args[:value_from] if args.key?(:value_from)
end
end
# EnvVarSource represents a source for the value of an EnvVar.
class EnvVarSource
include Google::Apis::Core::Hashable
# Not supported by Cloud Run Selects a key from a ConfigMap.
# Corresponds to the JSON property `configMapKeyRef`
# @return [Google::Apis::RunV1alpha1::ConfigMapKeySelector]
attr_accessor :config_map_key_ref
# SecretKeySelector selects a key of a Secret.
# Corresponds to the JSON property `secretKeyRef`
# @return [Google::Apis::RunV1alpha1::SecretKeySelector]
attr_accessor :secret_key_ref
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@config_map_key_ref = args[:config_map_key_ref] if args.key?(:config_map_key_ref)
@secret_key_ref = args[:secret_key_ref] if args.key?(:secret_key_ref)
end
end
# Not supported by Cloud Run ExecAction describes a "run in container" action.
class ExecAction
include Google::Apis::Core::Hashable
# (Optional) Command is the command line to execute inside the container, the
# working directory for the command is root ('/') in the container's filesystem.
# The command is simply exec'd, it is not run inside a shell, so traditional
# shell instructions ('|', etc) won't work. To use a shell, you need to
# explicitly call out to that shell. Exit status of 0 is treated as live/healthy
# and non-zero is unhealthy.
# Corresponds to the JSON property `command`
# @return [Array<String>]
attr_accessor :command
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@command = args[:command] if args.key?(:command)
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). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
class GoogleRpcStatus
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 is 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
# Not supported by Cloud Run HTTPGetAction describes an action based on HTTP Get
# requests.
class HttpGetAction
include Google::Apis::Core::Hashable
# (Optional) Host name to connect to, defaults to the pod IP. You probably want
# to set "Host" in httpHeaders instead.
# Corresponds to the JSON property `host`
# @return [String]
attr_accessor :host
# (Optional) Custom headers to set in the request. HTTP allows repeated headers.
# Corresponds to the JSON property `httpHeaders`
# @return [Array<Google::Apis::RunV1alpha1::HttpHeader>]
attr_accessor :http_headers
# (Optional) Path to access on the HTTP server.
# Corresponds to the JSON property `path`
# @return [String]
attr_accessor :path
# (Optional) Scheme to use for connecting to the host. Defaults to HTTP.
# Corresponds to the JSON property `scheme`
# @return [String]
attr_accessor :scheme
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@host = args[:host] if args.key?(:host)
@http_headers = args[:http_headers] if args.key?(:http_headers)
@path = args[:path] if args.key?(:path)
@scheme = args[:scheme] if args.key?(:scheme)
end
end
# Not supported by Cloud Run HTTPHeader describes a custom header to be used in
# HTTP probes
class HttpHeader
include Google::Apis::Core::Hashable
# The header field name
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# The header field value
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
@value = args[:value] if args.key?(:value)
end
end
# Result of an instance attempt.
class InstanceAttemptResult
include Google::Apis::Core::Hashable
# Optional. The exit code of this attempt. This may be unset if the container
# was unable to exit cleanly with a code due to some other failure. See status
# field for possible failure details.
# Corresponds to the JSON property `exitCode`
# @return [Fixnum]
attr_accessor :exit_code
# 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). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `status`
# @return [Google::Apis::RunV1alpha1::GoogleRpcStatus]
attr_accessor :status
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@exit_code = args[:exit_code] if args.key?(:exit_code)
@status = args[:status] if args.key?(:status)
end
end
# InstanceSpec is a description of an instance.
class InstanceSpec
include Google::Apis::Core::Hashable
# Optional. Optional duration in seconds the instance may be active relative to
# StartTime before the system will actively try to mark it failed and kill
# associated containers. If set to zero, the system will never attempt to kill
# an instance based on time. Otherwise, value must be a positive integer. +
# optional
# Corresponds to the JSON property `activeDeadlineSeconds`
# @return [Fixnum]
attr_accessor :active_deadline_seconds
# Optional. List of containers belonging to the instance. We disallow a number
# of fields on this Container. Only a single container may be provided.
# Corresponds to the JSON property `containers`
# @return [Array<Google::Apis::RunV1alpha1::Container>]
attr_accessor :containers
# Optional. Restart policy for all containers within the instance. Allowed
# values are: - OnFailure: Instances will always be restarted on failure if the
# backoffLimit has not been reached. - Never: Instances are never restarted and
# all failures are permanent. Cannot be used if backoffLimit is set. +optional
# Corresponds to the JSON property `restartPolicy`
# @return [String]
attr_accessor :restart_policy
# Optional. Email address of the IAM service account associated with the
# instance of a Job. The service account represents the identity of the running
# instance, and determines what permissions the instance has. If not provided,
# the instance will use the project's default service account. +optional
# Corresponds to the JSON property `serviceAccountName`
# @return [String]
attr_accessor :service_account_name
# Optional. Optional duration in seconds the instance needs to terminate
# gracefully. Value must be non-negative integer. The value zero indicates
# delete immediately. The grace period is the duration in seconds after the
# processes running in the instance are sent a termination signal and the time
# when the processes are forcibly halted with a kill signal. Set this value
# longer than the expected cleanup time for your process. +optional
# Corresponds to the JSON property `terminationGracePeriodSeconds`
# @return [Fixnum]
attr_accessor :termination_grace_period_seconds
# Optional. List of volumes that can be mounted by containers belonging to the
# instance. More info: https://kubernetes.io/docs/concepts/storage/volumes +
# optional
# Corresponds to the JSON property `volumes`
# @return [Array<Google::Apis::RunV1alpha1::Volume>]
attr_accessor :volumes
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@active_deadline_seconds = args[:active_deadline_seconds] if args.key?(:active_deadline_seconds)
@containers = args[:containers] if args.key?(:containers)
@restart_policy = args[:restart_policy] if args.key?(:restart_policy)
@service_account_name = args[:service_account_name] if args.key?(:service_account_name)
@termination_grace_period_seconds = args[:termination_grace_period_seconds] if args.key?(:termination_grace_period_seconds)
@volumes = args[:volumes] if args.key?(:volumes)
end
end
# Instance represents the status of an instance of a Job.
class InstanceStatus
include Google::Apis::Core::Hashable
# Optional. Represents time when the instance was completed. It is not
# guaranteed to be set in happens-before order across separate operations. It is
# represented in RFC3339 form and is in UTC. +optional
# Corresponds to the JSON property `completionTime`
# @return [String]
attr_accessor :completion_time
# Optional. The number of times this instance exited with code > 0; +optional
# Corresponds to the JSON property `failed`
# @return [Fixnum]
attr_accessor :failed
# Required. Index of the instance, unique per Job, and beginning at 0.
# Corresponds to the JSON property `index`
# @return [Fixnum]
attr_accessor :index
# Result of an instance attempt.
# Corresponds to the JSON property `lastAttemptResult`
# @return [Google::Apis::RunV1alpha1::InstanceAttemptResult]
attr_accessor :last_attempt_result
# Optional. Last exit code seen for this instance. +optional
# Corresponds to the JSON property `lastExitCode`
# @return [Fixnum]
attr_accessor :last_exit_code
# Optional. The number of times this instance was restarted. Instances are
# restarted according the restartPolicy configured in the Job template. +
# optional
# Corresponds to the JSON property `restarted`
# @return [Fixnum]
attr_accessor :restarted
# Optional. Represents time when the instance was created by the job controller.
# It is not guaranteed to be set in happens-before order across separate
# operations. It is represented in RFC3339 form and is in UTC. +optional
# Corresponds to the JSON property `startTime`
# @return [String]
attr_accessor :start_time
# Optional. The number of times this instance exited with code == 0. +optional
# Corresponds to the JSON property `succeeded`
# @return [Fixnum]
attr_accessor :succeeded
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@completion_time = args[:completion_time] if args.key?(:completion_time)
@failed = args[:failed] if args.key?(:failed)
@index = args[:index] if args.key?(:index)
@last_attempt_result = args[:last_attempt_result] if args.key?(:last_attempt_result)
@last_exit_code = args[:last_exit_code] if args.key?(:last_exit_code)
@restarted = args[:restarted] if args.key?(:restarted)
@start_time = args[:start_time] if args.key?(:start_time)
@succeeded = args[:succeeded] if args.key?(:succeeded)
end
end
# InstanceTemplateSpec describes the data an instance should have when created
# from a template.
class InstanceTemplateSpec
include Google::Apis::Core::Hashable
# InstanceSpec is a description of an instance.
# Corresponds to the JSON property `spec`
# @return [Google::Apis::RunV1alpha1::InstanceSpec]
attr_accessor :spec
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@spec = args[:spec] if args.key?(:spec)
end
end
# Job represents the configuration of a single job. A job an immutable resource
# that references a container image which is run to completion.
class Job
include Google::Apis::Core::Hashable
# Optional. APIVersion defines the versioned schema of this representation of an
# object. Servers should convert recognized schemas to the latest internal value,
# and may reject unrecognized values. More info: https://git.k8s.io/community/
# contributors/devel/sig-architecture/api-conventions.md#resources +optional
# Corresponds to the JSON property `apiVersion`
# @return [String]
attr_accessor :api_version
# Optional. Kind is a string value representing the REST resource this object
# represents. Servers may infer this from the endpoint the client submits
# requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/
# community/contributors/devel/sig-architecture/api-conventions.md#types-kinds +
# optional
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta is metadata that all persisted
# resources must have, which includes all objects users must create.
# Corresponds to the JSON property `metadata`
# @return [Google::Apis::RunV1alpha1::ObjectMeta]
attr_accessor :metadata
# JobSpec describes how the job execution will look like.
# Corresponds to the JSON property `spec`
# @return [Google::Apis::RunV1alpha1::JobSpec]
attr_accessor :spec
# JobStatus represents the current state of a Job.
# Corresponds to the JSON property `status`
# @return [Google::Apis::RunV1alpha1::JobStatus]
attr_accessor :status
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@api_version = args[:api_version] if args.key?(:api_version)
@kind = args[:kind] if args.key?(:kind)
@metadata = args[:metadata] if args.key?(:metadata)
@spec = args[:spec] if args.key?(:spec)
@status = args[:status] if args.key?(:status)
end
end
# JobCondition defines a readiness condition for a Revision.
class JobCondition
include Google::Apis::Core::Hashable
# Optional. Last time the condition transitioned from one status to another.
# Corresponds to the JSON property `lastTransitionTime`
# @return [String]
attr_accessor :last_transition_time
# Optional. Human readable message indicating details about the current status.
# Corresponds to the JSON property `message`
# @return [String]
attr_accessor :message
# Optional. One-word CamelCase reason for the condition's last transition.
# Corresponds to the JSON property `reason`
# @return [String]
attr_accessor :reason
# Optional. How to interpret failures of this condition, one of Error, Warning,
# Info
# Corresponds to the JSON property `severity`
# @return [String]
attr_accessor :severity
# Required. Status of the condition, one of True, False, Unknown.
# Corresponds to the JSON property `status`
# @return [String]
attr_accessor :status
# Required. Type is used to communicate the status of the reconciliation process.
# See also: https://github.com/knative/serving/blob/main/docs/spec/errors.md#
# error-conditions-and-reporting Types include: * "Completed": True when the Job
# has successfully completed. * "Started": True when the Job has successfully
# started running. * "ResourcesAvailable": True when underlying resources have
# been provisioned.
# 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)
@last_transition_time = args[:last_transition_time] if args.key?(:last_transition_time)
@message = args[:message] if args.key?(:message)
@reason = args[:reason] if args.key?(:reason)
@severity = args[:severity] if args.key?(:severity)
@status = args[:status] if args.key?(:status)
@type = args[:type] if args.key?(:type)
end
end
# JobSpec describes how the job execution will look like.
class JobSpec
include Google::Apis::Core::Hashable
# Optional. Not supported. Specifies the duration in seconds relative to the
# startTime that the job may be active before the system tries to terminate it.
# If set to zero, the system will never attempt to terminate the job based on
# time. Otherwise, the value must be positive integer. +optional
# Corresponds to the JSON property `activeDeadlineSeconds`
# @return [Fixnum]
attr_accessor :active_deadline_seconds
# Optional. Specifies the number of retries per instance, before marking this
# job failed. If set to zero, instances will never retry on failure. +optional
# Corresponds to the JSON property `backoffLimit`
# @return [Fixnum]
attr_accessor :backoff_limit
# Optional. Specifies the desired number of successfully finished instances the
# job should be run with. Setting to 1 means that parallelism is limited to 1
# and the success of that instance signals the success of the job. More info:
# https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-
# completion/ +optional
# Corresponds to the JSON property `completions`
# @return [Fixnum]
attr_accessor :completions
# Optional. Specifies the maximum desired number of instances the job should run
# at any given time. Must be <= completions. The actual number of instances
# running in steady state will be less than this number when ((.spec.completions
# - .status.successful) < .spec.parallelism), i.e. when the work left to do is
# less than max parallelism. More info: https://kubernetes.io/docs/concepts/
# workloads/controllers/jobs-run-to-completion/ +optional
# Corresponds to the JSON property `parallelism`
# @return [Fixnum]
attr_accessor :parallelism
# InstanceTemplateSpec describes the data an instance should have when created
# from a template.
# Corresponds to the JSON property `template`
# @return [Google::Apis::RunV1alpha1::InstanceTemplateSpec]
attr_accessor :template
# Optional. Not supported. ttlSecondsAfterFinished limits the lifetime of a Job
# that has finished execution (either Complete or Failed). If this field is set,
# ttlSecondsAfterFinished after the Job finishes, it is eligible to be
# automatically deleted. When the Job is being deleted, its lifecycle guarantees
# (e.g. finalizers) will be honored. If this field is set to zero, the Job won't
# be automatically deleted. +optional
# Corresponds to the JSON property `ttlSecondsAfterFinished`
# @return [Fixnum]
attr_accessor :ttl_seconds_after_finished
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@active_deadline_seconds = args[:active_deadline_seconds] if args.key?(:active_deadline_seconds)
@backoff_limit = args[:backoff_limit] if args.key?(:backoff_limit)
@completions = args[:completions] if args.key?(:completions)
@parallelism = args[:parallelism] if args.key?(:parallelism)
@template = args[:template] if args.key?(:template)
@ttl_seconds_after_finished = args[:ttl_seconds_after_finished] if args.key?(:ttl_seconds_after_finished)
end
end
# JobStatus represents the current state of a Job.
class JobStatus
include Google::Apis::Core::Hashable
# Optional. The number of actively running instances. +optional
# Corresponds to the JSON property `active`
# @return [Fixnum]
attr_accessor :active
# Optional. Represents time when the job was completed. It is not guaranteed to
# be set in happens-before order across separate operations. It is represented
# in RFC3339 form and is in UTC. +optional
# Corresponds to the JSON property `completionTime`
# @return [String]
attr_accessor :completion_time
# Optional. The latest available observations of a job's current state. More
# info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-
# completion/ +optional
# Corresponds to the JSON property `conditions`
# @return [Array<Google::Apis::RunV1alpha1::JobCondition>]
attr_accessor :conditions
# Optional. The number of instances which reached phase Failed. +optional
# Corresponds to the JSON property `failed`
# @return [Fixnum]
attr_accessor :failed
# Optional. ImageDigest holds the resolved digest for the image specified within
# .Spec.Template.Spec.Container.Image. The digest is resolved during the
# creation of the Job. This field holds the digest value regardless of whether a
# tag or digest was originally specified in the Container object.
# Corresponds to the JSON property `imageDigest`
# @return [String]
attr_accessor :image_digest
# Optional. Status of completed, failed, and running instances. +optional
# Corresponds to the JSON property `instances`
# @return [Array<Google::Apis::RunV1alpha1::InstanceStatus>]
attr_accessor :instances
# Optional. The 'generation' of the job that was last processed by the
# controller.
# Corresponds to the JSON property `observedGeneration`
# @return [Fixnum]
attr_accessor :observed_generation
# Optional. Represents time when the job was acknowledged by the job controller.
# It is not guaranteed to be set in happens-before order across separate
# operations. It is represented in RFC3339 form and is in UTC. +optional
# Corresponds to the JSON property `startTime`
# @return [String]
attr_accessor :start_time
# Optional. The number of instances which reached phase Succeeded. +optional
# Corresponds to the JSON property `succeeded`
# @return [Fixnum]
attr_accessor :succeeded
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@active = args[:active] if args.key?(:active)
@completion_time = args[:completion_time] if args.key?(:completion_time)
@conditions = args[:conditions] if args.key?(:conditions)
@failed = args[:failed] if args.key?(:failed)
@image_digest = args[:image_digest] if args.key?(:image_digest)
@instances = args[:instances] if args.key?(:instances)
@observed_generation = args[:observed_generation] if args.key?(:observed_generation)
@start_time = args[:start_time] if args.key?(:start_time)
@succeeded = args[:succeeded] if args.key?(:succeeded)
end
end
# Maps a string key to a path within a volume.
class KeyToPath
include Google::Apis::Core::Hashable
# The Cloud Secret Manager secret version. Can be 'latest' for the latest value
# or an integer for a specific version. The key to project.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
# (Optional) Mode bits to use on this file, must be a value between 01 and 0777 (
# octal). If 0 or not set, the Volume's default mode will be used. Notes *
# Internally, a umask of 0222 will be applied to any non-zero value. * This is
# an integer representation of the mode bits. So, the octal integer value should
# look exactly as the chmod numeric notation with a leading zero. Some examples:
# for chmod 777 (a=rwx), set to 0777 (octal) or 511 (base-10). For chmod 640 (u=
# rw,g=r), set to 0640 (octal) or 416 (base-10). For chmod 755 (u=rwx,g=rx,o=rx),
# set to 0755 (octal) or 493 (base-10). * This might be in conflict with other
# options that affect the file mode, like fsGroup, and the result can be other
# mode bits set.
# Corresponds to the JSON property `mode`
# @return [Fixnum]
attr_accessor :mode
# The relative path of the file to map the key to. May not be an absolute path.
# May not contain the path element '..'. May not start with the string '..'.
# Corresponds to the JSON property `path`
# @return [String]
attr_accessor :path
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@key = args[:key] if args.key?(:key)
@mode = args[:mode] if args.key?(:mode)
@path = args[:path] if args.key?(:path)
end
end
# ListJobsResponse is a list of Jobs resources.
class ListJobsResponse
include Google::Apis::Core::Hashable
# The API version for this call such as "run.googleapis.com/v1alpha1".
# Corresponds to the JSON property `apiVersion`
# @return [String]
attr_accessor :api_version
# List of Jobs.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::RunV1alpha1::Job>]
attr_accessor :items
# The kind of this resource, in this case "JobsList".
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# ListMeta describes metadata that synthetic resources must have, including
# lists and various status objects. A resource may have only one of `ObjectMeta,
# ListMeta`.
# Corresponds to the JSON property `metadata`
# @return [Google::Apis::RunV1alpha1::ListMeta]
attr_accessor :metadata
# This field is equivalent to the metadata.continue field and is provided as a
# convenience for compatibility with https://google.aip.dev/158. The value is
# opaque and may be used to issue another request to the endpoint that served
# this list to retrieve the next set of available objects. Continuing a list may
# not be possible if the server configuration has changed or more than a few
# minutes have passed. The metadata.resourceVersion field returned when using
# this field will be identical to the value in the first response.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
# Locations that could not be reached.
# Corresponds to the JSON property `unreachable`
# @return [Array<String>]
attr_accessor :unreachable
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@api_version = args[:api_version] if args.key?(:api_version)
@items = args[:items] if args.key?(:items)
@kind = args[:kind] if args.key?(:kind)
@metadata = args[:metadata] if args.key?(:metadata)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
@unreachable = args[:unreachable] if args.key?(:unreachable)
end
end
# ListMeta describes metadata that synthetic resources must have, including
# lists and various status objects. A resource may have only one of `ObjectMeta,
# ListMeta`.
class ListMeta
include Google::Apis::Core::Hashable
# continue may be set if the user set a limit on the number of items returned,
# and indicates that the server has more data available. The value is opaque and
# may be used to issue another request to the endpoint that served this list to
# retrieve the next set of available objects. Continuing a list may not be
# possible if the server configuration has changed or more than a few minutes
# have passed. The resourceVersion field returned when using this continue value
# will be identical to the value in the first response.
# Corresponds to the JSON property `continue`
# @return [String]
attr_accessor :continue
# String that identifies the server's internal version of this object that can
# be used by clients to determine when objects have changed. Value must be
# treated as opaque by clients and passed unmodified back to the server.
# Populated by the system. Read-only. More info: https://git.k8s.io/community/
# contributors/devel/api-conventions.md#concurrency-control-and-consistency +
# optional
# Corresponds to the JSON property `resourceVersion`
# @return [String]
attr_accessor :resource_version
# SelfLink is a URL representing this object. Populated by the system. Read-only.
# +optional
# Corresponds to the JSON property `selfLink`
# @return [String]
attr_accessor :self_link
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@continue = args[:continue] if args.key?(:continue)
@resource_version = args[:resource_version] if args.key?(:resource_version)
@self_link = args[:self_link] if args.key?(:self_link)
end
end
# Not supported by Cloud Run LocalObjectReference contains enough information to
# let you locate the referenced object inside the same namespace.
class LocalObjectReference
include Google::Apis::Core::Hashable
# (Optional) Name of the referent. More info: https://kubernetes.io/docs/
# concepts/overview/working-with-objects/names/#names
# 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)
@name = args[:name] if args.key?(:name)
end
end
# k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta is metadata that all persisted
# resources must have, which includes all objects users must create.
class ObjectMeta
include Google::Apis::Core::Hashable
# (Optional) Annotations is an unstructured key value map stored with a resource
# that may be set by external tools to store and retrieve arbitrary metadata.
# They are not queryable and should be preserved when modifying objects. More
# info: https://kubernetes.io/docs/user-guide/annotations
# Corresponds to the JSON property `annotations`
# @return [Hash<String,String>]
attr_accessor :annotations
# (Optional) Not supported by Cloud Run The name of the cluster which the object
# belongs to. This is used to distinguish resources with same name and namespace
# in different clusters. This field is not set anywhere right now and apiserver
# is going to ignore it if set in create or update request.
# Corresponds to the JSON property `clusterName`
# @return [String]
attr_accessor :cluster_name
# (Optional) CreationTimestamp is a timestamp representing the server time when
# this object was created. It is not guaranteed to be set in happens-before
# order across separate operations. Clients may not set this value. It is
# represented in RFC3339 form and is in UTC. Populated by the system. Read-only.
# Null for lists. More info: https://git.k8s.io/community/contributors/devel/api-
# conventions.md#metadata
# Corresponds to the JSON property `creationTimestamp`
# @return [String]
attr_accessor :creation_timestamp
# (Optional) Not supported by Cloud Run Number of seconds allowed for this
# object to gracefully terminate before it will be removed from the system. Only
# set when deletionTimestamp is also set. May only be shortened. Read-only.
# Corresponds to the JSON property `deletionGracePeriodSeconds`
# @return [Fixnum]
attr_accessor :deletion_grace_period_seconds
# (Optional) Not supported by Cloud Run DeletionTimestamp is RFC 3339 date and
# time at which this resource will be deleted. This field is set by the server
# when a graceful deletion is requested by the user, and is not directly
# settable by a client. The resource is expected to be deleted (no longer
# visible from resource lists, and not reachable by name) after the time in this
# field, once the finalizers list is empty. As long as the finalizers list
# contains items, deletion is blocked. Once the deletionTimestamp is set, this
# value may not be unset or be set further into the future, although it may be
# shortened or the resource may be deleted prior to this time. For example, a
# user may request that a pod is deleted in 30 seconds. The Kubelet will react
# by sending a graceful termination signal to the containers in the pod. After
# that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to
# the container and after cleanup, remove the pod from the API. In the presence
# of network partitions, this object may still exist after this timestamp, until
# an administrator or automated process can determine the resource is fully
# terminated. If not set, graceful deletion of the object has not been requested.
# Populated by the system when a graceful deletion is requested. Read-only.
# More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#
# metadata
# Corresponds to the JSON property `deletionTimestamp`
# @return [String]
attr_accessor :deletion_timestamp
# (Optional) Not supported by Cloud Run Must be empty before the object is
# deleted from the registry. Each entry is an identifier for the responsible
# component that will remove the entry from the list. If the deletionTimestamp
# of the object is non-nil, entries in this list can only be removed. +
# patchStrategy=merge
# Corresponds to the JSON property `finalizers`
# @return [Array<String>]
attr_accessor :finalizers
# (Optional) Not supported by Cloud Run GenerateName is an optional prefix, used
# by the server, to generate a unique name ONLY IF the Name field has not been
# provided. If this field is used, the name returned to the client will be
# different than the name passed. This value will also be combined with a unique
# suffix. The provided value has the same validation rules as the Name field,
# and may be truncated by the length of the suffix required to make the value
# unique on the server. If this field is specified and the generated name exists,
# the server will NOT return a 409 - instead, it will either return 201 Created
# or 500 with Reason ServerTimeout indicating a unique name could not be found
# in the time allotted, and the client should retry (optionally after the time
# indicated in the Retry-After header). Applied only if Name is not specified.
# More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#
# idempotency string generateName = 2;
# Corresponds to the JSON property `generateName`
# @return [String]
attr_accessor :generate_name
# (Optional) A sequence number representing a specific generation of the desired
# state. Populated by the system. Read-only.
# Corresponds to the JSON property `generation`
# @return [Fixnum]
attr_accessor :generation
# (Optional) Map of string keys and values that can be used to organize and
# categorize (scope and select) objects. May match selectors of replication
# controllers and routes. More info: https://kubernetes.io/docs/user-guide/
# labels
# Corresponds to the JSON property `labels`
# @return [Hash<String,String>]
attr_accessor :labels
# Name must be unique within a namespace, within a Cloud Run region. Is required
# when creating resources, although some resources may allow a client to request
# the generation of an appropriate name automatically. Name is primarily
# intended for creation idempotence and configuration definition. Cannot be
# updated. More info: https://kubernetes.io/docs/user-guide/identifiers#names +
# optional
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Namespace defines the space within each name must be unique, within a Cloud
# Run region. In Cloud Run the namespace must be equal to either the project ID
# or project number.
# Corresponds to the JSON property `namespace`
# @return [String]
attr_accessor :namespace
# (Optional) Not supported by Cloud Run List of objects that own this object. If
# ALL objects in the list have been deleted, this object will be garbage
# collected.
# Corresponds to the JSON property `ownerReferences`
# @return [Array<Google::Apis::RunV1alpha1::OwnerReference>]
attr_accessor :owner_references
# Optional. An opaque value that represents the internal version of this object
# that can be used by clients to determine when objects have changed. May be
# used for optimistic concurrency, change detection, and the watch operation on
# a resource or set of resources. Clients must treat these values as opaque and
# passed unmodified back to the server or omit the value to disable conflict-
# detection. They may only be valid for a particular resource or set of
# resources. Populated by the system. Read-only. Value must be treated as opaque
# by clients or omitted. More info: https://git.k8s.io/community/contributors/
# devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
# Corresponds to the JSON property `resourceVersion`
# @return [String]
attr_accessor :resource_version
# (Optional) SelfLink is a URL representing this object. Populated by the system.
# Read-only. string selfLink = 4;
# Corresponds to the JSON property `selfLink`
# @return [String]
attr_accessor :self_link
# (Optional) UID is the unique in time and space value for this object. It is
# typically generated by the server on successful creation of a resource and is
# not allowed to change on PUT operations. Populated by the system. Read-only.
# More info: https://kubernetes.io/docs/user-guide/identifiers#uids
# Corresponds to the JSON property `uid`
# @return [String]
attr_accessor :uid
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@annotations = args[:annotations] if args.key?(:annotations)
@cluster_name = args[:cluster_name] if args.key?(:cluster_name)
@creation_timestamp = args[:creation_timestamp] if args.key?(:creation_timestamp)
@deletion_grace_period_seconds = args[:deletion_grace_period_seconds] if args.key?(:deletion_grace_period_seconds)
@deletion_timestamp = args[:deletion_timestamp] if args.key?(:deletion_timestamp)
@finalizers = args[:finalizers] if args.key?(:finalizers)
@generate_name = args[:generate_name] if args.key?(:generate_name)
@generation = args[:generation] if args.key?(:generation)
@labels = args[:labels] if args.key?(:labels)
@name = args[:name] if args.key?(:name)
@namespace = args[:namespace] if args.key?(:namespace)
@owner_references = args[:owner_references] if args.key?(:owner_references)
@resource_version = args[:resource_version] if args.key?(:resource_version)
@self_link = args[:self_link] if args.key?(:self_link)
@uid = args[:uid] if args.key?(:uid)
end
end
# OwnerReference contains enough information to let you identify an owning
# object. Currently, an owning object must be in the same namespace, so there is
# no namespace field.
class OwnerReference
include Google::Apis::Core::Hashable
# API version of the referent.
# Corresponds to the JSON property `apiVersion`
# @return [String]
attr_accessor :api_version
# If true, AND if the owner has the "foregroundDeletion" finalizer, then the
# owner cannot be deleted from the key-value store until this reference is
# removed. Defaults to false. To set this field, a user needs "delete"
# permission of the owner, otherwise 422 (Unprocessable Entity) will be returned.
# +optional
# Corresponds to the JSON property `blockOwnerDeletion`
# @return [Boolean]
attr_accessor :block_owner_deletion
alias_method :block_owner_deletion?, :block_owner_deletion
# If true, this reference points to the managing controller. +optional
# Corresponds to the JSON property `controller`
# @return [Boolean]
attr_accessor :controller
alias_method :controller?, :controller
# Kind of the referent. More info: https://git.k8s.io/community/contributors/
# devel/sig-architecture/api-conventions.md#types-kinds
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Name of the referent. More info: https://kubernetes.io/docs/user-guide/
# identifiers#names
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# UID of the referent. More info: https://kubernetes.io/docs/user-guide/
# identifiers#uids
# Corresponds to the JSON property `uid`
# @return [String]
attr_accessor :uid
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@api_version = args[:api_version] if args.key?(:api_version)
@block_owner_deletion = args[:block_owner_deletion] if args.key?(:block_owner_deletion)
@controller = args[:controller] if args.key?(:controller)
@kind = args[:kind] if args.key?(:kind)
@name = args[:name] if args.key?(:name)
@uid = args[:uid] if args.key?(:uid)
end
end
# Not supported by Cloud Run Probe describes a health check to be performed
# against a container to determine whether it is alive or ready to receive
# traffic.
class Probe
include Google::Apis::Core::Hashable
# Not supported by Cloud Run ExecAction describes a "run in container" action.
# Corresponds to the JSON property `exec`
# @return [Google::Apis::RunV1alpha1::ExecAction]
attr_accessor :exec
# (Optional) Minimum consecutive failures for the probe to be considered failed
# after having succeeded. Defaults to 3. Minimum value is 1.
# Corresponds to the JSON property `failureThreshold`
# @return [Fixnum]
attr_accessor :failure_threshold
# Not supported by Cloud Run HTTPGetAction describes an action based on HTTP Get
# requests.
# Corresponds to the JSON property `httpGet`
# @return [Google::Apis::RunV1alpha1::HttpGetAction]
attr_accessor :http_get
# (Optional) Number of seconds after the container has started before liveness
# probes are initiated. More info: https://kubernetes.io/docs/concepts/workloads/
# pods/pod-lifecycle#container-probes
# Corresponds to the JSON property `initialDelaySeconds`
# @return [Fixnum]
attr_accessor :initial_delay_seconds
# (Optional) How often (in seconds) to perform the probe. Default to 10 seconds.
# Minimum value is 1. Maximum value is 3600. Must be greater or equal than
# timeout_seconds.
# Corresponds to the JSON property `periodSeconds`
# @return [Fixnum]
attr_accessor :period_seconds
# (Optional) Minimum consecutive successes for the probe to be considered
# successful after having failed. Defaults to 1. Must be 1 for liveness and
# startup Probes.
# Corresponds to the JSON property `successThreshold`
# @return [Fixnum]
attr_accessor :success_threshold
# Not supported by Cloud Run TCPSocketAction describes an action based on
# opening a socket
# Corresponds to the JSON property `tcpSocket`
# @return [Google::Apis::RunV1alpha1::TcpSocketAction]
attr_accessor :tcp_socket
# (Optional) Number of seconds after which the probe times out. Defaults to 1
# second. Minimum value is 1. Maximum value is 3600. Must be smaller than
# period_seconds. More info: https://kubernetes.io/docs/concepts/workloads/pods/
# pod-lifecycle#container-probes
# Corresponds to the JSON property `timeoutSeconds`
# @return [Fixnum]
attr_accessor :timeout_seconds
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@exec = args[:exec] if args.key?(:exec)
@failure_threshold = args[:failure_threshold] if args.key?(:failure_threshold)
@http_get = args[:http_get] if args.key?(:http_get)
@initial_delay_seconds = args[:initial_delay_seconds] if args.key?(:initial_delay_seconds)
@period_seconds = args[:period_seconds] if args.key?(:period_seconds)
@success_threshold = args[:success_threshold] if args.key?(:success_threshold)
@tcp_socket = args[:tcp_socket] if args.key?(:tcp_socket)
@timeout_seconds = args[:timeout_seconds] if args.key?(:timeout_seconds)
end
end
# ResourceRequirements describes the compute resource requirements.
class ResourceRequirements
include Google::Apis::Core::Hashable
# (Optional) Only memory and CPU are supported. Limits describes the maximum
# amount of compute resources allowed. The values of the map is string form of
# the 'quantity' k8s type: https://github.com/kubernetes/kubernetes/blob/master/
# staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go
# Corresponds to the JSON property `limits`
# @return [Hash<String,String>]
attr_accessor :limits
# (Optional) Only memory and CPU are supported. Requests describes the minimum
# amount of compute resources required. If Requests is omitted for a container,
# it defaults to Limits if that is explicitly specified, otherwise to an
# implementation-defined value. The values of the map is string form of the '
# quantity' k8s type: https://github.com/kubernetes/kubernetes/blob/master/
# staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go
# Corresponds to the JSON property `requests`
# @return [Hash<String,String>]
attr_accessor :requests
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@limits = args[:limits] if args.key?(:limits)
@requests = args[:requests] if args.key?(:requests)
end
end
# Not supported by Cloud Run SecretEnvSource selects a Secret to populate the
# environment variables with. The contents of the target Secret's Data field
# will represent the key-value pairs as environment variables.
class SecretEnvSource
include Google::Apis::Core::Hashable
# Not supported by Cloud Run LocalObjectReference contains enough information to
# let you locate the referenced object inside the same namespace.
# Corresponds to the JSON property `localObjectReference`
# @return [Google::Apis::RunV1alpha1::LocalObjectReference]
attr_accessor :local_object_reference
# The Secret to select from.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# (Optional) Specify whether the Secret must be defined
# Corresponds to the JSON property `optional`
# @return [Boolean]
attr_accessor :optional
alias_method :optional?, :optional
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@local_object_reference = args[:local_object_reference] if args.key?(:local_object_reference)
@name = args[:name] if args.key?(:name)
@optional = args[:optional] if args.key?(:optional)
end
end
# SecretKeySelector selects a key of a Secret.
class SecretKeySelector
include Google::Apis::Core::Hashable
# A Cloud Secret Manager secret version. Must be 'latest' for the latest version
# or an integer for a specific version. The key of the secret to select from.
# Must be a valid secret key.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
# Not supported by Cloud Run LocalObjectReference contains enough information to
# let you locate the referenced object inside the same namespace.
# Corresponds to the JSON property `localObjectReference`
# @return [Google::Apis::RunV1alpha1::LocalObjectReference]
attr_accessor :local_object_reference
# The name of the secret in Cloud Secret Manager. By default, the secret is
# assumed to be in the same project. If the secret is in another project, you
# must define an alias. An alias definition has the form: :projects//secrets/.
# If multiple alias definitions are needed, they must be separated by commas.
# The alias definitions must be set on the run.googleapis.com/secrets annotation.
# The name of the secret in the pod's namespace to select from.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# (Optional) Specify whether the Secret or its key must be defined
# Corresponds to the JSON property `optional`
# @return [Boolean]
attr_accessor :optional
alias_method :optional?, :optional
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@key = args[:key] if args.key?(:key)
@local_object_reference = args[:local_object_reference] if args.key?(:local_object_reference)
@name = args[:name] if args.key?(:name)
@optional = args[:optional] if args.key?(:optional)
end
end
# The secret's value will be presented as the content of a file whose name is
# defined in the item path. If no items are defined, the name of the file is the
# secret_name. The contents of the target Secret's Data field will be presented
# in a volume as files using the keys in the Data field as the file names.
class SecretVolumeSource
include Google::Apis::Core::Hashable
# Integer representation of mode bits to use on created files by default. Must
# be a value between 01 and 0777 (octal). If 0 or not set, it will default to
# 0644. Directories within the path are not affected by this setting. Notes *
# Internally, a umask of 0222 will be applied to any non-zero value. * This is
# an integer representation of the mode bits. So, the octal integer value should
# look exactly as the chmod numeric notation with a leading zero. Some examples:
# for chmod 777 (a=rwx), set to 0777 (octal) or 511 (base-10). For chmod 640 (u=
# rw,g=r), set to 0640 (octal) or 416 (base-10). For chmod 755 (u=rwx,g=rx,o=rx),
# set to 0755 (octal) or 493 (base-10). * This might be in conflict with other
# options that affect the file mode, like fsGroup, and the result can be other
# mode bits set.
# Corresponds to the JSON property `defaultMode`
# @return [Fixnum]
attr_accessor :default_mode
# (Optional) If unspecified, the volume will expose a file whose name is the
# secret_name. If specified, the key will be used as the version to fetch from
# Cloud Secret Manager and the path will be the name of the file exposed in the
# volume. When items are defined, they must specify a key and a path. If
# unspecified, each key-value pair in the Data field of the referenced Secret
# will be projected into the volume as a file whose name is the key and content
# is the value. If specified, the listed keys will be projected into the
# specified paths, and unlisted keys will not be present. If a key is specified
# that is not present in the Secret, the volume setup will error unless it is
# marked optional.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::RunV1alpha1::KeyToPath>]
attr_accessor :items
# (Optional) Specify whether the Secret or its keys must be defined.
# Corresponds to the JSON property `optional`
# @return [Boolean]
attr_accessor :optional
alias_method :optional?, :optional
# The name of the secret in Cloud Secret Manager. By default, the secret is
# assumed to be in the same project. If the secret is in another project, you
# must define an alias. An alias definition has the form: :projects//secrets/.
# If multiple alias definitions are needed, they must be separated by commas.
# The alias definitions must be set on the run.googleapis.com/secrets annotation.
# Name of the secret in the container's namespace to use.
# Corresponds to the JSON property `secretName`
# @return [String]
attr_accessor :secret_name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@default_mode = args[:default_mode] if args.key?(:default_mode)
@items = args[:items] if args.key?(:items)
@optional = args[:optional] if args.key?(:optional)
@secret_name = args[:secret_name] if args.key?(:secret_name)
end
end
# Not supported by Cloud Run SecurityContext holds security configuration that
# will be applied to a container. Some fields are present in both
# SecurityContext and PodSecurityContext. When both are set, the values in
# SecurityContext take precedence.
class SecurityContext
include Google::Apis::Core::Hashable
# (Optional) The UID to run the entrypoint of the container process. Defaults to
# user specified in image metadata if unspecified. May also be set in
# PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the
# value specified in SecurityContext takes precedence.
# Corresponds to the JSON property `runAsUser`
# @return [Fixnum]
attr_accessor :run_as_user
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@run_as_user = args[:run_as_user] if args.key?(:run_as_user)
end
end
# Not supported by Cloud Run TCPSocketAction describes an action based on
# opening a socket
class TcpSocketAction
include Google::Apis::Core::Hashable
# (Optional) Optional: Host name to connect to, defaults to the pod IP.
# Corresponds to the JSON property `host`
# @return [String]
attr_accessor :host
# Number or name of the port to access on the container. Number must be in the
# range 1 to 65535. Name must be an IANA_SVC_NAME. This field is currently
# limited to integer types only because of proto's inability to properly support
# the IntOrString golang type.
# Corresponds to the JSON property `port`
# @return [Fixnum]
attr_accessor :port
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@host = args[:host] if args.key?(:host)
@port = args[:port] if args.key?(:port)
end
end
# Volume represents a named volume in a container.
class Volume
include Google::Apis::Core::Hashable
# Not supported by Cloud Run Adapts a ConfigMap into a volume. The contents of
# the target ConfigMap's Data field will be presented in a volume as files using
# the keys in the Data field as the file names, unless the items element is
# populated with specific mappings of keys to paths.
# Corresponds to the JSON property `configMap`
# @return [Google::Apis::RunV1alpha1::ConfigMapVolumeSource]
attr_accessor :config_map
# Volume's name. In Cloud Run Fully Managed, the name 'cloudsql' is reserved.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# The secret's value will be presented as the content of a file whose name is
# defined in the item path. If no items are defined, the name of the file is the
# secret_name. The contents of the target Secret's Data field will be presented
# in a volume as files using the keys in the Data field as the file names.
# Corresponds to the JSON property `secret`
# @return [Google::Apis::RunV1alpha1::SecretVolumeSource]
attr_accessor :secret
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@config_map = args[:config_map] if args.key?(:config_map)
@name = args[:name] if args.key?(:name)
@secret = args[:secret] if args.key?(:secret)
end
end
# VolumeMount describes a mounting of a Volume within a container.
class VolumeMount
include Google::Apis::Core::Hashable
# Path within the container at which the volume should be mounted. Must not
# contain ':'.
# Corresponds to the JSON property `mountPath`
# @return [String]
attr_accessor :mount_path
# The name of the volume. There must be a corresponding Volume with the same
# name.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# (Optional) Only true is accepted. Defaults to true.
# Corresponds to the JSON property `readOnly`
# @return [Boolean]
attr_accessor :read_only
alias_method :read_only?, :read_only
# (Optional) Path within the volume from which the container's volume should be
# mounted. Defaults to "" (volume's root).
# Corresponds to the JSON property `subPath`
# @return [String]
attr_accessor :sub_path
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@mount_path = args[:mount_path] if args.key?(:mount_path)
@name = args[:name] if args.key?(:name)
@read_only = args[:read_only] if args.key?(:read_only)
@sub_path = args[:sub_path] if args.key?(:sub_path)
end
end
end
end
end
| 46.472497 | 133 | 0.644383 |
ed77482b31236b00ac7d97a9f6653cf0d5274073 | 844 | #
# Cookbook:: docker-engine
# Recipe:: config
#
# Copyright:: 2016 The 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.
directory '/etc/docker' do
owner 'root'
group 'root'
mode '0755'
end
file '/etc/docker/daemon.json' do
content lazy { node['docker-engine']['config'].to_json }
owner 'root'
group 'root'
mode '0640'
end
| 27.225806 | 74 | 0.727488 |
79220fbbd84cfdfa641b34aa557d8f9f2310d7ad | 1,270 | class Serd < Formula
desc "C library for RDF syntax"
homepage "https://drobilla.net/software/serd/"
url "https://download.drobilla.net/serd-0.30.10.tar.bz2"
sha256 "affa80deec78921f86335e6fc3f18b80aefecf424f6a5755e9f2fa0eb0710edf"
license "ISC"
livecheck do
url "https://download.drobilla.net/"
regex(/href=.*?serd[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
sha256 cellar: :any, arm64_big_sur: "10155eb151924f5fea4d02b197a5e08c5536340d9335329ce9d3dd6af3431a11"
sha256 cellar: :any, big_sur: "e28a02ac86a643e66e2d98fb2e22089f58071bd27faba353494ddc92f6823bfb"
sha256 cellar: :any, catalina: "b9b49fee3a281d23119785510ce19337a2eb9fea637583291651a44b27b4f15f"
sha256 cellar: :any, mojave: "b780e951258475391de8618edc7915c5f10ea8286769537743d703ed51318778"
end
depends_on "pkg-config" => :build
on_linux do
depends_on "[email protected]" => :build
end
def install
ENV.prepend_path "PATH", Formula["[email protected]"].opt_libexec/"bin" if OS.linux?
system "./waf", "configure", "--prefix=#{prefix}"
system "./waf"
system "./waf", "install"
end
test do
pipe_output("serdi -", "() a <http://example.org/List> .", 0)
end
end
| 34.324324 | 122 | 0.670866 |
ed9baa94364af1a45918df1a8ecf7cd2273ba761 | 8,267 | =begin
#Ory Kratos API
#Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the administative API port you should use something like Nginx, Ory Oathkeeper, or any other technology capable of authorizing incoming requests.
The version of the OpenAPI document: v0.10.1
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.4.0
=end
require 'date'
require 'time'
module OryKratosClient
# SubmitSelfServiceLoginFlowWithOidcMethodBody is used to decode the login form payload when using the oidc method.
class SubmitSelfServiceLoginFlowWithOidcMethodBody
# The CSRF Token
attr_accessor :csrf_token
# Method to use This field must be set to `oidc` when using the oidc method.
attr_accessor :method
# The provider to register with
attr_accessor :provider
# The identity traits. This is a placeholder for the registration flow.
attr_accessor :traits
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'csrf_token' => :'csrf_token',
:'method' => :'method',
:'provider' => :'provider',
:'traits' => :'traits'
}
end
# Returns all the JSON keys this model knows about
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
def self.openapi_types
{
:'csrf_token' => :'String',
:'method' => :'String',
:'provider' => :'String',
:'traits' => :'Object'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `OryKratosClient::SubmitSelfServiceLoginFlowWithOidcMethodBody` 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 `OryKratosClient::SubmitSelfServiceLoginFlowWithOidcMethodBody`. 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?(:'csrf_token')
self.csrf_token = attributes[:'csrf_token']
end
if attributes.key?(:'method')
self.method = attributes[:'method']
end
if attributes.key?(:'provider')
self.provider = attributes[:'provider']
end
if attributes.key?(:'traits')
self.traits = attributes[:'traits']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if @method.nil?
invalid_properties.push('invalid value for "method", method cannot be nil.')
end
if @provider.nil?
invalid_properties.push('invalid value for "provider", provider cannot be nil.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @method.nil?
return false if @provider.nil?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
csrf_token == o.csrf_token &&
method == o.method &&
provider == o.provider &&
traits == o.traits
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[csrf_token, method, provider, traits].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
elsif type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :Time
Time.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
# models (e.g. Pet) or oneOf
klass = OryKratosClient.const_get(type)
klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 31.67433 | 429 | 0.63699 |
f8cd2feb00156a930a36c17545d642b4ee59f71e | 1,432 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "googleauth"
module Google
module Cloud
module Dlp
module V2
class Credentials < Google::Auth::Credentials
SCOPE = [
"https://www.googleapis.com/auth/cloud-platform"
].freeze
PATH_ENV_VARS = %w(DLP_CREDENTIALS
DLP_KEYFILE
GOOGLE_CLOUD_CREDENTIALS
GOOGLE_CLOUD_KEYFILE
GCLOUD_KEYFILE)
JSON_ENV_VARS = %w(DLP_CREDENTIALS_JSON
DLP_KEYFILE_JSON
GOOGLE_CLOUD_CREDENTIALS_JSON
GOOGLE_CLOUD_KEYFILE_JSON
GCLOUD_KEYFILE_JSON)
DEFAULT_PATHS = ["~/.config/gcloud/application_default_credentials.json"]
end
end
end
end
end
| 34.095238 | 83 | 0.613128 |
f88010dc2f904e7bef2935efcbbe4d17671ea4e9 | 4,908 | describe "motion_print gem" do
it 'indents' do
MotionPrint.indent_by(0).should == ''
MotionPrint.indent_by(1).should == ' '
MotionPrint.indent_by(2).should == ' '
MotionPrint.indent_by(5).should == ' '
end
it 'picks a color based on a type symbol' do
MotionPrint.colors[:date].should == :greenish
MotionPrint.colors[:falseclass].should == :red
MotionPrint.colors[:float].should == :blue
MotionPrint.colors[:hash].should == :pale
MotionPrint.colors[:method].should == :purpleish
MotionPrint.colors[:nilclass].should == :red
MotionPrint.colors[:fixnum].should == :blue
end
it 'forces a color no matter the type' do
# Strings
MotionPrint.logger("String", force_color: :blue).should == "\e[1;34m\"String\"\e[0m"
MotionPrint.logger("String", force_color: :red).should == "\e[1;31m\"String\"\e[0m"
MotionPrint.logger("String", force_color: :none).should == "\"String\""
# Arrays
MotionPrint.logger([1, '2'], force_color: :purple).should == "[\n \e[1;35m1\e[0m,\n \e[1;35m\"2\"\e[0m\n]"
MotionPrint.logger([1, '2'], force_color: :none).should == "[\n 1,\n \"2\"\n]"
# Hashes
MotionPrint.logger({a: 'b', c: :d}, force_color: :white).should == "{\n \e[1;37m:a\e[0m \e[1;37m => \e[0m\e[1;37m\"b\"\e[0m,\n \e[1;37m:c\e[0m \e[1;37m => \e[0m\e[1;37m:d\e[0m\n}"
MotionPrint.logger({a: 'b', c: :d}, force_color: :none).should == "{\n :a => \"b\",\n :c => :d\n}"
# Symbols
MotionPrint.logger(:a_symbol, force_color: :green).should == "\e[1;32m:a_symbol\e[0m"
MotionPrint.logger(:a_symbol, force_color: :none).should == ":a_symbol"
end
it 'aligns strings properly' do
MotionPrint.align('RubyMotion', 0, 0).should == 'RubyMotion'
MotionPrint.align('RubyMotion', 5, 0).should == 'RubyMotion'
MotionPrint.align('RubyMotion', 20, 0).should == 'RubyMotion '
MotionPrint.align('RubyMotion', 20, 1).should == ' RubyMotion '
MotionPrint.align('RubyMotion', 20, 2).should == ' RubyMotion '
MotionPrint.align('RubyMotion', 20, 5).should == ' RubyMotion '
MotionPrint.align('RubyMotion', 5, 2).should == ' RubyMotion'
MotionPrint.align('RubyMotion', 0, 1).should == ' RubyMotion'
end
it 'outputs arrays properly' do
# Numbers
MotionPrint.logger([1, 2]).should == "[\n \e[1;34m1\e[0m,\n \e[1;34m2\e[0m\n]"
# Strings
MotionPrint.logger(['1', '2']).should == "[\n \e[0;33m\"1\"\e[0m,\n \e[0;33m\"2\"\e[0m\n]"
end
it 'outputs multidimensional arrays properly' do
# Numbers and Strings
MotionPrint.logger([1, 2, ['1', '2']]).should == "[\n \e[1;34m1\e[0m,\n \e[1;34m2\e[0m,\n [\n \e[0;33m\"1\"\e[0m,\n \e[0;33m\"2\"\e[0m\n ]\n]"
end
it 'outputs hashes properly' do
MotionPrint.logger({a: 'a', b: 2}).should == "{\n \e[0;36m:a\e[0m \e[0;36m => \e[0m\e[0;33m\"a\"\e[0m,\n \e[0;36m:b\e[0m \e[0;36m => \e[0m\e[1;34m2\e[0m\n}"
end
it 'outputs hashes with arrays properly' do
MotionPrint.logger({
a: 'a',
b: 2,
c: [
BigDecimal.new('4.4'),
12,
String
]
}).should == "{\n \e[0;36m:a\e[0m \e[0;36m => \e[0m\e[0;33m\"a\"\e[0m,\n \e[0;36m:b\e[0m \e[0;36m => \e[0m\e[1;34m2\e[0m,\n \e[0;36m:c\e[0m \e[0;36m => \e[0m[\n \e[1;34m4.4\e[0m,\n \e[1;34m12\e[0m,\n \e[1;33mString\e[0m\n ]\n}"
end
it 'outputs numbers correctly' do
MotionPrint.logger(42).should == "\e[1;34m42\e[0m"
end
it 'outputs classes correctly' do
MotionPrint.logger(Array).should == "\e[1;33mArray\e[0m"
end
it 'outputs symbols correctly' do
MotionPrint.logger(:symbol).should == "\e[0;36m:symbol\e[0m"
end
it 'outputs true/false correctly' do
MotionPrint.logger(true).should == "\e[1;32mtrue\e[0m"
MotionPrint.logger(false).should == "\e[1;31mfalse\e[0m"
end
it 'outputs string correctly' do
MotionPrint.logger('boo!').should == "\e[0;33m\"boo!\"\e[0m"
end
it 'outputs string with newlines correctly' do
MotionPrint.logger("a\nb\nc").should == "\e[0;33m\"a\\nb\\nc\"\e[0m"
end
it 'outputs string with newlines indented correctly' do
MotionPrint.logger(["a\nb\nc"], indent_level: 2).should == "[\n \e[0;33m\"a\\nb\\nc\"\e[0m\n ]"
end
it 'outputs instance variables properly' do
class Foo
attr_accessor :bar1
def initialize
@bar1, @bar2 = 1, 2
end
end
ivar = Foo.new
# MotionPrint.logger(ivar).should == "\e[1;33mFoo\e[0m\n \e[0;35m:@bar1\e[0m \e[0;36m => \e[0m\e[0;37m1\e[0m\n \e[0;36m:@bar2\e[0m \e[0;36m => \e[0m\e[0;37m2\e[0m\n"
MotionPrint.logger(ivar).start_with?("\e[1;33m#<Foo:0x").should == true
MotionPrint.logger(ivar).end_with?(">\e[0m\n \e[0;35m:@bar1\e[0m \e[0;36m => \e[0m\e[0;37m1\e[0m\n \e[0;36m:@bar2\e[0m \e[0;36m => \e[0m\e[0;37m2\e[0m\n").should == true
end
end
| 40.229508 | 247 | 0.593113 |
5daa712b318f565918c31a72f90a5bd53baaeea4 | 375 | module PostmanMta
class Tag < ApplicationModel
attr_reader :conversation_id
def initialize(conversation_id)
@conversation_id = conversation_id
end
def create(params)
post("/conversations/#{conversation_id}/tags", body: params)
end
def destroy(tag_id)
delete("/conversations/#{conversation_id}/tags/#{tag_id}")
end
end
end
| 20.833333 | 66 | 0.693333 |
f8b4c0a74e47045a107a5c4c9d81178026c6fea1 | 1,208 | module Tufy
class BuildIdSegment < BuildSegment
expects :raw_data
promises :transformed_data
REQUIRED_KEYS = [
:id_number,
:id_type,
]
executed do |ctx|
# ID Segment is not required.
# If ID type passed here does
# not exist, do not proceed.
# TODO: Testing
validate_presence_of_required_keys(ctx.raw_data, REQUIRED_KEYS)
if id_type_exists?(ctx.raw_data[:id_type])
ctx.transformed_data = transform(ctx).upcase
end
end
private
def self.transform(ctx)
ctx[:segment_tag] = Constants::SEGMENT_TAG
result = with(ctx).reduce(
Fields::BuildSegmentTagField,
Fields::Id::BuildIdNumberField,
Fields::Id::BuildIdTypeField,
)
result[:transformed_data]
end
def self.id_type_exists?(id_type)
Constants::ID_TYPES.include?(id_type)
end
module Constants
# tags
SEGMENT_TAG = "ID03I01"
ID_NUMBER_TAG = "01"
ID_TYPE_TAG = "02"
# id type constants
SSS = "SSS"
PP = "PP"
TIN = "TIN"
DL = "DL"
GSIS = "GSIS"
UMID = "UMID"
ID_TYPES = [SSS, PP, TIN, DL, GSIS, UMID]
end
end
end
| 20.827586 | 69 | 0.600166 |
abdd613f06008309f049a3c40144e0ec7ccfd4aa | 591 | require 'test_helper'
module Elastic
module Test
class WatcherStartTest < ::Test::Unit::TestCase
context "Watcher: Start" do
subject { FakeClient.new }
should "perform correct request" do
subject.expects(:perform_request).with do |method, url, params, body|
assert_equal 'PUT', method
assert_equal "/_watcher/_start", url
assert_equal Hash.new, params
assert_nil body
true
end.returns(FakeResponse.new)
subject.watcher.start
end
end
end
end
end
| 21.888889 | 79 | 0.598985 |
5de4e33cf372056b0080c01c899acd96714d4502 | 3,710 | # 常用命令:pod
# 本地 验证 podspec 文件:$ pod lib lint
# 本地&远程 验证 podspec 文件:$ pod spec lint
# 获取验证 podspec 文件时产生的详细信息:$ pod lib lint --verbose
# 移除验证 podspec 文件时产生的一般警告:$ pod lib lint --allow-warnings
# 第三方库的依赖中包含.a文件:$ pod lib lint --use-libraries
# 第三方库是私有库,需要添加源:$ pod lib lint --sources=https://github.com/CocoaPods/Specs.git,[第三方库源]
# 当前 podspec 文件验证:$ pod lib lint --sources=https://github.com/CocoaPods/Specs.git,https://github.com/aliyun/aliyun-specs.git,https://github.com/sinaweibosdk/weibo_ios_sdk.git --use-libraries --allow-warnings --verbose
# 添加&更新 私有repo 中的 podspec 文件:pod repo push [私有repo] [.podspec文件路径]
Pod::Spec.new do |s|
s.name = "XiaoFuTech-develop" # 项目名称
s.version = "1.0.3" # 版本号 与 你仓库的 标签号 对应
s.license = "MIT" # 开源证书
s.summary = "iOS 快捷开发工具包 XiaoFuTech.framework for Develop." # 项目简介
s.deprecated = false
s.homepage = "https://github.com/XiaoFuGenius/XiaoFuTech-develop" # 你的主页
s.source = { :git => "https://github.com/XiaoFuGenius/XiaoFuTech-develop.git", :tag => "#{s.version}" } # 你的仓库地址
s.requires_arc = true # 是否启用ARC
s.platform = :ios, "8.0" #平台及支持的最低版本
s.vendored_frameworks = "Frameworks/XiaoFuTech.framework" #第三方库依赖
s.frameworks = "UIKit", "Foundation" #支持的框架
# User
s.author = { "Raywf" => "https://github.com/XiaoFuGenius" } # 作者信息
s.social_media_url = "https://github.com/XiaoFuGenius" # 个人主页
# 子组件管理
s.default_subspec = ['Bugly']
# 自封装 快捷开发『XFRapidCoding』
# 自封装 用户权限『XFUserRightsPool』
# 第三方库封装『XF3rdEncapsulation』
# MJRefresh
# s.subspec 'MJRefresh' do |mj|
# mj.ios.deployment_target = '8.0'
# mj.source_files = 'CapacityExpansion/XF3rdEncapsulation/MJRefresh/*.{h,m}'
# mj.ios.vendored_frameworks = 'Frameworks/XiaoFuTech.framework'
# mj.dependency 'MJRefresh'
# end
# QQ_MTA
s.subspec 'QQ_MTA' do |mta|
mta.ios.deployment_target = '8.0'
mta.source_files = 'CapacityExpansion/XF3rdEncapsulation/QQ_MTA/*.{h,m}'
mta.dependency 'QQ_MTA/AutoTrack'
end
# Bugly
s.subspec 'Bugly' do |bugly|
bugly.ios.deployment_target = '8.0'
bugly.source_files = 'CapacityExpansion/XF3rdEncapsulation/Bugly/*.{h,m}'
bugly.dependency 'Bugly'
end
# AFNetworking
s.subspec 'AFNetworking' do |afNet|
afNet.ios.deployment_target = '8.0'
afNet.source_files = 'CapacityExpansion/XF3rdEncapsulation/AFNetworking/*.{h,m}'
afNet.ios.vendored_frameworks = 'Frameworks/XiaoFuTech.framework'
afNet.dependency 'AFNetworking', '~> 3.0'
end
# WechatOpenSDK
s.subspec 'WechatOpenSDK' do |wechat|
wechat.ios.deployment_target = '8.0'
wechat.source_files = 'CapacityExpansion/XF3rdEncapsulation/WechatOpenSDK/*.{h,m}'
wechat.ios.vendored_frameworks = 'Frameworks/XiaoFuTech.framework'
wechat.dependency 'XiaoFuTech-develop/AFNetworking'
wechat.dependency 'WechatOpenSDK'
end
# Weibo_SDK,source 'https://github.com/sinaweibosdk/weibo_ios_sdk.git'
s.subspec 'Weibo_SDK' do |weibo|
weibo.ios.deployment_target = '8.0'
weibo.source_files = 'CapacityExpansion/XF3rdEncapsulation/Weibo_SDK/*.{h,m}'
weibo.ios.vendored_frameworks = 'Frameworks/XiaoFuTech.framework'
weibo.dependency 'XiaoFuTech-develop/AFNetworking'
weibo.dependency 'Weibo_SDK'
end
# AlicloudPush,source 'https://github.com/aliyun/aliyun-specs.git'
s.subspec 'AlicloudPush' do |alicloudpush|
alicloudpush.ios.deployment_target = '8.0'
alicloudpush.source_files = 'CapacityExpansion/XF3rdEncapsulation/AlicloudPush/*.{h,m}'
alicloudpush.ios.vendored_frameworks = 'Frameworks/XiaoFuTech.framework'
alicloudpush.dependency 'AlicloudPush', '~> 1.9.8'
end
end | 38.645833 | 217 | 0.701887 |
bf14ff5ddee6b25390276d56f9620d969a521cc2 | 532 | cask :v1 => 'music-manager' do
version '1.0.104.6528'
sha256 'a1e4e48e008958f9a725bfee1e2d8360dc8efad38ef2532fc1b3e4b9c3df8f0d'
url "https://dl.google.com/dl/androidjumper/mac/#{version.sub(%r{^\d+\.\d+\.},'').gsub('.','')}/musicmanager.dmg"
homepage 'https://play.google.com/music/'
license :unknown
# Renamed for consistency: app name is different in the Finder and in a shell.
# Original discussion: https://github.com/caskroom/homebrew-cask/pull/4282
app 'MusicManager.app', :target => 'Music Manager.app'
end
| 40.923077 | 115 | 0.719925 |
033cc96efb3f6a54a62bdb08073f532d7704f671 | 7,211 | =begin
#Kubernetes
#No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.3
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.2.3
=end
require 'date'
module Kubernetes
# TokenReview attempts to authenticate a token to a known user. Note: TokenReview requests may be cached by the webhook token authenticator plugin in the kube-apiserver.
class V1TokenReview
# APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
attr_accessor :api_version
# Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
attr_accessor :kind
attr_accessor :metadata
# Spec holds information about the request being evaluated
attr_accessor :spec
# Status is filled in by the server and indicates whether the request can be authenticated.
attr_accessor :status
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'api_version' => :'apiVersion',
:'kind' => :'kind',
:'metadata' => :'metadata',
:'spec' => :'spec',
:'status' => :'status'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'api_version' => :'String',
:'kind' => :'String',
:'metadata' => :'V1ObjectMeta',
:'spec' => :'V1TokenReviewSpec',
:'status' => :'V1TokenReviewStatus'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
if attributes.has_key?(:'apiVersion')
self.api_version = attributes[:'apiVersion']
end
if attributes.has_key?(:'kind')
self.kind = attributes[:'kind']
end
if attributes.has_key?(:'metadata')
self.metadata = attributes[:'metadata']
end
if attributes.has_key?(:'spec')
self.spec = attributes[:'spec']
end
if attributes.has_key?(:'status')
self.status = attributes[:'status']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
def list_invalid_properties
invalid_properties = Array.new
if @spec.nil?
invalid_properties.push("invalid value for 'spec', spec cannot be nil.")
end
return invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @spec.nil?
return true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
api_version == o.api_version &&
kind == o.kind &&
metadata == o.metadata &&
spec == o.spec &&
status == o.status
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[api_version, kind, metadata, spec, status].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = Kubernetes.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map{ |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 30.816239 | 279 | 0.630426 |
3392fbca91ef13fac4c29733f0a757fefa23c7a2 | 2,857 | require 'project_wiki'
class Projects::WikisController < Projects::ApplicationController
before_filter :authorize_read_wiki!
before_filter :authorize_write_wiki!, only: [:edit, :create, :history]
before_filter :authorize_admin_wiki!, only: :destroy
before_filter :load_project_wiki
def pages
@wiki_pages = Kaminari.paginate_array(@project_wiki.pages).page(params[:page]).per(30)
end
def show
@page = @project_wiki.find_page(params[:id], params[:version_id])
if @page
render 'show'
elsif file = @project_wiki.find_file(params[:id], params[:version_id])
if file.on_disk?
send_file file.on_disk_path, disposition: 'inline'
else
send_data(
file.raw_data,
type: file.mime_type,
disposition: 'inline',
filename: file.name
)
end
else
return render('empty') unless can?(current_user, :write_wiki, @project)
@page = WikiPage.new(@project_wiki)
@page.title = params[:id]
render 'edit'
end
end
def edit
@page = @project_wiki.find_page(params[:id])
end
def update
@page = @project_wiki.find_page(params[:id])
return render('empty') unless can?(current_user, :write_wiki, @project)
if @page.update(content, format, message)
redirect_to [@project.namespace.becomes(Namespace), @project, @page], notice: 'Wiki was successfully updated.'
else
render 'edit'
end
end
def create
@page = WikiPage.new(@project_wiki)
if @page.create(wiki_params)
redirect_to(
namespace_project_wiki_path(@project.namespace, @project, @page),
notice: 'Wiki was successfully updated.'
)
else
render action: "edit"
end
end
def history
@page = @project_wiki.find_page(params[:id])
unless @page
redirect_to(
namespace_project_wiki_path(@project.namespace, @project, :home),
notice: "Page not found"
)
end
end
def destroy
@page = @project_wiki.find_page(params[:id])
@page.delete if @page
redirect_to(
namespace_project_wiki_path(@project.namespace, @project, :home),
notice: "Page was successfully deleted"
)
end
def git_access
end
private
def load_project_wiki
@project_wiki = ProjectWiki.new(@project, current_user)
# Call #wiki to make sure the Wiki Repo is initialized
@project_wiki.wiki
rescue ProjectWiki::CouldNotCreateWikiError => ex
flash[:notice] = "Could not create Wiki Repository at this time. Please try again later."
redirect_to project_path(@project)
return false
end
def wiki_params
params[:wiki].slice(:title, :content, :format, :message)
end
def content
params[:wiki][:content]
end
def format
params[:wiki][:format]
end
def message
params[:wiki][:message]
end
end
| 23.808333 | 116 | 0.665733 |
bb4c4a6bf9f3b4ca1c17ba6fd196af41036e6201 | 167 | class HomeController < ApplicationController
skip_after_action :verify_authorized, :verify_policy_scoped
def index
@answer = Question.random&.answer
end
end
| 23.857143 | 61 | 0.802395 |
ed52cfbe5062ac046e99e7ae8734be3eb2104635 | 223 | class AddCompanyAndDesignationToUsers < ActiveRecord::Migration[5.1]
def change
add_column :users, :company, :string
add_column :users, :designation, :string
add_column :users, :is_contact, :boolean
end
end
| 27.875 | 68 | 0.744395 |
6a8cb7ac924d7eddf8fdfd3310b014fcf0fc23ae | 256 | require 'rubygems'
require 'spec'
require 'fakeweb'
FakeWeb.allow_net_connect = false
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'focus'
Spec::Runner.configure do |config|
end | 19.692308 | 66 | 0.75 |
0881c692ae80a400b47a42d1815257cedb46cd07 | 46 | class MainController < Ramaze::Controller
end
| 15.333333 | 41 | 0.826087 |
79aae2ef9503ea3b56c910b5e26b33d6f33db6e0 | 287 | # frozen_string_literal: true
module V1
module Stories
class FindRepository
def initialize(id)
@id = id
end
def find
Story.find_by!(id: @id)
rescue ActiveRecord::RecordNotFound => e
{ error: e.message }
end
end
end
end
| 15.944444 | 46 | 0.585366 |
28fa2bb9fe3c84a0e30f179ab360660fa1851ea7 | 250 | module Travis::API::V3
class Services::Plans::All < Service
params :organization_id
def run!
raise LoginRequired unless access_control.full_access_or_logged_in?
result query(:plans).all(access_control.user.id)
end
end
end
| 25 | 73 | 0.728 |
7920b654655d4cfca1b23a0ede5456920097fe6c | 141 | class AddIsDegreeToCourses < ActiveRecord::Migration
def change
add_column :courses, :is_degree, :boolean, :default => false
end
end
| 23.5 | 64 | 0.751773 |
e85a3ba3fb389b144a32af15040663bbc371d24e | 2,182 | class NodeAT10 < Formula
desc "Platform built on V8 to build network applications"
homepage "https://nodejs.org/"
url "https://nodejs.org/dist/v10.19.0/node-v10.19.0.tar.gz"
sha256 "db85b9992f1ec66629731d82f690987883dd2989abb4cc136eb65dd720b1bda8"
bottle do
cellar :any
sha256 "2340eeada3e44d29f118f7d7381f6c1bc1c6c58dbf246cff7d83a88346f2d93f" => :catalina
sha256 "021c43ebaa85ac1d763fa453e98b5f9bfff750b032fdc2b627f545fcd18247a1" => :mojave
sha256 "80138dde9c1c0b7f1b0dfb6ce7c209d7dac07f4dae37d2b2e398f6018ae3c56f" => :high_sierra
end
keg_only :versioned_formula
depends_on "pkg-config" => :build
depends_on "icu4c"
# Will not work with Python 3 without extensive patching. Node 10 will be EOL April 2021
uses_from_macos "python@2" => :build
def install
system "./configure", "--prefix=#{prefix}", "--with-intl=system-icu"
system "make", "install"
end
def post_install
(lib/"node_modules/npm/npmrc").atomic_write("prefix = #{HOMEBREW_PREFIX}\n")
end
test do
path = testpath/"test.js"
path.write "console.log('hello');"
output = shell_output("#{bin}/node #{path}").strip
assert_equal "hello", output
output = shell_output("#{bin}/node -e 'console.log(new Intl.NumberFormat(\"en-EN\").format(1234.56))'").strip
assert_equal "1,234.56", output
output = shell_output("#{bin}/node -e 'console.log(new Intl.NumberFormat(\"de-DE\").format(1234.56))'").strip
assert_equal "1.234,56", output
# make sure npm can find node
ENV.prepend_path "PATH", opt_bin
ENV.delete "NVM_NODEJS_ORG_MIRROR"
assert_equal which("node"), opt_bin/"node"
assert_predicate bin/"npm", :exist?, "npm must exist"
assert_predicate bin/"npm", :executable?, "npm must be executable"
npm_args = ["-ddd", "--cache=#{HOMEBREW_CACHE}/npm_cache", "--build-from-source"]
system "#{bin}/npm", *npm_args, "install", "npm@latest"
system "#{bin}/npm", *npm_args, "install", "bignum"
assert_predicate bin/"npx", :exist?, "npx must exist"
assert_predicate bin/"npx", :executable?, "npx must be executable"
assert_match "< hello >", shell_output("#{bin}/npx cowsay hello")
end
end
| 38.964286 | 113 | 0.703941 |
6afa2736e6d8fa2fa1c2bd44f82731cbc5704be7 | 652 | # Copyright (c) 2010, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3 or later. See
# the COPYRIGHT file.
require 'spec_helper'
describe Job::Mail::Mentioned do
describe '#perfom' do
it 'should call .deliver on the notifier object' do
user = alice
sm = Factory(:status_message)
m = Mention.new(:person => user.person, :post=> sm)
mail_mock = mock()
mail_mock.should_receive(:deliver)
Notifier.should_receive(:mentioned).with(user.id, sm.author.id, m.id).and_return(mail_mock)
Job::Mail::Mentioned.perform(user.id, sm.author.id, m.id)
end
end
end
| 29.636364 | 97 | 0.679448 |
21da5c33fe02c5675ce006845610fdd6b4c5c65c | 221 | # This flow is used to test custom test method API
Flow.create interface: 'OrigenTesters::Test::CustomTestInterface' do
custom :test1, number: 30000
custom :test2, number: 30010
custom :test3, number: 30020
end
| 20.090909 | 68 | 0.746606 |
ffe14d4f9d135cf6b70884692fec05638c24f9d6 | 1,829 | # frozen_string_literal: true
# Robot package to run under multiplexing infrastructure
module Robots
# Use DorRepo/SdrRepo to match the workflow repo (and avoid name collision with Dor module)
module SdrRepo
# The workflow package name - match the actual workflow name, minus ending WF (using CamelCase)
module PreservationIngest
# Clean up workspace; transfer control back to accessioning by updating accessionWF sdr-ingest-received step
class CompleteIngest < Base
ROBOT_NAME = 'complete-ingest'
def initialize
super(WORKFLOW_NAME, ROBOT_NAME)
end
def perform(druid)
LyberCore::Log.debug("#{ROBOT_NAME} #{druid} starting")
@druid = druid # for base class attr_accessor
complete_ingest
end
private
def complete_ingest
# common_accessioning workflow blocks after it queues up preservation workflow for object
# until it receives this signal
update_accession_workflow
end
def update_accession_workflow
workflow_service.update_status(druid: druid,
workflow: 'accessionWF',
process: 'sdr-ingest-received',
status: 'completed',
elapsed: 1,
note: "#{WORKFLOW_NAME} completed on #{Socket.gethostname}")
rescue Dor::WorkflowException => e
errmsg = "Error completing ingest for #{druid}: failed to update " \
"accessionWF:sdr-ingest-received to completed: #{e.message}\n#{e.backtrace.join('\n')}"
LyberCore::Log.error(errmsg)
raise(ItemError, errmsg)
end
end
end
end
end
| 38.104167 | 114 | 0.595954 |
5d10bb925ee15978f7ad5cd69975e957e53f118b | 1,614 | class Api::CodeCategoriesController < Api::BaseController
before_action :set_category, except: %i[create index]
swagger_controller :codes, 'Type de codes des établissements'
swagger_api :index do
summary 'Returns all code categories'
notes 'Tous les types de codes'
end
swagger_api :create do
summary 'Create a code category'
notes 'Créer un type de code'
param :query, :title, :string, :required, 'Title'
end
swagger_api :show do
summary 'Show a code category'
notes 'Afficher un type de code'
param :query, :code_category_id, :integer, :required, 'Code category ID'
end
swagger_api :update do
summary 'Update a code category'
notes 'Mettre à jour un type de code'
param :query, :code_category_id, :integer, :required, 'Code category ID'
end
swagger_api :destroy do
summary 'Delete a code category'
notes 'Effacer un type de code'
param :query, :code_category_id, :integer, :required, 'Code category ID'
end
def create
@category = CodeCategory.create!(code_category_params)
respond_with @category
end
def show
respond_with @category
end
def update
@category.update!(code_category_params)
respond_with @category
end
def destroy
@category.destroy
render json: { message: 'Code Category deleted' }, status: 200
end
def index
@categories = CodeCategory.all
end
private
def set_category
@category = CodeCategory.find(params[:id])
return not_found unless @category
end
def code_category_params
params[:code_category].permit(:title, :position)
end
end
| 23.391304 | 76 | 0.707559 |
5dce8d4e21938ab9455d6acb4074e12b8194ce31 | 258 | require('rspec')
require('pg')
require('stylist')
require('client')
DB = PG.connect({:dbname => 'hair_salon_test'})
RSpec.configure do |config|
config.after(:each) do
DB.exec("DELETE FROM clients *;")
DB.exec("DELETE FROM stylists *;")
end
end
| 18.428571 | 47 | 0.666667 |
01c72b20dadec42b81ba272b5339820c12f2d7c8 | 1,179 | describe HubEdos::V1::Contacts do
context 'mock proxy' do
before(:each) do
allow(Settings.terms).to receive(:fake_now).and_return('2017-11-07 00:00:00')
end
let(:proxy) { HubEdos::V1::Contacts.new(fake: true, user_id: '61889') }
subject { proxy.get }
it_behaves_like 'a proxy that properly observes the profile feature flag'
it_should_behave_like 'a simple proxy that returns errors'
it 'returns data with the expected structure' do
expect(subject[:feed]['student']).to be
expect(subject[:feed]['student']['identifiers'][0]['type']).to be
expect(subject[:feed]['student']['addresses'][0]['state']).to eq 'CA'
expect(subject[:feed]['student']['addresses'][0]['postal']).to eq '94708'
expect(subject[:feed]['student']['addresses'][0]['country']).to eq 'USA'
expect(subject[:feed]['student']['addresses'][0]['formattedAddress']).to eq "1234 56TH ST\nAPT 789, BOX 101112\nBERKELEY, California 94708"
expect(subject[:feed]['student']['phones'].length).to eq 1
end
it 'properly removes inactive addresses' do
expect(subject[:feed]['student']['addresses'].length).to eq 2
end
end
end
| 42.107143 | 145 | 0.66497 |
bf49fdc5054fa7e216f7f4275a16062b5cbbb74b | 2,646 | #-- encoding: UTF-8
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
describe Queries::Relations::Filters::FromFilter, type: :model do
include_context 'filter tests'
let(:values) { ['1'] }
let(:model) { Relation }
let(:current_user) { FactoryBot.build_stubbed(:user) }
it_behaves_like 'basic query filter' do
let(:class_key) { :from_id }
let(:type) { :integer }
# The name is not very good but as long as the filter is not displayed in the UI ...
let(:human_name) { 'Work package' }
describe '#allowed_values' do
it 'is nil' do
expect(instance.allowed_values).to be_nil
end
end
end
describe '#visibility_checked?' do
it 'is true' do
expect(instance).to be_visibility_checked
end
end
describe '#scope' do
before do
login_as(current_user)
end
let(:visible_sql) { WorkPackage.visible(current_user).select(:id).to_sql }
context 'for "="' do
let(:operator) { '=' }
it 'is the same as handwriting the query' do
expected = model.where("from_id IN ('1') AND to_id IN (#{visible_sql})")
expect(instance.scope.to_sql).to eql expected.to_sql
end
end
context 'for "!"' do
let(:operator) { '!' }
it 'is the same as handwriting the query' do
expected = model.where("from_id NOT IN ('1') AND to_id IN (#{visible_sql})")
expect(instance.scope.to_sql).to eql expected.to_sql
end
end
end
end
| 31.129412 | 91 | 0.692744 |
385dbde9c389795300acfd610fdae3f9f82d22d3 | 2,657 | class Libtorch < Formula
include Language::Python::Virtualenv
desc "Tensors and dynamic neural networks"
homepage "https://pytorch.org/"
url "https://github.com/pytorch/pytorch.git",
tag: "v1.9.0",
revision: "d69c22dd61a2f006dcfe1e3ea8468a3ecaf931aa"
license "BSD-3-Clause"
livecheck do
url :stable
strategy :github_latest
end
bottle do
sha256 cellar: :any, big_sur: "a51bfd1cc532abeabea070676f04ef4650fd087371307fabc8ffac3a7b212d30"
sha256 cellar: :any, catalina: "ca0ddb068dd09872cfe9f7bcfdb264fd01a61347dba7660eecab45840535ad53"
sha256 cellar: :any, mojave: "3e9191a6c5dcc80856aded5542387830bfcf6c6047790775b51e901324e37494"
end
depends_on "cmake" => :build
depends_on "[email protected]" => :build
depends_on "eigen"
depends_on "libomp"
depends_on "libyaml"
depends_on "protobuf"
depends_on "pybind11"
resource "PyYAML" do
url "https://files.pythonhosted.org/packages/a0/a4/d63f2d7597e1a4b55aa3b4d6c5b029991d3b824b5bd331af8d4ab1ed687d/PyYAML-5.4.1.tar.gz"
sha256 "607774cbba28732bfa802b54baa7484215f530991055bb562efbed5b2f20a45e"
end
resource "typing-extensions" do
url "https://files.pythonhosted.org/packages/aa/55/62e2d4934c282a60b4243a950c9dbfa01ae7cac0e8d6c0b5315b87432c81/typing_extensions-3.10.0.0.tar.gz"
sha256 "50b6f157849174217d0656f99dc82fe932884fb250826c18350e159ec6cdf342"
end
def install
venv = virtualenv_create(buildpath/"venv", Formula["[email protected]"].opt_bin/"python3")
venv.pip_install resources
args = %W[
-DBUILD_CUSTOM_PROTOBUF=OFF
-DBUILD_PYTHON=OFF
-DPYTHON_EXECUTABLE=#{buildpath}/venv/bin/python
-Dpybind11_PREFER_third_party=OFF
-DUSE_CUDA=OFF
-DUSE_METAL=OFF
-DUSE_MKLDNN=OFF
-DUSE_NNPACK=OFF
-DUSE_OPENMP=OFF
-DUSE_SYSTEM_EIGEN_INSTALL=ON
]
mkdir "build" do
system "cmake", "..", *std_cmake_args, *args
# Avoid references to Homebrew shims
inreplace "caffe2/core/macros.h", %r{#{HOMEBREW_SHIMS_PATH}/[^/]+/super/#{Regexp.escape(ENV.cxx)}}, ENV.cxx
system "make"
system "make", "install"
end
end
test do
(testpath/"test.cpp").write <<~EOS
#include <torch/torch.h>
#include <iostream>
int main() {
torch::Tensor tensor = torch::rand({2, 3});
std::cout << tensor << std::endl;
}
EOS
system ENV.cxx, "-std=c++14", "test.cpp", "-o", "test",
"-I#{include}/torch/csrc/api/include",
"-L#{lib}", "-ltorch", "-ltorch_cpu", "-lc10"
system "./test"
end
end
| 31.630952 | 150 | 0.672939 |
1140d07cc87105a8be0eb9de020468f8e0ae5b67 | 363 | module Formtastic
module Inputs
class TimeInput < TimeSelectInput
def to_html
::ActiveSupport::Deprecation.warn("TimeInput (:as => :time) has been renamed to TimeSelectInput (:as => :time_select) and will be removed or changed in the next version of Formtastic, please update your forms.", caller(2))
super
end
end
end
end
| 33 | 230 | 0.694215 |
5d6d48a47e6fb2194df4845fc46bbf6a66ff5646 | 719 | require 'sinatra/base'
class Contracto::Server < Sinatra::Base
contract_files = Dir["#{Contracto::Config.root_dir}/**/*.contract.json"]
if contract_files.empty?
puts "warning: no contracts found in #{Contracto::Config.root_dir}, create some *.contract.json files"
end
Contracto::Parser.new(contract_files).contracts.each do |contract|
send(contract.http_method, contract.url_pattern) do
contract_response = contract.response(params, http_headers)
headers['contract-filename'] = contract.filename
headers['contract-example-path'] = contract_response.body_path
contract_response.body
end
end
def http_headers
env.select {|k,v| k.start_with? 'HTTP_'}
end
end
| 25.678571 | 106 | 0.723227 |
4ac64947c8d0d41da48efcc00ffefd293c7ed44e | 155 | require 'test_helper'
describe Redis::ActionPack::VERSION do
it "must be equal to 4.0.0" do
Redis::ActionPack::VERSION.must_equal '4.0.0'
end
end
| 19.375 | 49 | 0.716129 |
91904e1ee14bc43c8290f53251d3e757c4cf8e99 | 2,740 | require 'uri'
require 'openssl'
require 'rest-client'
require 'json'
require 'yaml'
module QQpush
# General REST API
class General
attr_accessor :settings, :request_params
PROTOCAL = 'http'
ROOT_URL = 'openapi.xg.qq.com'
VERSION = 'v2'
SERVICES = { push: %w(single_device single_account
account_list all_device tags_device) }
SERVICES.each do |param_class, param_methods|
param_methods.each do |param_method|
define_method("#{param_class}_#{param_method}") do |params = {}|
params = request_params unless params.any?
params[:param_request] = 'get'
request(
params.merge(param_class: param_class,
param_method: param_method))
end
end
end
def initialize(params = {})
@settings =
File.exist?('settings.yml') ? YAML.load_file('settings.yml') : {}
@request_params = params
end
def request(params = {})
response = RestClient.send(
params[:param_request], request_url(params))
JSON.parse response
end
def request_url(params)
params[:param_encode] = true
all_params = params.merge(general_params(params))
"#{PROTOCAL}://#{ROOT_URL}/#{VERSION}/#{params[:param_class]}/" \
"#{params[:param_method]}?#{params_string(all_params).gsub(/\&$/, '')}"
end
def general_params(params)
base_params = { access_id: settings[:access_id],
timestamp: params[:timestamp],
valid_time: params[:valid_time] }
base_params[:timestamp] ||= Time.now.to_i
all_params = params.merge base_params
base_params.merge(sign: param_sign(all_params))
end
def param_sign(params)
params.delete(:param_encode)
sign_string = "#{params[:param_request].upcase}" \
"#{ROOT_URL}/#{VERSION}/#{params[:param_class]}/" \
"#{params[:param_method]}#{params_string(params)}" \
"#{settings[:secret_key]}"
OpenSSL::Digest::MD5.new(sign_string).to_s
end
private
def params_string(params)
new_string = ''
business_params_string_keys(params).each do |key|
next unless params[key] || params[key.to_sym]
value = [params[key], params[key.to_sym]].compact.first
value = param_string_value(value)
new_value = params[:param_encode] ? "#{URI.encode(value)}&" : value
new_string += "#{key}=#{new_value}"
end
new_string
end
def business_params_string_keys(params)
params.reject { |k, _v| k.to_s =~ /param_.*/ }.keys.map(&:to_s).sort
end
def param_string_value(value)
value.is_a?(Hash) ? value.to_json : value.to_s
end
end
end
| 30.444444 | 77 | 0.617153 |
18f2a0b4650a3a73c4248db7e19ccad5aa13c9fa | 632 | # This class represents a file upload field found in a form. To use this
# class, set FileUpload#file_data= to the data of the file you want to upload
# and FileUpload#mime_type= to the appropriate mime type of the file.
#
# See the example in EXAMPLES
class Mechanize::Form::FileUpload < Mechanize::Form::Field
attr_accessor :file_name # File name
attr_accessor :mime_type # Mime Type (Optional)
alias :file_data :value
alias :file_data= :value=
def initialize node, file_name
@file_name = Mechanize::Util.html_unescape(file_name)
@file_data = nil
@node = node
super(node, @file_data)
end
end
| 28.727273 | 77 | 0.727848 |
7a0c3742e43dc5bacbb28345dd75b02229640a75 | 375 | class PerformersController < ApplicationController
def show
@performer = Performer.find(params[:performer_id])
respond_to do |format|
format.html do
@user = @performer
render 'users/show'
end
format.json {render json: @performer}
end
end
def search
render json: Performer.search(params["term"]), root: false
end
end | 22.058824 | 62 | 0.661333 |
79e5743f7841a96497e35eb806f9e9d601a08cc6 | 464 | # frozen_string_literal: true
require_relative '../stock'
module Engine
module Round
module G1828
class Stock < Stock
def finish_round
@game.corporations.select(&:floated?).sort.each do |corp|
@game.stock_market.move_up(corp) if corp.share_price.type == :unlimited
@game.stock_market.move_up(corp) if corp.owner.num_shares_of(corp) >= 8
end
super
end
end
end
end
end
| 22.095238 | 83 | 0.622845 |
5d8e3eeee92677eea9585f545a15f4ef9cb6bb29 | 2,143 | class Diffoscope < Formula
desc "In-depth comparison of files, archives, and directories."
homepage "https://diffoscope.org"
url "https://files.pythonhosted.org/packages/72/76/5c44c30c4ab43f4f711941a3e89aff8157d51238db3457a1f7adfe89cb56/diffoscope-84.tar.gz"
sha256 "7a8e6a2bd3562fa650cad90f4c9a3ec9b070d5a2e55d437f5f28a8a07aecd53f"
bottle do
cellar :any_skip_relocation
sha256 "aebd26ee5e903380ef3c160de1d7bba026830ff32948fe7b5f6c4f469b33dc6b" => :sierra
sha256 "aebd26ee5e903380ef3c160de1d7bba026830ff32948fe7b5f6c4f469b33dc6b" => :el_capitan
sha256 "aebd26ee5e903380ef3c160de1d7bba026830ff32948fe7b5f6c4f469b33dc6b" => :yosemite
end
depends_on "libmagic"
depends_on "libarchive"
depends_on "gnu-tar"
depends_on :python3
resource "libarchive-c" do
url "https://files.pythonhosted.org/packages/1f/4a/7421e8db5c7509cf75e34b92a32b69c506f2b6f6392a909c2f87f3e94ad2/libarchive-c-2.7.tar.gz"
sha256 "56eadbc383c27ec9cf6aad3ead72265e70f80fa474b20944328db38bab762b04"
end
resource "python-magic" do
url "https://files.pythonhosted.org/packages/65/0b/c6b31f686420420b5a16b24a722fe980724b28d76f65601c9bc324f08d02/python-magic-0.4.13.tar.gz"
sha256 "604eace6f665809bebbb07070508dfa8cabb2d7cb05be9a56706c60f864f1289"
end
def install
pyver = Language::Python.major_minor_version "python3"
ENV.prepend_create_path "PYTHONPATH", libexec/"vendor/lib/python#{pyver}/site-packages"
resources.each do |r|
r.stage do
system "python3", *Language::Python.setup_install_args(libexec/"vendor")
end
end
ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python#{pyver}/site-packages"
system "python3", *Language::Python.setup_install_args(libexec)
bin.install Dir[libexec/"bin/*"]
libarchive = Formula["libarchive"].opt_lib/"libarchive.dylib"
bin.env_script_all_files(libexec+"bin", :PYTHONPATH => ENV["PYTHONPATH"],
:LIBARCHIVE => libarchive)
end
test do
(testpath/"test1").write "test"
cp testpath/"test1", testpath/"test2"
system "#{bin}/diffoscope", "test1", "test2"
end
end
| 40.433962 | 143 | 0.758283 |
accb0ffb7378d11b530613cc616009d3101d9e03 | 4,111 | # Copyright (c) 2009-2012 VMware, Inc.
require_relative '../../spec/support/deployments'
Sham.define do
name { |index| "name-#{index}" }
username { |index| "username-#{index}" }
password { |index| "password-#{index}" }
version { |index| "version-#{index}" }
manifest { |index| "manifest-#{index}" }
job { |index| "job-#{index}"}
vm_cid { |index| "vm-cid-#{index}" }
disk_cid { |index| "disk-cid-#{index}" }
snapshot_cid { |index| "snapshot-cid-#{index}" }
stemcell_cid { |index| "stemcell-cid-#{index}" }
blobstore_id { |index| "blobstore-id-#{index}" }
agent_id { |index| "agent-id-#{index}" }
index { |index| index }
description { |index| "description #{index}" }
type { |index| "type #{index}" }
sha1 { |index| "sha1-#{index}" }
build { |index| index }
ip { |index|
octet = index % 255
"#{octet}.#{octet}.#{octet}.#{octet}"
}
ptr { |index|
octet = index % 255
"#{octet}.#{octet}.#{octet}.in-addr.arpa"
}
end
module Bosh::Director::Models
Release.blueprint do
name { Sham.name }
end
ReleaseVersion.blueprint do
release { Release.make }
version { Sham.version }
end
Package.blueprint do
release { Release.make }
name { Sham.name }
version { Sham.version }
blobstore_id { Sham.blobstore_id }
sha1 { Sham.sha1 }
dependency_set_json { "[]" }
end
Template.blueprint do
release
name { Sham.name }
version { Sham.version }
blobstore_id { Sham.blobstore_id }
sha1 { Sham.sha1 }
package_names_json { "[]" }
end
Stemcell.blueprint do
name { Sham.name }
version { Sham.version }
cid { Sham.stemcell_cid }
end
CompiledPackage.blueprint do
package { Package.make }
stemcell { Stemcell.make }
build { Sham.build }
blobstore_id { Sham.blobstore_id }
sha1 { Sham.sha1 }
dependency_key { "[]" }
end
Deployment.blueprint do
name { Sham.name }
manifest { Sham.manifest }
end
Vm.blueprint do
deployment { Deployment.make }
agent_id { Sham.agent_id }
cid { Sham.vm_cid }
end
Instance.blueprint do
deployment { Deployment.make }
job { Sham.job }
index { Sham.index }
vm { Vm.make }
state { "started" }
end
Task.blueprint do
state { "queued" }
type { Sham.type }
timestamp { Time.now }
description { Sham.description }
result { nil }
output { nil }
end
User.blueprint do
username { Sham.username }
password { Sham.password }
end
PersistentDisk.blueprint do
active { true }
disk_cid { Sham.disk_cid }
instance { Instance.make }
end
Snapshot.blueprint do
persistent_disk { PersistentDisk.make }
snapshot_cid { Sham.snapshot_cid }
end
DeploymentProblem.blueprint do
deployment { Deployment.make }
type { "inactive_disk" }
resource_id { PersistentDisk.make.id }
data_json { "{}" }
state { "open" }
end
RenderedTemplatesArchive.blueprint do
instance { Instance.make }
blobstore_id { Sham.blobstore_id }
sha1 { Sham.sha1 }
content_sha1 { Sham.sha1 }
created_at { Time.now }
end
CloudConfig.blueprint do
manifest { Bosh::Spec::Deployments.simple_cloud_config }
end
module Dns
Domain.blueprint do
name { Sham.name }
type { "NATIVE" }
end
Record.blueprint do
domain { Domain.make }
name { Sham.name }
type { "A" }
content { Sham.ip }
end
Record.blueprint(:PTR) do
domain { Domain.make }
name { Sham.ptr }
type { "PTR" }
content { Sham.name }
end
end
end
| 25.534161 | 60 | 0.535879 |
d5a5248633ed19fb43f69ca1169d78fa9e0911e2 | 1,433 | ENV["MITTSU_ENV"] = 'test'
require 'pry'
require 'simplecov'
require 'coveralls'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
Coveralls::SimpleCov::Formatter,
SimpleCov::Formatter::HTMLFormatter
]
SimpleCov.start do
add_filter "/test/"
add_group 'Cameras', 'lib/mittsu/cameras'
add_group 'Core', 'lib/mittsu/core'
add_group 'Extras', 'lib/mittsu/extras'
add_group 'Lights', 'lib/mittsu/lights'
add_group 'Loaders', 'lib/mittsu/loaders'
add_group 'Materials', 'lib/mittsu/materials'
add_group 'Math', 'lib/mittsu/math'
add_group 'Objects', 'lib/mittsu/objects'
add_group 'Renderers', 'lib/mittsu/renderers'
add_group 'Scenes', 'lib/mittsu/scenes'
add_group 'Textures', 'lib/mittsu/textures'
end
require "minitest/reporters"
REPORTER = "#{ENV['MINITEST_REPORTER'] || 'Progress'}Reporter"
if !Minitest::Reporters.const_defined?(REPORTER)
puts "WARNING: Reporter \"#{REPORTER}\" not found, using default"
Minitest::Reporters.use!
else
Minitest::Reporters.use! Minitest::Reporters.const_get(REPORTER).new
end
$LOAD_PATH.unshift File.expand_path('../lib', __dir__)
require 'minitest'
Dir[__dir__ + '/support/*.rb'].each {|file| require file }
require 'mittsu'
class Minitest::Test
def assert_color_equal expected, actual
assert_in_delta expected.r, actual.r
assert_in_delta expected.g, actual.g
assert_in_delta expected.b, actual.b
end
end
require 'minitest/autorun'
| 28.66 | 70 | 0.7418 |
91c19ab151b4f5a1fecdc5cc704b249cc5149431 | 1,689 | cask "sublime-text" do
version "4.107"
sha256 "5da344779f92c7eb3ac279a6b3cc8810e86480b3e71fba79d8e09e94a3631602"
url "https://download.sublimetext.com/sublime_text_build_#{version.no_dots}_mac.zip"
name "Sublime Text"
desc "Text editor for code, markup and prose"
homepage "https://www.sublimetext.com/"
livecheck do
url "https://www.sublimetext.com/download"
regex(/href=.*?v?(\d+)_mac\.zip/i)
strategy :page_match do |page, regex|
match = page.match(regex)[1]
"#{match[0]}.#{match[1..]}"
end
end
auto_updates true
conflicts_with cask: "sublime-text-dev"
app "Sublime Text.app"
binary "#{appdir}/Sublime Text.app/Contents/SharedSupport/bin/subl"
uninstall quit: "com.sublimetext.#{version.major}"
# Sublime Text 4 uses `Sublime Text 3` and `com.sublimetext.3` dirs if they exist
# Otherwise, it creates `Sublime Text` and `com.sublimetext.4`
# More info: https://www.sublimetext.com/docs/side_by_side.html
zap trash: [
"~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.sublimetext.#{version.major}.sfl*",
"~/Library/Application Support/Sublime Text",
"~/Library/Application Support/Sublime Text (Safe Mode)",
"~/Library/Application Support/Sublime Text 3",
"~/Library/Caches/com.sublimetext.#{version.major}",
"~/Library/Caches/com.sublimetext.3",
"~/Library/Preferences/com.sublimetext.#{version.major}.plist",
"~/Library/Preferences/com.sublimetext.3.plist",
"~/Library/Saved Application State/com.sublimetext.#{version.major}.savedState",
"~/Library/Saved Application State/com.sublimetext.3.savedState",
]
end
| 39.27907 | 153 | 0.721729 |
62a75111c5e33e8fe06df777b521041475a657f3 | 379 | cask :v1 => 'font-sniglet' do
# version '2.000'
version :latest
sha256 :no_check
url 'https://github.com/w0ng/googlefontdirectory/trunk/fonts/sniglet',
:using => :svn,
:revision => '50',
:trust_cert => true
homepage 'http://www.google.com/fonts/specimen/Sniglet'
license :ofl
font 'Sniglet-ExtraBold.ttf'
font 'Sniglet-Regular.ttf'
end
| 23.6875 | 72 | 0.651715 |
e8dbde176efaec9a610c20e843f90511b9d67ebc | 5,931 | # Module providing methods for dealing with separating a tree-ish string and a
# file path string when combined in a request parameter
module ExtractsPath
# Raised when given an invalid file path
InvalidPathError = Class.new(StandardError)
# Given a string containing both a Git tree-ish, such as a branch or tag, and
# a filesystem path joined by forward slashes, attempts to separate the two.
#
# Expects a @project instance variable to contain the active project. This is
# used to check the input against a list of valid repository refs.
#
# Examples
#
# # No @project available
# extract_ref('master')
# # => ['', '']
#
# extract_ref('master')
# # => ['master', '']
#
# extract_ref("f4b14494ef6abf3d144c28e4af0c20143383e062/CHANGELOG")
# # => ['f4b14494ef6abf3d144c28e4af0c20143383e062', 'CHANGELOG']
#
# extract_ref("v2.0.0/README.md")
# # => ['v2.0.0', 'README.md']
#
# extract_ref('master/app/models/project.rb')
# # => ['master', 'app/models/project.rb']
#
# extract_ref('issues/1234/app/models/project.rb')
# # => ['issues/1234', 'app/models/project.rb']
#
# # Given an invalid branch, we fall back to just splitting on the first slash
# extract_ref('non/existent/branch/README.md')
# # => ['non', 'existent/branch/README.md']
#
# Returns an Array where the first value is the tree-ish and the second is the
# path
def extract_ref(id)
pair = ['', '']
return pair unless @project # rubocop:disable Gitlab/ModuleWithInstanceVariables
if id =~ /^(\h{40})(.+)/
# If the ref appears to be a SHA, we're done, just split the string
pair = $~.captures
else
# Otherwise, attempt to detect the ref using a list of the project's
# branches and tags
# Append a trailing slash if we only get a ref and no file path
id += '/' unless id.ends_with?('/')
valid_refs = ref_names.select { |v| id.start_with?("#{v}/") }
if valid_refs.length == 0
# No exact ref match, so just try our best
pair = id.match(%r{([^/]+)(.*)}).captures
else
# There is a distinct possibility that multiple refs prefix the ID.
# Use the longest match to maximize the chance that we have the
# right ref.
best_match = valid_refs.max_by(&:length)
# Partition the string into the ref and the path, ignoring the empty first value
pair = id.partition(best_match)[1..-1]
end
end
# Remove ending slashes from path
pair[1].gsub!(%r{^/|/$}, '')
pair
end
# If we have an ID of 'foo.atom', and the controller provides Atom and HTML
# formats, then we have to check if the request was for the Atom version of
# the ID without the '.atom' suffix, or the HTML version of the ID including
# the suffix. We only check this if the version including the suffix doesn't
# match, so it is possible to create a branch which has an unroutable Atom
# feed.
def extract_ref_without_atom(id)
id_without_atom = id.sub(/\.atom$/, '')
valid_refs = ref_names.select { |v| "#{id_without_atom}/".start_with?("#{v}/") }
valid_refs.max_by(&:length)
end
# Assigns common instance variables for views working with Git tree-ish objects
#
# Assignments are:
#
# - @id - A string representing the joined ref and path
# - @ref - A string representing the ref (e.g., the branch, tag, or commit SHA)
# - @path - A string representing the filesystem path
# - @commit - A Commit representing the commit from the given ref
#
# If the :id parameter appears to be requesting a specific response format,
# that will be handled as well.
#
# If there is no path and the ref doesn't exist in the repo, try to resolve
# the ref without an '.atom' suffix. If _that_ ref is found, set the request's
# format to Atom manually.
#
# Automatically renders `not_found!` if a valid tree path could not be
# resolved (e.g., when a user inserts an invalid path or ref).
# rubocop:disable Gitlab/ModuleWithInstanceVariables
def assign_ref_vars
# assign allowed options
allowed_options = ["filter_ref"]
@options = params.select {|key, value| allowed_options.include?(key) && !value.blank? }
@options = HashWithIndifferentAccess.new(@options)
@id = get_id
@ref, @path = extract_ref(@id)
@repo = @project.repository
@commit = @repo.commit(@ref)
if @path.empty? && !@commit && @id.ends_with?('.atom')
@id = @ref = extract_ref_without_atom(@id)
@commit = @repo.commit(@ref)
request.format = :atom if @commit
end
raise InvalidPathError unless @commit
@hex_path = Digest::SHA1.hexdigest(@path)
@logs_path = logs_file_project_ref_path(@project, @ref, @path)
rescue RuntimeError, NoMethodError, InvalidPathError
render_404
end
# rubocop:enable Gitlab/ModuleWithInstanceVariables
def tree
@tree ||= @repo.tree(@commit.id, @path) # rubocop:disable Gitlab/ModuleWithInstanceVariables
end
def lfs_blob_ids
blob_ids = tree.blobs.map(&:id)
# When current endpoint is a Blob then `tree.blobs` will be empty, it means we need to analyze
# the current Blob in order to determine if it's a LFS object
blob_ids = Array.wrap(@repo.blob_at(@commit.id, @path)&.id) if blob_ids.empty? # rubocop:disable Gitlab/ModuleWithInstanceVariables
@lfs_blob_ids = Gitlab::Git::Blob.batch_lfs_pointers(@project.repository, blob_ids).map(&:id) # rubocop:disable Gitlab/ModuleWithInstanceVariables
end
private
# overriden in subclasses, do not remove
def get_id
id = params[:id] || params[:ref]
id += "/" + params[:path] unless params[:path].blank?
id
end
def ref_names
return [] unless @project # rubocop:disable Gitlab/ModuleWithInstanceVariables
@ref_names ||= @project.repository.ref_names # rubocop:disable Gitlab/ModuleWithInstanceVariables
end
end
| 35.945455 | 150 | 0.673074 |
7a21783c4bc976ce12efd136a29eefb4c614eab3 | 841 | require 'spec_helper'
describe Stannis::Plugin::AwsSnapshots::Config do
subject {
example_config = File.expand_path("../../config.example.yml", __FILE__)
Stannis::Plugin::AwsSnapshots::Config.load_file(example_config)
}
it 'has fog_compute Fog::Compute::AWS' do
expect(subject.fog_compute).not_to be nil
expect(subject.fog_compute).to be_instance_of(Fog::Compute::AWS::Real)
end
it 'has fog_rds Fog::AWS::RDS' do
expect(subject.fog_rds).not_to be nil
expect(subject.fog_rds).to be_instance_of(Fog::AWS::RDS::Real)
end
it 'has stannis client' do
expect(subject.stannis).not_to be nil
expect(subject.stannis).to be_instance_of(Stannis::Client)
end
it 'maps deployments to RDS usage' do
expect(subject.deployments).not_to be nil
expect(subject.deployments.size).to eq(1)
end
end
| 29 | 75 | 0.726516 |
ab4b62b350ff9c5cfd6d54497535d31c41616086 | 642 | require 'rubygems'
require 'dogapi'
api_key = '<DATADOG_API_KEY>'
app_key = '<DATADOG_APPLICATION_KEY>'
dog = Dogapi::Client.new(api_key, app_key)
list_id = 4741
dashboards = [
{
"type" => "custom_screenboard",
"id" => "rys-xwq-geh"
},
{
"type" => "custom_timeboard",
"id" => "qts-q2k-yq6"
},
{
"type" => "integration_screenboard",
"id" => "87"
},
{
"type" => "integration_timeboard",
"id" => "23"
},
{
"type" => "host_timeboard",
"id" => "3245468"
}
]
result = dog.v2.add_items_to_dashboard_list(list_id, dashboards)
| 18.882353 | 64 | 0.528037 |
e9cf0de22a5a6455a97f7ddd5374b26c8d1779a1 | 4,053 | # frozen_string_literal: true
module Alchemy
class Element < BaseRecord
# Methods used for presenting an Alchemy Element.
#
module Presenters
extend ActiveSupport::Concern
module ClassMethods
# Human name for displaying elements in select boxes and element editor views.
#
# The name is beeing translated from given name value as described in +config/alchemy/elements.yml+
#
# Translate the name in your +config/locales+ language file.
#
# == Example:
#
# de:
# alchemy:
# element_names:
# contactform: 'Kontakt Formular'
#
# If no translation is found a humanized name is used.
#
def display_name_for(name)
Alchemy.t(name, scope: "element_names", default: name.to_s.humanize)
end
end
# Returns the translated name
#
# @see Alchemy::Element::Presenters#display_name_for
#
def display_name
self.class.display_name_for(definition["name"] || name)
end
# Returns a preview text for element.
#
# It's taken from the first Content found in the +elements.yml+ definition file.
#
# You can flag a Content as +as_element_title+ to take this as preview.
#
# @param maxlength [Fixnum] (60)
# Length of characters after the text will be cut off.
#
def preview_text(maxlength = 60)
preview_text_from_preview_ingredient(maxlength) ||
preview_text_from_preview_content(maxlength) ||
preview_text_from_nested_elements(maxlength)
end
# Generates a preview text containing Element#display_name and Element#preview_text.
#
# It is displayed inside the head of the Element in the Elements.list overlay window from the Alchemy Admin::Page#edit view.
#
# === Example
#
# A Element described as:
#
# - name: funky_element
# display_name: Funky Element
# contents:
# - name: headline
# type: EssenceText
# - name: text
# type EssenceRichtext
# as_element_title: true
#
# With "I want to tell you a funky story" as stripped_body for the EssenceRichtext Content produces:
#
# Funky Element: I want to tell ...
#
# @param maxlength [Fixnum] (30)
# Length of characters after the text will be cut off.
#
def display_name_with_preview_text(maxlength = 30)
"#{display_name}: #{preview_text(maxlength)}"
end
# Returns a dom id used for elements html id tag.
#
def dom_id
"#{name}_#{id}"
end
# The content that's used for element's preview text.
#
# It tries to find one of element's contents that is defined +as_element_title+.
# Takes element's first content if no content is defined +as_element_title+.
#
# @return (Alchemy::Content)
#
def preview_content
@_preview_content ||= contents.detect(&:preview_content?) || contents.first
end
# The ingredient that's used for element's preview text.
#
# It tries to find one of element's ingredients that is defined +as_element_title+.
# Takes element's first ingredient if no ingredient is defined +as_element_title+.
#
# @return (Alchemy::Ingredient)
#
def preview_ingredient
@_preview_ingredient ||= ingredients.detect(&:preview_ingredient?) || ingredients.first
end
private
def preview_text_from_nested_elements(maxlength)
return if all_nested_elements.empty?
all_nested_elements.first.preview_text(maxlength)
end
def preview_text_from_preview_content(maxlength)
preview_content.try!(:preview_text, maxlength)
end
def preview_text_from_preview_ingredient(maxlength)
preview_ingredient&.preview_text(maxlength)
end
end
end
end
| 31.664063 | 130 | 0.622995 |
aba2386b7d4b1615f74d9303c7f5314894667ebc | 231 | # frozen_string_literal: true
class VerificationRequest < ApplicationRecord
validates_associated :phone_number
validates :verification_code, presence: true, numericality: { integer_only: true }
belongs_to :phone_number
end
| 25.666667 | 84 | 0.818182 |
38fb63dc094f71bdac344163a65b41218b1e215f | 165 | class MakeSubscriberListGovDeliveryIdNotNull < ActiveRecord::Migration[5.1]
def change
change_column_null :subscriber_lists, :gov_delivery_id, false
end
end
| 27.5 | 75 | 0.818182 |
7ae0e467ab6d5d8b444b8f9f17f2349259b4e25d | 1,220 | require 'spec_helper'
class TestInterface < Raven::Interface
attr_accessor :some_attr
end
RSpec.describe Raven::Interface do
it "should register an interface when a new class is defined" do
expect(Raven::Interface.registered[:test]).to eq(TestInterface)
end
it "can be initialized with some attributes" do
interface = TestInterface.new(:some_attr => "test")
expect(interface.some_attr).to eq("test")
end
it "can initialize with a block" do
interface = TestInterface.new { |int| int.some_attr = "test" }
expect(interface.some_attr).to eq("test")
end
it "serializes to a Hash" do
interface = TestInterface.new(:some_attr => "test")
expect(interface.to_hash).to eq(:some_attr => "test")
end
end
RSpec.describe Raven::MessageInterface do
it "supports invalid format string message when params is not defined" do
interface = Raven::MessageInterface.new(:params => nil, :message => "test '%'")
expect(interface.unformatted_message).to eq("test '%'")
end
it "supports invalid format string message when params is empty" do
interface = Raven::MessageInterface.new(:message => "test '%'")
expect(interface.unformatted_message).to eq("test '%'")
end
end
| 32.105263 | 83 | 0.713934 |
f7d1a3f5783f84c8f15b923aae62815e6f528d26 | 264 | require File.dirname(File.join(__rhoGetCurrentDir(), __FILE__)) + '/../../spec_helper'
require File.dirname(File.join(__rhoGetCurrentDir(), __FILE__)) + '/../../shared/file/chardev'
describe "File.chardev?" do
it_behaves_like :file_chardev, :chardev?, File
end
| 37.714286 | 94 | 0.734848 |
08627ba8b4072171733c7fbe601d326d1de85d8d | 37 | json.partial! 'email', email: @email
| 18.5 | 36 | 0.702703 |
0320a758ef3dfe049da92a347fe8e692c9490cf4 | 39 | class Sponsor < ActiveRecord::Base
end
| 13 | 34 | 0.794872 |
4aab91cc219a33cb83aacb695aea23ed40f20873 | 145 | module V1
class Base < ApplicationAPI
version "v1", :using => :path
mount ProductAPI
mount SampleAPI
mount SecretAPI
end
end
| 16.111111 | 33 | 0.675862 |
e8022c742a39771562c533589da761f180e32629 | 19,102 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Projects::MergeRequests::DiffsController do
include ProjectForksHelper
shared_examples '404 for unexistent diffable' do
context 'when diffable does not exists' do
it 'returns 404' do
go(diff_id: non_existing_record_id)
expect(MergeRequestDiff.find_by(id: non_existing_record_id)).to be_nil
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'when the merge_request_diff.id is blank' do
it 'returns 404' do
allow_next_instance_of(MergeRequest) do |instance|
allow(instance).to receive(:merge_request_diff).and_return(MergeRequestDiff.new(merge_request_id: instance.id))
go
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
end
shared_examples 'forked project with submodules' do
render_views
let(:project) { create(:project, :repository) }
let(:forked_project) { fork_project_with_submodules(project) }
let(:merge_request) { create(:merge_request_with_diffs, source_project: forked_project, source_branch: 'add-submodule-version-bump', target_branch: 'master', target_project: project) }
before do
project.add_developer(user)
merge_request.reload
go
end
it 'renders' do
expect(response).to be_successful
expect(response.body).to have_content('Subproject commit')
end
end
shared_examples 'cached diff collection' do
it 'ensures diff highlighting cache writing' do
expect_next_instance_of(Gitlab::Diff::HighlightCache) do |cache|
expect(cache).to receive(:write_if_empty).once
end
go
end
end
shared_examples "diff note on-demand position creation" do
it "updates diff discussion positions" do
service = double("service")
expect(Discussions::CaptureDiffNotePositionsService).to receive(:new).with(merge_request).and_return(service)
expect(service).to receive(:execute)
go
end
end
shared_examples 'show the right diff files with previous diff_id' do
context 'with previous diff_id' do
let!(:merge_request_diff_1) { merge_request.merge_request_diffs.create!(head_commit_sha: '6f6d7e7ed97bb5f0054f2b1df789b39ca89b6ff9') }
let!(:merge_request_diff_2) { merge_request.merge_request_diffs.create!(head_commit_sha: '5937ac0a7beb003549fc5fd26fc247adbce4a52e', diff_type: :merge_head) }
subject { go(diff_id: merge_request_diff_1.id, diff_head: true) }
it 'shows the right diff files' do
subject
expect(json_response["diff_files"].size).to eq(merge_request_diff_1.files_count)
end
end
end
let(:project) { create(:project, :repository) }
let(:user) { create(:user) }
let(:merge_request) { create(:merge_request_with_diffs, target_project: project, source_project: project) }
before do
project.add_maintainer(user)
sign_in(user)
end
describe 'GET show' do
def go(extra_params = {})
params = {
namespace_id: project.namespace.to_param,
project_id: project,
id: merge_request.iid,
format: 'json'
}
get :show, params: params.merge(extra_params)
end
context 'with default params' do
context 'for the same project' do
before do
allow(controller).to receive(:rendered_for_merge_request?).and_return(true)
end
it 'serializes merge request diff collection' do
expect_next_instance_of(DiffsSerializer) do |instance|
expect(instance).to receive(:represent).with(an_instance_of(Gitlab::Diff::FileCollection::MergeRequestDiff), an_instance_of(Hash))
end
go
end
end
context 'when note is a legacy diff note' do
before do
create(:legacy_diff_note_on_merge_request, project: project, noteable: merge_request)
end
it 'serializes merge request diff collection' do
expect_next_instance_of(DiffsSerializer) do |instance|
expect(instance).to receive(:represent).with(an_instance_of(Gitlab::Diff::FileCollection::MergeRequestDiff), an_instance_of(Hash))
end
go
end
end
it_behaves_like 'forked project with submodules'
end
it_behaves_like 'cached diff collection'
it_behaves_like 'diff note on-demand position creation'
end
describe 'GET diffs_metadata' do
def go(extra_params = {})
params = {
namespace_id: project.namespace.to_param,
project_id: project,
id: merge_request.iid,
format: 'json'
}
get :diffs_metadata, params: params.merge(extra_params)
end
it_behaves_like '404 for unexistent diffable'
it_behaves_like 'show the right diff files with previous diff_id'
context 'when not authorized' do
let(:another_user) { create(:user) }
before do
sign_in(another_user)
end
it 'returns 404 when not a member' do
go
expect(response).to have_gitlab_http_status(:not_found)
end
it 'returns 404 when visibility level is not enough' do
project.add_guest(another_user)
go
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'with valid diff_id' do
it 'returns success' do
go(diff_id: merge_request.merge_request_diff.id)
expect(response).to have_gitlab_http_status(:ok)
end
it 'serializes diffs metadata with expected arguments' do
expected_options = {
environment: nil,
merge_request: merge_request,
merge_request_diff: merge_request.merge_request_diff,
merge_request_diffs: merge_request.merge_request_diffs,
start_version: nil,
start_sha: nil,
commit: nil,
latest_diff: true,
only_context_commits: false
}
expect_next_instance_of(DiffsMetadataSerializer) do |instance|
expect(instance).to receive(:represent)
.with(an_instance_of(Gitlab::Diff::FileCollection::MergeRequestDiff), expected_options)
.and_call_original
end
go(diff_id: merge_request.merge_request_diff.id)
end
end
context "with the :default_merge_ref_for_diffs flag on" do
let(:diffable_merge_ref) { true }
subject do
go(diff_head: true,
diff_id: merge_request.merge_request_diff.id,
start_sha: merge_request.merge_request_diff.start_commit_sha)
end
it "correctly generates the right diff between versions" do
MergeRequests::MergeToRefService.new(project: project, current_user: merge_request.author).execute(merge_request)
expect_next_instance_of(CompareService) do |service|
expect(service).to receive(:execute).with(
project,
merge_request.merge_request_diff.head_commit_sha,
straight: true)
end
subject
end
end
context 'with diff_head param passed' do
before do
allow(merge_request).to receive(:diffable_merge_ref?)
.and_return(diffable_merge_ref)
end
context 'the merge request can be compared with head' do
let(:diffable_merge_ref) { true }
it 'compares diffs with the head' do
create(:merge_request_diff, :merge_head, merge_request: merge_request)
go(diff_head: true)
expect(response).to have_gitlab_http_status(:ok)
end
end
context 'the merge request cannot be compared with head' do
let(:diffable_merge_ref) { false }
it 'compares diffs with the base' do
go(diff_head: true)
expect(response).to have_gitlab_http_status(:ok)
end
end
end
context 'with MR regular diff params' do
it 'returns success' do
go
expect(response).to have_gitlab_http_status(:ok)
end
it 'serializes diffs metadata with expected arguments' do
expected_options = {
environment: nil,
merge_request: merge_request,
merge_request_diff: merge_request.merge_request_diff,
merge_request_diffs: merge_request.merge_request_diffs,
start_version: nil,
start_sha: nil,
commit: nil,
latest_diff: true,
only_context_commits: false
}
expect_next_instance_of(DiffsMetadataSerializer) do |instance|
expect(instance).to receive(:represent)
.with(an_instance_of(Gitlab::Diff::FileCollection::MergeRequestDiff), expected_options)
.and_call_original
end
go
end
end
context 'with commit param' do
it 'returns success' do
go(commit_id: merge_request.diff_head_sha)
expect(response).to have_gitlab_http_status(:ok)
end
it 'serializes diffs metadata with expected arguments' do
expected_options = {
environment: nil,
merge_request: merge_request,
merge_request_diff: nil,
merge_request_diffs: merge_request.merge_request_diffs,
start_version: nil,
start_sha: nil,
commit: merge_request.diff_head_commit,
latest_diff: nil,
only_context_commits: false
}
expect_next_instance_of(DiffsMetadataSerializer) do |instance|
expect(instance).to receive(:represent)
.with(an_instance_of(Gitlab::Diff::FileCollection::Commit), expected_options)
.and_call_original
end
go(commit_id: merge_request.diff_head_sha)
end
end
end
describe 'GET diff_for_path' do
def diff_for_path(extra_params = {})
params = {
namespace_id: project.namespace.to_param,
project_id: project,
id: merge_request.iid,
format: 'json'
}
get :diff_for_path, params: params.merge(extra_params)
end
let(:existing_path) { 'files/ruby/popen.rb' }
context 'when the merge request exists' do
context 'when the user can view the merge request' do
context 'when the path exists in the diff' do
it 'enables diff notes' do
diff_for_path(old_path: existing_path, new_path: existing_path)
expect(assigns(:diff_notes_disabled)).to be_falsey
expect(assigns(:new_diff_note_attrs)).to eq(noteable_type: 'MergeRequest',
noteable_id: merge_request.id,
commit_id: nil)
end
it 'only renders the diffs for the path given' do
diff_for_path(old_path: existing_path, new_path: existing_path)
paths = json_response['diff_files'].map { |file| file['new_path'] }
expect(paths).to include(existing_path)
end
end
end
context 'when the user cannot view the merge request' do
before do
project.team.truncate
diff_for_path(old_path: existing_path, new_path: existing_path)
end
it 'returns a 404' do
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
context 'when the merge request does not exist' do
before do
diff_for_path(id: merge_request.iid.succ, old_path: existing_path, new_path: existing_path)
end
it 'returns a 404' do
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'when the merge request belongs to a different project' do
let(:other_project) { create(:project) }
before do
other_project.add_maintainer(user)
diff_for_path(old_path: existing_path, new_path: existing_path, project_id: other_project)
end
it 'returns a 404' do
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
describe 'GET diffs_batch' do
shared_examples_for 'serializes diffs with expected arguments' do
it 'serializes paginated merge request diff collection' do
expect_next_instance_of(PaginatedDiffSerializer) do |instance|
expect(instance).to receive(:represent)
.with(an_instance_of(collection), expected_options)
.and_call_original
end
subject
end
end
shared_examples_for 'successful request' do
it 'returns success' do
subject
expect(response).to have_gitlab_http_status(:ok)
end
it 'tracks mr_diffs event' do
expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter)
.to receive(:track_mr_diffs_action)
.with(merge_request: merge_request)
subject
end
context 'when DNT is enabled' do
before do
request.headers['DNT'] = '1'
end
it 'does not track any mr_diffs event' do
expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter)
.not_to receive(:track_mr_diffs_action)
expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter)
.not_to receive(:track_mr_diffs_single_file_action)
subject
end
end
context 'when user has view_diffs_file_by_file set to false' do
before do
user.update!(view_diffs_file_by_file: false)
end
it 'does not track single_file_diffs events' do
expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter)
.not_to receive(:track_mr_diffs_single_file_action)
subject
end
end
context 'when user has view_diffs_file_by_file set to true' do
before do
user.update!(view_diffs_file_by_file: true)
end
it 'tracks single_file_diffs events' do
expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter)
.to receive(:track_mr_diffs_single_file_action)
.with(merge_request: merge_request, user: user)
subject
end
end
end
def collection_arguments(pagination_data = {})
{
environment: nil,
merge_request: merge_request,
diff_view: :inline,
merge_ref_head_diff: nil,
allow_tree_conflicts: true,
pagination_data: {
total_pages: nil
}.merge(pagination_data)
}
end
def go(extra_params = {})
params = {
namespace_id: project.namespace.to_param,
project_id: project,
id: merge_request.iid,
page: 0,
per_page: 20,
format: 'json'
}
get :diffs_batch, params: params.merge(extra_params)
end
it_behaves_like '404 for unexistent diffable'
it_behaves_like 'show the right diff files with previous diff_id'
context 'when not authorized' do
let(:other_user) { create(:user) }
before do
sign_in(other_user)
end
it 'returns 404' do
go
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'with valid diff_id' do
subject { go(diff_id: merge_request.merge_request_diff.id) }
it_behaves_like 'serializes diffs with expected arguments' do
let(:collection) { Gitlab::Diff::FileCollection::MergeRequestDiffBatch }
let(:expected_options) { collection_arguments(total_pages: 20).merge(merge_ref_head_diff: false) }
end
it_behaves_like 'successful request'
end
context 'with commit_id param' do
subject { go(commit_id: merge_request.diff_head_sha) }
it_behaves_like 'serializes diffs with expected arguments' do
let(:collection) { Gitlab::Diff::FileCollection::Commit }
let(:expected_options) { collection_arguments }
end
end
context 'with diff_id and start_sha params' do
subject do
go(diff_id: merge_request.merge_request_diff.id,
start_sha: merge_request.merge_request_diff.start_commit_sha)
end
it_behaves_like 'serializes diffs with expected arguments' do
let(:collection) { Gitlab::Diff::FileCollection::Compare }
let(:expected_options) { collection_arguments.merge(merge_ref_head_diff: false) }
end
it_behaves_like 'successful request'
end
context 'with paths param' do
let(:example_file_path) { "README" }
let(:file_path_option) { { paths: [example_file_path] } }
subject do
go(file_path_option)
end
it_behaves_like 'serializes diffs with expected arguments' do
let(:collection) { Gitlab::Diff::FileCollection::MergeRequestDiffBatch }
let(:expected_options) do
collection_arguments(total_pages: 20)
end
end
it_behaves_like 'successful request'
it 'filters down the response to the expected file path' do
subject
expect(json_response["diff_files"].size).to eq(1)
expect(json_response["diff_files"].first["file_path"]).to eq(example_file_path)
end
end
context 'with default params' do
subject { go }
it_behaves_like 'serializes diffs with expected arguments' do
let(:collection) { Gitlab::Diff::FileCollection::MergeRequestDiffBatch }
let(:expected_options) { collection_arguments(total_pages: 20) }
end
it_behaves_like 'successful request'
end
context 'with smaller diff batch params' do
subject { go(page: 5, per_page: 5) }
it_behaves_like 'serializes diffs with expected arguments' do
let(:collection) { Gitlab::Diff::FileCollection::MergeRequestDiffBatch }
let(:expected_options) { collection_arguments(total_pages: 20) }
end
it_behaves_like 'successful request'
end
context 'when display_merge_conflicts_in_diff is disabled' do
before do
stub_feature_flags(display_merge_conflicts_in_diff: false)
end
subject { go }
it_behaves_like 'serializes diffs with expected arguments' do
let(:collection) { Gitlab::Diff::FileCollection::MergeRequestDiffBatch }
let(:expected_options) { collection_arguments(total_pages: 20).merge(allow_tree_conflicts: false) }
end
it_behaves_like 'successful request'
end
it_behaves_like 'forked project with submodules'
it_behaves_like 'cached diff collection'
context 'diff unfolding' do
let!(:unfoldable_diff_note) do
create(:diff_note_on_merge_request, :folded_position, project: project, noteable: merge_request)
end
let!(:diff_note) do
create(:diff_note_on_merge_request, project: project, noteable: merge_request)
end
it 'unfolds correct diff file positions' do
expect_next_instance_of(Gitlab::Diff::FileCollection::MergeRequestDiffBatch) do |instance|
expect(instance)
.to receive(:unfold_diff_files)
.with([unfoldable_diff_note.position])
.and_call_original
end
go
end
end
end
end
| 30.176935 | 188 | 0.661292 |
03d6a612a4a8ad58f4de5d81a8e63b1c7212fb25 | 767 | require 'formula'
class Ufraw < Formula
homepage 'http://ufraw.sourceforge.net'
url 'https://downloads.sourceforge.net/project/ufraw/ufraw/ufraw-0.19.2/ufraw-0.19.2.tar.gz'
sha1 '11a607e874eb16453a8f7964e4946a29d18b071d'
depends_on 'pkg-config' => :build
depends_on :libpng
depends_on 'dcraw'
depends_on 'glib'
depends_on 'jpeg'
depends_on 'libtiff'
depends_on 'little-cms'
depends_on 'exiv2' => :optional
fails_with :llvm do
cause "Segfault while linking"
end
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--without-gtk",
"--without-gimp"
system "make install"
(share+'pixmaps').rmtree
end
end
| 25.566667 | 94 | 0.634941 |
bb2b3e6968be2e149e6b459116762c5e31eaeadd | 139 | require "ruby/selenium/version"
module Ruby
module Selenium
class Error < StandardError; end
# Your code goes here...
end
end
| 15.444444 | 36 | 0.705036 |
d5bc260aa58db9be8d1e5cfa1ad2877b1b7bffa1 | 1,330 |
class BuildCloud::DbParameterGroup
include ::BuildCloud::Component
@@objects = []
def initialize ( fog_interfaces, log, options = {} )
@rds = fog_interfaces[:rds]
@log = log
@options = options
@log.debug( options.inspect )
required_options(:family, :description, :id, :params)
end
def create
return if exists?
@log.info( "Creating DB Parameter Group #{@options[:id]}" )
options = @options.dup
param_group = @rds.create_db_parameter_group(options[:id], options[:family], options[:description])
@log.debug( param_group.inspect )
params = @rds.modify_db_parameter_group options[:id], options[:params].collect! { |c|
{
'ParameterName' => c[:param_name],
'ParameterValue' => c[:param_value],
'ApplyMethod' => c[:apply_method],
}
}
@log.debug( params.inspect )
end
def read
@rds.parameter_groups.select { |g| g.id == "#{@options[:id]}".downcase }.first
end
alias_method :fog_object, :read
def delete
return unless exists?
@log.info( "Deleting DB Parameter Group #{@options[:id]}" )
puts fog_object.inspect
fog_object.destroy
end
end
| 21.111111 | 107 | 0.565414 |
e9eb4d8cb95599b7a9390de2f7d4ca8bf6d26113 | 351 | # == Schema Information
#
# Table name: holdings
#
# id :bigint not null, primary key
# user_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
require 'test_helper'
class HoldingTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 20.647059 | 53 | 0.612536 |
f83247afb190a1699ad57b5e9502f27e0862c89c | 1,045 | #!/usr/bin/ruby -Ku
# -*- coding: utf-8 -*-
require 'kconv'
require 'iconv'
require 'rexml/encoding'
class ChangingEncodings < Test::Unit::TestCase
def initialize a
@u = 'テスト ほげ ふが 美しい'
@e = Kconv.toeuc(@u)
@f = Foo.new
super
end
class Foo
include REXML::Encoding
end
# Note that these tests must be executed in order for the third one to
# actually test anything.
def test_0_euc
@f.encoding = 'EUC-JP'
assert_equal( @u, @f.decode(@e) )
# This doesn't happen anymore, for some reason
#assert_raises( Iconv::IllegalSequence, "Decoding unicode should fail" ) {
# @f.decode(@u) == @u
#}
end
def test_1_utf
@f.encoding = 'UTF-8'
assert_not_equal( @u, @f.decode( @e ) )
assert_equal( @u, @f.decode( @u ) )
end
def test_2_euc
@f.encoding = 'EUC-JP'
assert_equal( @u, @f.decode(@e) )
# This doesn't happen anymore, for some reason
#assert_raises( Iconv::IllegalSequence, "Decoding unicode should fail" ) {
# @f.decode(@u) == @u
#}
end
end
| 22.234043 | 78 | 0.620096 |
ff95666c737ce3346f2c819bee27aac4d5604a77 | 1,865 | # frozen_string_literal: true
# Copyright (c) 2008-2013 Michael Dvorkin and contributors.
#
# Fat Free CRM is freely distributable under the terms of MIT license.
# See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
# See vendor/plugins/authlogic/lib/authlogic/test_case.rb
#----------------------------------------------------------------------------
def activate_authlogic
require 'authlogic/test_case/rails_request_adapter'
require 'authlogic/test_case/mock_cookie_jar'
require 'authlogic/test_case/mock_request'
Authlogic::Session::Base.controller = (@request && Authlogic::TestCase::RailsRequestAdapter.new(@request)) || controller
end
# Note: Authentication is NOT ActiveRecord model, so we mock and stub it using RSpec.
#----------------------------------------------------------------------------
def login(user_stubs = {}, session_stubs = {})
User.current_user = @current_user = create(:user, user_stubs)
@current_user_session = double(Authentication, { record: current_user }.merge(session_stubs))
allow(Authentication).to receive(:find).and_return(@current_user_session)
# set_timezone
assigns[:current_user] = current_user
end
#----------------------------------------------------------------------------
def login_admin
login(admin: true)
end
#----------------------------------------------------------------------------
def logout
@current_user = nil
@current_user_session = nil
allow(Authentication).to receive(:find).and_return(nil)
end
alias require_no_user logout
#----------------------------------------------------------------------------
def current_user
@current_user
end
#----------------------------------------------------------------------------
def current_user_session
@current_user_session
end
| 37.3 | 122 | 0.554424 |
872be3c780d5bc5a277f11acf2fdc9e98f5d51ab | 7,440 | ActiveAdmin.setup do |config|
# == Site Title
#
# Set the title that is displayed on the main layout
# for each of the active admin pages.
#
config.site_title = "Brasil Acessivel"
# Set the link url for the title. For example, to take
# users to your main site. Defaults to no link.
#
# config.site_title_link = "/"
# Set an optional image to be displayed for the header
# instead of a string (overrides :site_title)
#
# Note: Aim for an image that's 21px high so it fits in the header.
#
# config.site_title_image = "logo.png"
# == Default Namespace
#
# Set the default namespace each administration resource
# will be added to.
#
# eg:
# config.default_namespace = :hello_world
#
# This will create resources in the HelloWorld module and
# will namespace routes to /hello_world/*
#
# To set no namespace by default, use:
# config.default_namespace = false
#
# Default:
# config.default_namespace = :admin
#
# You can customize the settings for each namespace by using
# a namespace block. For example, to change the site title
# within a namespace:
#
# config.namespace :admin do |admin|
# admin.site_title = "Custom Admin Title"
# end
#
# This will ONLY change the title for the admin section. Other
# namespaces will continue to use the main "site_title" configuration.
# == User Authentication
#
# Active Admin will automatically call an authentication
# method in a before filter of all controller actions to
# ensure that there is a currently logged in admin user.
#
# This setting changes the method which Active Admin calls
# within the application controller.
config.authentication_method = :authenticate_admin_user!
# == User Authorization
#
# Active Admin will automatically call an authorization
# method in a before filter of all controller actions to
# ensure that there is a user with proper rights. You can use
# CanCanAdapter or make your own. Please refer to documentation.
# config.authorization_adapter = ActiveAdmin::CanCanAdapter
# In case you prefer Pundit over other solutions you can here pass
# the name of default policy class. This policy will be used in every
# case when Pundit is unable to find suitable policy.
# config.pundit_default_policy = "MyDefaultPunditPolicy"
# You can customize your CanCan Ability class name here.
# config.cancan_ability_class = "Ability"
# You can specify a method to be called on unauthorized access.
# This is necessary in order to prevent a redirect loop which happens
# because, by default, user gets redirected to Dashboard. If user
# doesn't have access to Dashboard, he'll end up in a redirect loop.
# Method provided here should be defined in application_controller.rb.
# config.on_unauthorized_access = :access_denied
# == Current User
#
# Active Admin will associate actions with the current
# user performing them.
#
# This setting changes the method which Active Admin calls
# (within the application controller) to return the currently logged in user.
config.current_user_method = :current_admin_user
# == Logging Out
#
# Active Admin displays a logout link on each screen. These
# settings configure the location and method used for the link.
#
# This setting changes the path where the link points to. If it's
# a string, the strings is used as the path. If it's a Symbol, we
# will call the method to return the path.
#
# Default:
config.logout_link_path = :destroy_admin_user_session_path
# This setting changes the http method used when rendering the
# link. For example :get, :delete, :put, etc..
#
# Default:
# config.logout_link_method = :get
# == Root
#
# Set the action to call for the root path. You can set different
# roots for each namespace.
#
# Default:
# config.root_to = 'dashboard#index'
# == Admin Comments
#
# This allows your users to comment on any resource registered with Active Admin.
#
# You can completely disable comments:
# config.comments = false
#
# You can disable the menu item for the comments index page:
# config.show_comments_in_menu = false
#
# You can change the name under which comments are registered:
# config.comments_registration_name = 'AdminComment'
# == Batch Actions
#
# Enable and disable Batch Actions
#
config.batch_actions = true
# == Controller Filters
#
# You can add before, after and around filters to all of your
# Active Admin resources and pages from here.
#
# config.before_filter :do_something_awesome
# == Setting a Favicon
#
config.favicon = 'logo.ico'
# == Removing Breadcrumbs
#
# Breadcrumbs are enabled by default. You can customize them for individual
# resources or you can disable them globally from here.
#
# config.breadcrumb = false
# == Register Stylesheets & Javascripts
#
# We recommend using the built in Active Admin layout and loading
# up your own stylesheets / javascripts to customize the look
# and feel.
#
# To load a stylesheet:
# config.register_stylesheet 'my_stylesheet.css'
#
# You can provide an options hash for more control, which is passed along to stylesheet_link_tag():
# config.register_stylesheet 'my_print_stylesheet.css', media: :print
#
# To load a javascript file:
# config.register_javascript 'my_javascript.js'
# == CSV options
#
# Set the CSV builder separator
# config.csv_options = { col_sep: ';' }
#
# Force the use of quotes
# config.csv_options = { force_quotes: true }
# == Menu System
#
# You can add a navigation menu to be used in your application, or configure a provided menu
#
# To change the default utility navigation to show a link to your website & a logout btn
#
# config.namespace :admin do |admin|
# admin.build_menu :utility_navigation do |menu|
# menu.add label: "My Great Website", url: "http://www.mygreatwebsite.com", html_options: { target: :blank }
# admin.add_logout_button_to_menu menu
# end
# end
#
# If you wanted to add a static menu item to the default menu provided:
#
# config.namespace :admin do |admin|
# admin.build_menu :default do |menu|
# menu.add label: "My Great Website", url: "http://www.mygreatwebsite.com", html_options: { target: :blank }
# end
# end
# == Download Links
#
# You can disable download links on resource listing pages,
# or customize the formats shown per namespace/globally
#
# To disable/customize for the :admin namespace:
#
# config.namespace :admin do |admin|
#
# # Disable the links entirely
# admin.download_links = false
#
# # Only show XML & PDF options
# admin.download_links = [:xml, :pdf]
#
# # Enable/disable the links based on block
# # (for example, with cancan)
# admin.download_links = proc { can?(:view_download_links) }
#
# end
# == Pagination
#
# Pagination is enabled by default for all resources.
# You can control the default per page count for all resources here.
#
# config.default_per_page = 30
# == Filters
#
# By default the index screen includes a "Filters" sidebar on the right
# hand side with a filter for each attribute of the registered model.
# You can enable or disable them for all resources here.
#
# config.filters = true
end
| 31.794872 | 116 | 0.700403 |
39a33a1480e702cfc0192732d0721dcc20b2c2b4 | 1,339 | module Tamplier
class Validator
def ensure(root, environment = nil)
Iterator.new.call(root) do |sample_file, config_file|
raise ConfigurationException.new("Configuration file #{config_file} does not exist, but sample file #{sample_file} does.") unless config_file.exist?
if environmental_file?(sample_file)
raise ConfigurationException.new("There is no #{environment} environment in the #{config_file} file.") unless YAML.load(config_file.read)[environment].present?
end
sample_config = YAML.load(sample_file.read)
real_config = YAML.load(config_file.read)
diff = environmental_file?(sample_file) ?
flat_keys(sample_config['development']) - flat_keys(real_config[environment]) :
flat_keys(sample_config) - flat_keys(real_config)
raise ConfigurationException.new("Several keys #{diff.inspect} from #{sample_file} are not in #{config_file} file.") unless diff.empty?
end
end
private
def environmental_file?(file)
(YAML.load(file.read).keys & %w[development test]).present?
end
def flat_keys(hash, path = '')
return [path] unless hash.is_a?(Hash)
hash.map do |key, value|
flat_keys(value, path.blank? ? key : [path, key].join('/'))
end.flatten
end
end
end
| 37.194444 | 169 | 0.671397 |
d56740003d0656cfb2521dcaf4a23e8ed59d0155 | 4,433 | # frozen_string_literal: true
require 'oauth/consumer'
require File.join(File.dirname(__FILE__), 'simple_client')
module Oauth
module Models
module Consumers
module Token
def self.included(model)
model.class_eval do
validates_presence_of :user, :token
end
model.send(:include, InstanceMethods)
model.send(:extend, ClassMethods)
end
module ClassMethods
def service_name
@service_name ||= to_s.underscore.scan(/^(.*?)(_token)?$/)[0][0].to_sym
end
def consumer
options = credentials[:options] || {}
@consumer ||= OAuth::Consumer.new credentials[:key], credentials[:secret], options
end
def get_request_token(callback_url)
consumer.get_request_token(oauth_callback: callback_url)
end
def find_or_create_from_request_token(user, token, secret, oauth_verifier)
request_token = OAuth::RequestToken.new consumer, token, secret
options = {}
options[:oauth_verifier] = oauth_verifier if oauth_verifier
access_token = request_token.get_access_token options
find_or_create_from_access_token user, access_token
end
# Finds, creates or updates a ConsumerToken by finding the token
# or taking it when it's given. It then updates the attributes and saves the changes/new record to a datastore.
# @param user [User] The user to which the access token should belong to
# @param access_token [AccessToken || Oauth2Token] Either a request token taken from the service or a ConsumerToken
# @param new_token [AccessToken] A new access token, used for refreshing the access token with OAuth 2.
#
# Usage example:
# find_or_create_from_access_token(current_user, access_token) <-- Find or create a new access token
# find_or_create_from_access-token(current_user, Oauth2Token.last, client.refresh!) <-- Edits existing record with new refreshed information
def find_or_create_from_access_token(user, access_token, new_token = nil)
if access_token.class.ancestors.include?(Oauth2Token)
token = access_token
else
token = if user
find_or_initialize_by_user_id_and_token(user.id, access_token.token)
else
find_or_initialize_by_token(access_token.token)
end
end
token = new_token ? set_details(new_token, access_token) : set_details(access_token, token)
token.save! if token.new_record? || token.changed?
token
end
# Set the details such as the secret, refresh token and expiration time to an instance of ConsumerToken
# @return [ConsumerToken] A ConsumerToken
def set_details(access_token, token)
secret = access_token.respond_to?(:secret) ? access_token.secret : nil
refresh_token = access_token.respond_to?(:refresh_token) ? access_token.refresh_token : nil
if token.class.ancestors.include?(Oauth2Token)
expires_in, expires_at = token.expiration_date(access_token)
end
token.token = access_token.token
token.refresh_token = refresh_token
token.secret = secret
token.expires_at = expires_at
token.expires_in = expires_in
token
end
def build_user_from_token; end
def credentials
@credentials ||= OAUTH_CREDENTIALS[service_name]
end
end
module InstanceMethods
# Main client for interfacing with remote service. Override this to use
# preexisting library eg. Twitter gem.
def client
@client ||= OAuth::AccessToken.new self.class.consumer, token, secret
end
def simple_client
@simple_client ||= SimpleClient.new client
end
# Override this to return user data from service
def params_for_user
{}
end
def create_user
self.user ||= begin
User.new params_for_user
user.save(validate: false)
end
end
end
end
end
end
end
| 36.941667 | 150 | 0.618317 |
f8800468b34334c50fcd0413aae6a6a9365a1569 | 45,787 | # coding: US-ASCII
# frozen_string_literal: false
require 'test/unit'
class TestRegexp < Test::Unit::TestCase
def setup
@verbose = $VERBOSE
$VERBOSE = nil
end
def teardown
$VERBOSE = @verbose
end
def test_has_NOENCODING
assert Regexp::NOENCODING
re = //n
assert_equal Regexp::NOENCODING, re.options
end
def test_ruby_dev_999
assert_match(/(?<=a).*b/, "aab")
assert_match(/(?<=\u3042).*b/, "\u3042ab")
end
def test_ruby_core_27247
assert_match(/(a){2}z/, "aaz")
end
def test_ruby_dev_24643
assert_nothing_raised("[ruby-dev:24643]") {
/(?:(?:[a]*[a])?b)*a*$/ =~ "aabaaca"
}
end
def test_ruby_talk_116455
assert_match(/^(\w{2,}).* ([A-Za-z\xa2\xc0-\xff]{2,}?)$/n, "Hallo Welt")
end
def test_ruby_dev_24887
assert_equal("a".gsub(/a\Z/, ""), "")
end
def test_yoshidam_net_20041111_1
s = "[\xC2\xA0-\xC3\xBE]"
assert_match(Regexp.new(s, nil, "u"), "\xC3\xBE")
end
def test_yoshidam_net_20041111_2
assert_raise(RegexpError) do
s = "[\xFF-\xFF]".force_encoding("utf-8")
Regexp.new(s, nil, "u")
end
end
def test_ruby_dev_31309
assert_equal('Ruby', 'Ruby'.sub(/[^a-z]/i, '-'))
end
def test_assert_normal_exit
# moved from knownbug. It caused core.
Regexp.union("a", "a")
end
def test_to_s
assert_equal '(?-mix:\x00)', Regexp.new("\0").to_s
str = "abcd\u3042"
[:UTF_16BE, :UTF_16LE, :UTF_32BE, :UTF_32LE].each do |es|
enc = Encoding.const_get(es)
rs = Regexp.new(str.encode(enc)).to_s
assert_equal("(?-mix:abcd\u3042)".encode(enc), rs)
assert_equal(enc, rs.encoding)
end
end
def test_to_s_extended_subexp
re = /#\g#{"\n"}/x
re = /#{re}/
assert_warn('', '[ruby-core:82328] [Bug #13798]') {re.to_s}
end
def test_union
assert_equal :ok, begin
Regexp.union(
"a",
Regexp.new("\xc2\xa1".force_encoding("euc-jp")),
Regexp.new("\xc2\xa1".force_encoding("utf-8")))
:ng
rescue ArgumentError
:ok
end
re = Regexp.union(/\//, "")
re2 = eval(re.inspect)
assert_equal(re.to_s, re2.to_s)
assert_equal(re.source, re2.source)
assert_equal(re, re2)
end
def test_word_boundary
assert_match(/\u3042\b /, "\u3042 ")
assert_not_match(/\u3042\ba/, "\u3042a")
end
def test_named_capture
m = /&(?<foo>.*?);/.match("aaa & yyy")
assert_equal("amp", m["foo"])
assert_equal("amp", m[:foo])
assert_equal(5, m.begin(:foo))
assert_equal(8, m.end(:foo))
assert_equal([5,8], m.offset(:foo))
assert_equal("aaa [amp] yyy",
"aaa & yyy".sub(/&(?<foo>.*?);/, '[\k<foo>]'))
assert_equal('#<MatchData "& y" foo:"amp">',
/&(?<foo>.*?); (y)/.match("aaa & yyy").inspect)
assert_equal('#<MatchData "& y" 1:"amp" 2:"y">',
/&(.*?); (y)/.match("aaa & yyy").inspect)
assert_equal('#<MatchData "& y" foo:"amp" bar:"y">',
/&(?<foo>.*?); (?<bar>y)/.match("aaa & yyy").inspect)
assert_equal('#<MatchData "& y" foo:"amp" foo:"y">',
/&(?<foo>.*?); (?<foo>y)/.match("aaa & yyy").inspect)
/(?<_id>[A-Za-z_]+)/ =~ "!abc"
assert_not_nil(Regexp.last_match)
assert_equal("abc", Regexp.last_match(1))
assert_equal("abc", Regexp.last_match(:_id))
/a/ =~ "b" # doesn't match.
assert_equal(nil, Regexp.last_match)
assert_equal(nil, Regexp.last_match(1))
assert_equal(nil, Regexp.last_match(:foo))
bug11825_name = "\u{5b9d 77f3}"
bug11825_str = "\u{30eb 30d3 30fc}"
bug11825_re = /(?<#{bug11825_name}>)#{bug11825_str}/
assert_equal(["foo", "bar"], /(?<foo>.)(?<bar>.)/.names)
assert_equal(["foo"], /(?<foo>.)(?<foo>.)/.names)
assert_equal([], /(.)(.)/.names)
assert_equal([bug11825_name], bug11825_re.names)
assert_equal(["foo", "bar"], /(?<foo>.)(?<bar>.)/.match("ab").names)
assert_equal(["foo"], /(?<foo>.)(?<foo>.)/.match("ab").names)
assert_equal([], /(.)(.)/.match("ab").names)
assert_equal([bug11825_name], bug11825_re.match(bug11825_str).names)
assert_equal({"foo"=>[1], "bar"=>[2]},
/(?<foo>.)(?<bar>.)/.named_captures)
assert_equal({"foo"=>[1, 2]},
/(?<foo>.)(?<foo>.)/.named_captures)
assert_equal({}, /(.)(.)/.named_captures)
assert_equal("a[b]c", "abc".sub(/(?<x>[bc])/, "[\\k<x>]"))
assert_equal("o", "foo"[/(?<bar>o)/, "bar"])
assert_equal("o", "foo"[/(?<@bar>o)/, "@bar"])
assert_equal("o", "foo"[/(?<@bar>.)\g<@bar>\k<@bar>/, "@bar"])
s = "foo"
s[/(?<bar>o)/, "bar"] = "baz"
assert_equal("fbazo", s)
end
def test_named_capture_with_nul
bug9902 = '[ruby-dev:48275] [Bug #9902]'
m = /(?<a>.*)/.match("foo")
assert_raise(IndexError, bug9902) {m["a\0foo"]}
assert_raise(IndexError, bug9902) {m["a\0foo".to_sym]}
m = Regexp.new("(?<foo\0bar>.*)").match("xxx")
assert_raise(IndexError, bug9902) {m["foo"]}
assert_raise(IndexError, bug9902) {m["foo".to_sym]}
assert_nothing_raised(IndexError, bug9902) {
assert_equal("xxx", m["foo\0bar"], bug9902)
assert_equal("xxx", m["foo\0bar".to_sym], bug9902)
}
end
def test_named_capture_nonascii
bug9903 = '[ruby-dev:48278] [Bug #9903]'
key = "\xb1\xb2".force_encoding(Encoding::EUC_JP)
m = /(?<#{key}>.*)/.match("xxx")
assert_equal("xxx", m[key])
assert_raise(IndexError, bug9903) {m[key.dup.force_encoding(Encoding::Shift_JIS)]}
end
def test_match_data_named_captures
assert_equal({'a' => '1', 'b' => '2', 'c' => nil}, /^(?<a>.)(?<b>.)(?<c>.)?/.match('12').named_captures)
assert_equal({'a' => '1', 'b' => '2', 'c' => '3'}, /^(?<a>.)(?<b>.)(?<c>.)?/.match('123').named_captures)
assert_equal({'a' => '1', 'b' => '2', 'c' => ''}, /^(?<a>.)(?<b>.)(?<c>.?)/.match('12').named_captures)
assert_equal({'a' => 'x'}, /(?<a>x)|(?<a>y)/.match('x').named_captures)
assert_equal({'a' => 'y'}, /(?<a>x)|(?<a>y)/.match('y').named_captures)
assert_equal({'a' => '1', 'b' => '2'}, /^(.)(?<a>.)(?<b>.)/.match('012').named_captures)
assert_equal({'a' => '2'}, /^(?<a>.)(?<a>.)/.match('12').named_captures)
assert_equal({}, /^(.)/.match('123').named_captures)
end
def test_assign_named_capture
assert_equal("a", eval('/(?<foo>.)/ =~ "a"; foo'))
assert_equal(nil, eval('/(?<@foo>.)/ =~ "a"; defined?(@foo)'))
assert_equal("a", eval('foo = 1; /(?<foo>.)/ =~ "a"; foo'))
assert_equal("a", eval('1.times {|foo| /(?<foo>.)/ =~ "a"; break foo }'))
assert_nothing_raised { eval('/(?<Foo>.)/ =~ "a"') }
assert_nil(eval('/(?<Foo>.)/ =~ "a"; defined? Foo'))
end
def test_assign_named_capture_to_reserved_word
/(?<nil>.)/ =~ "a"
assert_not_include(local_variables, :nil, "[ruby-dev:32675]")
end
def test_assign_named_capture_to_const
%W[C \u{1d402}].each do |name|
assert_equal(:ok, Class.new.class_eval("#{name} = :ok; /(?<#{name}>.*)/ =~ 'ng'; #{name}"))
end
end
def test_assign_named_capture_trace
bug = '[ruby-core:79940] [Bug #13287]'
assert_normal_exit("#{<<-"begin;"}\n#{<<-"end;"}", bug)
begin;
/ (?<foo>.*)/ =~ "bar" &&
true
end;
end
def test_match_regexp
r = /./
m = r.match("a")
assert_equal(r, m.regexp)
re = /foo/
assert_equal(re, re.match("foo").regexp)
end
def test_source
bug5484 = '[ruby-core:40364]'
assert_equal('', //.source)
assert_equal('\:', /\:/.source, bug5484)
assert_equal(':', %r:\::.source, bug5484)
end
def test_source_escaped
expected, result = "$*+.?^|".each_char.map {|c|
[
["\\#{c}", "\\#{c}", 1],
begin
re = eval("%r#{c}\\#{c}#{c}", nil, __FILE__, __LINE__)
t = eval("/\\#{c}/", nil, __FILE__, __LINE__).source
rescue SyntaxError => e
[e, t, nil]
else
[re.source, t, re =~ "a#{c}a"]
end
]
}.transpose
assert_equal(expected, result)
end
def test_source_escaped_paren
bug7610 = '[ruby-core:51088] [Bug #7610]'
bug8133 = '[ruby-core:53578] [Bug #8133]'
[
["(", ")", bug7610], ["[", "]", bug8133],
["{", "}", bug8133], ["<", ">", bug8133],
].each do |lparen, rparen, bug|
s = "\\#{lparen}a\\#{rparen}"
assert_equal(/#{s}/, eval("%r#{lparen}#{s}#{rparen}"), bug)
end
end
def test_source_unescaped
expected, result = "!\"#%&',-/:;=@_`~".each_char.map {|c|
[
["#{c}", "\\#{c}", 1],
begin
re = eval("%r#{c}\\#{c}#{c}", nil, __FILE__, __LINE__)
t = eval("%r{\\#{c}}", nil, __FILE__, __LINE__).source
rescue SyntaxError => e
[e, t, nil]
else
[re.source, t, re =~ "a#{c}a"]
end
]
}.transpose
assert_equal(expected, result)
end
def test_inspect
assert_equal('//', //.inspect)
assert_equal('//i', //i.inspect)
assert_equal('/\//i', /\//i.inspect)
assert_equal('/\//i', %r"#{'/'}"i.inspect)
assert_equal('/\/x/i', /\/x/i.inspect)
assert_equal('/\x00/i', /#{"\0"}/i.inspect)
assert_equal("/\n/i", /#{"\n"}/i.inspect)
s = [0xf1, 0xf2, 0xf3].pack("C*")
assert_equal('/\/\xF1\xF2\xF3/i', /\/#{s}/i.inspect)
end
def test_char_to_option
assert_equal("BAR", "FOOBARBAZ"[/b../i])
assert_equal("bar", "foobarbaz"[/ b . . /x])
assert_equal("bar\n", "foo\nbar\nbaz"[/b.../m])
assert_raise(SyntaxError) { eval('//z') }
end
def test_char_to_option_kcode
assert_equal("bar", "foobarbaz"[/b../s])
assert_equal("bar", "foobarbaz"[/b../e])
assert_equal("bar", "foobarbaz"[/b../u])
end
def test_to_s2
assert_equal('(?-mix:foo)', /(?:foo)/.to_s)
assert_equal('(?m-ix:foo)', /(?:foo)/m.to_s)
assert_equal('(?mi-x:foo)', /(?:foo)/mi.to_s)
assert_equal('(?mix:foo)', /(?:foo)/mix.to_s)
assert_equal('(?m-ix:foo)', /(?m-ix:foo)/.to_s)
assert_equal('(?mi-x:foo)', /(?mi-x:foo)/.to_s)
assert_equal('(?mix:foo)', /(?mix:foo)/.to_s)
assert_equal('(?mix:)', /(?mix)/.to_s)
assert_equal('(?-mix:(?mix:foo) )', /(?mix:foo) /.to_s)
end
def test_casefold_p
assert_equal(false, /a/.casefold?)
assert_equal(true, /a/i.casefold?)
assert_equal(false, /(?i:a)/.casefold?)
end
def test_options
assert_equal(Regexp::IGNORECASE, /a/i.options)
assert_equal(Regexp::EXTENDED, /a/x.options)
assert_equal(Regexp::MULTILINE, /a/m.options)
end
def test_match_init_copy
m = /foo/.match("foo")
assert_equal(/foo/, m.dup.regexp)
assert_raise(TypeError) do
m.instance_eval { initialize_copy(nil) }
end
assert_equal([0, 3], m.offset(0))
assert_equal(/foo/, m.dup.regexp)
end
def test_match_size
m = /(.)(.)(\d+)(\d)/.match("THX1138.")
assert_equal(5, m.size)
end
def test_match_offset_begin_end
m = /(?<x>b..)/.match("foobarbaz")
assert_equal([3, 6], m.offset("x"))
assert_equal(3, m.begin("x"))
assert_equal(6, m.end("x"))
assert_raise(IndexError) { m.offset("y") }
assert_raise(IndexError) { m.offset(2) }
assert_raise(IndexError) { m.begin(2) }
assert_raise(IndexError) { m.end(2) }
m = /(?<x>q..)?/.match("foobarbaz")
assert_equal([nil, nil], m.offset("x"))
assert_equal(nil, m.begin("x"))
assert_equal(nil, m.end("x"))
m = /\A\u3042(.)(.)?(.)\z/.match("\u3042\u3043\u3044")
assert_equal([1, 2], m.offset(1))
assert_equal([nil, nil], m.offset(2))
assert_equal([2, 3], m.offset(3))
end
def test_match_to_s
m = /(?<x>b..)/.match("foobarbaz")
assert_equal("bar", m.to_s)
end
def test_match_pre_post
m = /(?<x>b..)/.match("foobarbaz")
assert_equal("foo", m.pre_match)
assert_equal("baz", m.post_match)
end
def test_match_array
m = /(...)(...)(...)(...)?/.match("foobarbaz")
assert_equal(["foobarbaz", "foo", "bar", "baz", nil], m.to_a)
end
def test_match_captures
m = /(...)(...)(...)(...)?/.match("foobarbaz")
assert_equal(["foo", "bar", "baz", nil], m.captures)
end
def test_match_aref
m = /(...)(...)(...)(...)?/.match("foobarbaz")
assert_equal("foobarbaz", m[0])
assert_equal("foo", m[1])
assert_equal("foo", m[-4])
assert_nil(m[-1])
assert_nil(m[-11])
assert_nil(m[-11, 1])
assert_nil(m[-11..1])
assert_nil(m[5])
assert_nil(m[9])
assert_equal(["foo", "bar", "baz"], m[1..3])
assert_equal(["foo", "bar", "baz"], m[1, 3])
assert_equal([], m[3..1])
assert_equal([], m[3, 0])
assert_equal(nil, m[3, -1])
assert_equal(nil, m[9, 1])
assert_equal(["baz"], m[3, 1])
assert_equal(["baz", nil], m[3, 5])
assert_nil(m[5])
assert_raise(IndexError) { m[:foo] }
assert_raise(TypeError) { m[nil] }
end
def test_match_values_at
idx = Object.new
def idx.to_int; 2; end
m = /(...)(...)(...)(...)?/.match("foobarbaz")
assert_equal(["foo", "bar", "baz"], m.values_at(1, 2, 3))
assert_equal(["foo", "bar", "baz"], m.values_at(1..3))
assert_equal(["foo", "bar", "baz", nil, nil], m.values_at(1..5))
assert_equal([], m.values_at(3..1))
assert_equal([nil, nil, nil, nil, nil], m.values_at(5..9))
assert_equal(["bar"], m.values_at(idx))
assert_raise(RangeError){ m.values_at(-11..1) }
assert_raise(TypeError){ m.values_at(nil) }
m = /(?<a>\d+) *(?<op>[+\-*\/]) *(?<b>\d+)/.match("1 + 2")
assert_equal(["1", "2", "+"], m.values_at(:a, 'b', :op))
assert_equal(["+"], m.values_at(idx))
assert_raise(TypeError){ m.values_at(nil) }
assert_raise(IndexError){ m.values_at(:foo) }
end
def test_match_string
m = /(?<x>b..)/.match("foobarbaz")
assert_equal("foobarbaz", m.string)
end
def test_match_inspect
m = /(...)(...)(...)(...)?/.match("foobarbaz")
assert_equal('#<MatchData "foobarbaz" 1:"foo" 2:"bar" 3:"baz" 4:nil>', m.inspect)
end
def test_initialize
assert_raise(ArgumentError) { Regexp.new }
assert_equal(/foo/, Regexp.new(/foo/, Regexp::IGNORECASE))
assert_equal(Encoding.find("US-ASCII"), Regexp.new("b..", nil, "n").encoding)
assert_equal("bar", "foobarbaz"[Regexp.new("b..", nil, "n")])
assert_equal(//n, Regexp.new("", nil, "n"))
arg_encoding_none = 32 # ARG_ENCODING_NONE is implementation defined value
assert_equal(arg_encoding_none, Regexp.new("", nil, "n").options)
assert_equal(arg_encoding_none, Regexp.new("", nil, "N").options)
assert_raise(RegexpError) { Regexp.new(")(") }
assert_raise(RegexpError) { Regexp.new('[\\40000000000') }
assert_raise(RegexpError) { Regexp.new('[\\600000000000.') }
assert_raise(RegexpError) { Regexp.new("((?<v>))\\g<0>") }
end
def test_unescape
assert_raise(ArgumentError) { s = '\\'; /#{ s }/ }
assert_equal(/\xFF/n, /#{ s="\\xFF" }/n)
assert_equal(/\177/, (s = '\177'; /#{ s }/))
assert_raise(ArgumentError) { s = '\u'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\u{ ffffffff }'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\u{ ffffff }'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\u{ ffff X }'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\u{ }'; /#{ s }/ }
assert_equal("b", "abc"[(s = '\u{0062}'; /#{ s }/)])
assert_equal("b", "abc"[(s = '\u0062'; /#{ s }/)])
assert_raise(ArgumentError) { s = '\u0'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\u000X'; /#{ s }/ }
assert_raise(ArgumentError) { s = "\xff" + '\u3042'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\u3042' + [0xff].pack("C"); /#{ s }/ }
assert_raise(SyntaxError) { s = ''; eval(%q(/\u#{ s }/)) }
assert_equal(/a/, eval(%q(s="\u0061";/#{s}/n)))
assert_raise(RegexpError) { s = "\u3042"; eval(%q(/#{s}/n)) }
assert_raise(RegexpError) { s = "\u0061"; eval(%q(/\u3042#{s}/n)) }
assert_raise(RegexpError) { s1=[0xff].pack("C"); s2="\u3042"; eval(%q(/#{s1}#{s2}/)); [s1, s2] }
assert_raise(ArgumentError) { s = '\x'; /#{ s }/ }
assert_equal("\xe1", [0x00, 0xe1, 0xff].pack("C*")[/\M-a/])
assert_equal("\xdc", [0x00, 0xdc, 0xff].pack("C*")[/\M-\\/])
assert_equal("\x8a", [0x00, 0x8a, 0xff].pack("C*")[/\M-\n/])
assert_equal("\x89", [0x00, 0x89, 0xff].pack("C*")[/\M-\t/])
assert_equal("\x8d", [0x00, 0x8d, 0xff].pack("C*")[/\M-\r/])
assert_equal("\x8c", [0x00, 0x8c, 0xff].pack("C*")[/\M-\f/])
assert_equal("\x8b", [0x00, 0x8b, 0xff].pack("C*")[/\M-\v/])
assert_equal("\x87", [0x00, 0x87, 0xff].pack("C*")[/\M-\a/])
assert_equal("\x9b", [0x00, 0x9b, 0xff].pack("C*")[/\M-\e/])
assert_equal("\x01", [0x00, 0x01, 0xff].pack("C*")[/\C-a/])
assert_raise(ArgumentError) { s = '\M'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\M-\M-a'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\M-\\'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\C'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\c'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\C-\C-a'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\M-\z'; /#{ s }/ }
assert_raise(ArgumentError) { s = '\M-\777'; /#{ s }/ }
assert_equal("\u3042\u3042", "\u3042\u3042"[(s = "\u3042" + %q(\xe3\x81\x82); /#{s}/)])
assert_raise(ArgumentError) { s = "\u3042" + %q(\xe3); /#{s}/ }
assert_raise(ArgumentError) { s = "\u3042" + %q(\xe3\xe3); /#{s}/ }
assert_raise(ArgumentError) { s = '\u3042' + [0xff].pack("C"); /#{s}/ }
assert_raise(SyntaxError) { eval("/\u3042/n") }
s = ".........."
5.times { s.sub!(".", "") }
assert_equal(".....", s)
assert_equal("\\\u{3042}", Regexp.new("\\\u{3042}").source)
end
def test_equal
bug5484 = '[ruby-core:40364]'
assert_equal(/abc/, /abc/)
assert_not_equal(/abc/, /abc/m)
assert_not_equal(/abc/, /abd/)
assert_equal(/\/foo/, Regexp.new('/foo'), bug5484)
end
def test_match
assert_nil(//.match(nil))
assert_equal("abc", /.../.match(:abc)[0])
assert_raise(TypeError) { /.../.match(Object.new)[0] }
assert_equal("bc", /../.match('abc', 1)[0])
assert_equal("bc", /../.match('abc', -2)[0])
assert_nil(/../.match("abc", -4))
assert_nil(/../.match("abc", 4))
assert_equal('\x', /../n.match("\u3042" + '\x', 1)[0])
r = nil
/.../.match("abc") {|m| r = m[0] }
assert_equal("abc", r)
$_ = "abc"; assert_equal(1, ~/bc/)
$_ = "abc"; assert_nil(~/d/)
$_ = nil; assert_nil(~/./)
end
def test_match_p
/backref/ =~ 'backref'
# must match here, but not in a separate method, e.g., assert_send,
# to check if $~ is affected or not.
assert_equal(false, //.match?(nil))
assert_equal(true, //.match?(""))
assert_equal(true, /.../.match?(:abc))
assert_raise(TypeError) { /.../.match?(Object.new) }
assert_equal(true, /b/.match?('abc'))
assert_equal(true, /b/.match?('abc', 1))
assert_equal(true, /../.match?('abc', 1))
assert_equal(true, /../.match?('abc', -2))
assert_equal(false, /../.match?("abc", -4))
assert_equal(false, /../.match?("abc", 4))
assert_equal(true, /../.match?("\u3042xx", 1))
assert_equal(false, /../.match?("\u3042x", 1))
assert_equal(true, /\z/.match?(""))
assert_equal(true, /\z/.match?("abc"))
assert_equal(true, /R.../.match?("Ruby"))
assert_equal(false, /R.../.match?("Ruby", 1))
assert_equal(false, /P.../.match?("Ruby"))
assert_equal('backref', $&)
end
def test_eqq
assert_equal(false, /../ === nil)
end
def test_quote
assert_equal("\xff", Regexp.quote([0xff].pack("C")))
assert_equal("\\ ", Regexp.quote("\ "))
assert_equal("\\t", Regexp.quote("\t"))
assert_equal("\\n", Regexp.quote("\n"))
assert_equal("\\r", Regexp.quote("\r"))
assert_equal("\\f", Regexp.quote("\f"))
assert_equal("\\v", Regexp.quote("\v"))
assert_equal("\u3042\\t", Regexp.quote("\u3042\t"))
assert_equal("\\t\xff", Regexp.quote("\t" + [0xff].pack("C")))
bug13034 = '[ruby-core:78646] [Bug #13034]'
str = "\x00".force_encoding("UTF-16BE")
assert_equal(str, Regexp.quote(str), bug13034)
end
def test_try_convert
assert_equal(/re/, Regexp.try_convert(/re/))
assert_nil(Regexp.try_convert("re"))
o = Object.new
assert_nil(Regexp.try_convert(o))
def o.to_regexp() /foo/ end
assert_equal(/foo/, Regexp.try_convert(o))
end
def test_union2
assert_equal(/(?!)/, Regexp.union)
assert_equal(/foo/, Regexp.union(/foo/))
assert_equal(/foo/, Regexp.union([/foo/]))
assert_equal(/\t/, Regexp.union("\t"))
assert_equal(/(?-mix:\u3042)|(?-mix:\u3042)/, Regexp.union(/\u3042/, /\u3042/))
assert_equal("\u3041", "\u3041"[Regexp.union(/\u3042/, "\u3041")])
end
def test_dup
assert_equal(//, //.dup)
assert_raise(TypeError) { //.instance_eval { initialize_copy(nil) } }
end
def test_regsub
assert_equal("fooXXXbaz", "foobarbaz".sub!(/bar/, "XXX"))
s = [0xff].pack("C")
assert_equal(s, "X".sub!(/./, s))
assert_equal('\\' + s, "X".sub!(/./, '\\' + s))
assert_equal('\k', "foo".sub!(/.../, '\k'))
assert_raise(RuntimeError) { "foo".sub!(/(?<x>o)/, '\k<x') }
assert_equal('foo[bar]baz', "foobarbaz".sub!(/(b..)/, '[\0]'))
assert_equal('foo[foo]baz', "foobarbaz".sub!(/(b..)/, '[\`]'))
assert_equal('foo[baz]baz', "foobarbaz".sub!(/(b..)/, '[\\\']'))
assert_equal('foo[r]baz', "foobarbaz".sub!(/(b)(.)(.)/, '[\+]'))
assert_equal('foo[\\]baz', "foobarbaz".sub!(/(b..)/, '[\\\\]'))
assert_equal('foo[\z]baz', "foobarbaz".sub!(/(b..)/, '[\z]'))
end
def test_regsub_K
bug8856 = '[ruby-dev:47694] [Bug #8856]'
result = "foobarbazquux/foobarbazquux".gsub(/foo\Kbar/, "")
assert_equal('foobazquux/foobazquux', result, bug8856)
end
def test_KCODE
assert_nil($KCODE)
assert_nothing_raised { $KCODE = nil }
assert_equal(false, $=)
assert_nothing_raised { $= = nil }
end
def test_KCODE_warning
assert_warning(/variable \$KCODE is no longer effective; ignored/) { $KCODE = nil }
assert_warning(/variable \$KCODE is no longer effective/) { $KCODE = nil }
end
def test_ignorecase_warning
assert_warning(/variable \$= is no longer effective; ignored/) { $= = nil }
assert_warning(/variable \$= is no longer effective/) { $= }
end
def test_match_setter
/foo/ =~ "foo"
m = $~
/bar/ =~ "bar"
$~ = m
assert_equal("foo", $&)
end
def test_match_without_regexp
# create a MatchData for each assertion because the internal state may change
test = proc {|&blk| "abc".sub("a", ""); blk.call($~) }
bug10877 = '[ruby-core:68209] [Bug #10877]'
test.call {|m| assert_raise_with_message(IndexError, /foo/, bug10877) {m["foo"]} }
key = "\u{3042}"
[Encoding::UTF_8, Encoding::Shift_JIS, Encoding::EUC_JP].each do |enc|
idx = key.encode(enc)
test.call {|m| assert_raise_with_message(IndexError, /#{idx}/, bug10877) {m[idx]} }
end
test.call {|m| assert_equal(/a/, m.regexp) }
test.call {|m| assert_equal("abc", m.string) }
test.call {|m| assert_equal(1, m.size) }
test.call {|m| assert_equal(0, m.begin(0)) }
test.call {|m| assert_equal(1, m.end(0)) }
test.call {|m| assert_equal([0, 1], m.offset(0)) }
test.call {|m| assert_equal([], m.captures) }
test.call {|m| assert_equal([], m.names) }
test.call {|m| assert_equal({}, m.named_captures) }
test.call {|m| assert_equal(/a/.match("abc"), m) }
test.call {|m| assert_equal(/a/.match("abc").hash, m.hash) }
test.call {|m| assert_equal("bc", m.post_match) }
test.call {|m| assert_equal("", m.pre_match) }
test.call {|m| assert_equal(["a", nil], m.values_at(0, 1)) }
end
def test_last_match
/(...)(...)(...)(...)?/.match("foobarbaz")
assert_equal("foobarbaz", Regexp.last_match(0))
assert_equal("foo", Regexp.last_match(1))
assert_nil(Regexp.last_match(5))
assert_nil(Regexp.last_match(-1))
end
def test_getter
alias $__REGEXP_TEST_LASTMATCH__ $&
alias $__REGEXP_TEST_PREMATCH__ $`
alias $__REGEXP_TEST_POSTMATCH__ $'
alias $__REGEXP_TEST_LASTPARENMATCH__ $+
/(b)(.)(.)/.match("foobarbaz")
assert_equal("bar", $__REGEXP_TEST_LASTMATCH__)
assert_equal("foo", $__REGEXP_TEST_PREMATCH__)
assert_equal("baz", $__REGEXP_TEST_POSTMATCH__)
assert_equal("r", $__REGEXP_TEST_LASTPARENMATCH__)
/(...)(...)(...)/.match("foobarbaz")
assert_equal("baz", $+)
end
def test_rindex_regexp
assert_equal(3, "foobarbaz\u3042".rindex(/b../n, 5))
end
def assert_regexp(re, ss, fs = [], msg = nil)
re = Regexp.new(re) unless re.is_a?(Regexp)
ss = [ss] unless ss.is_a?(Array)
ss.each do |e, s|
s ||= e
assert_match(re, s, msg)
m = re.match(s)
assert_equal(e, m[0], msg)
end
fs = [fs] unless fs.is_a?(Array)
fs.each {|s| assert_no_match(re, s, msg) }
end
alias check assert_regexp
def assert_fail(re)
assert_raise(RegexpError) { %r"#{ re }" }
end
alias failcheck assert_fail
def test_parse
check(/\*\+\?\{\}\|\(\)\<\>\`\'/, "*+?{}|()<>`'")
check(/\A\w\W\z/, %w(a. b!), %w(.. ab))
check(/\A.\b.\b.\B.\B.\z/, %w(a.aaa .a...), %w(aaaaa .....))
check(/\A\s\S\z/, [' a', "\n."], [' ', "\n\n", 'a '])
check(/\A\d\D\z/, '0a', %w(00 aa))
check(/\A\h\H\z/, %w(0g ag BH), %w(a0 af GG))
check(/\Afoo\Z\s\z/, "foo\n", ["foo", "foo\nbar"])
assert_equal(%w(a b c), "abc def".scan(/\G\w/))
check(/\A\u3042\z/, "\u3042", ["", "\u3043", "a"])
check(/\A(..)\1\z/, %w(abab ....), %w(abba aba))
failcheck('\1')
check(/\A\80\z/, "80", ["\100", ""])
check(/\A\77\z/, "?")
check(/\A\78\z/, "\7" + '8', ["\100", ""])
check(eval('/\A\Qfoo\E\z/'), "QfooE")
check(/\Aa++\z/, "aaa")
check('\Ax]\z', "x]")
check(/x#foo/x, "x", "#foo")
check(/\Ax#foo#{ "\n" }x\z/x, "xx", ["x", "x#foo\nx"])
check(/\A\p{Alpha}\z/, ["a", "z"], [".", "", ".."])
check(/\A\p{^Alpha}\z/, [".", "!"], ["!a", ""])
check(/\A\n\z/, "\n")
check(/\A\t\z/, "\t")
check(/\A\r\z/, "\r")
check(/\A\f\z/, "\f")
check(/\A\a\z/, "\007")
check(/\A\e\z/, "\033")
check(/\A\v\z/, "\v")
failcheck('(')
failcheck('(?foo)')
failcheck('/\p{foobarbazqux}/')
failcheck('/\p{foobarbazqux' + 'a' * 1000 + '}/')
failcheck('/[1-\w]/')
end
def test_exec
check(/A*B/, %w(B AB AAB AAAB), %w(A))
check(/\w*!/, %w(! a! ab! abc!), %w(abc))
check(/\w*\W/, %w(! a" ab# abc$), %w(abc))
check(/\w*\w/, %w(z az abz abcz), %w(!))
check(/[a-z]*\w/, %w(z az abz abcz), %w(!))
check(/[a-z]*\W/, %w(! a" ab# abc$), %w(A))
check(/((a|bb|ccc|dddd)(1|22|333|4444))/i, %w(a1 bb1 a22), %w(a2 b1))
check(/\u0080/, (1..4).map {|i| ["\u0080", "\u0080" * i] }, ["\u0081"])
check(/\u0080\u0080/, (2..4).map {|i| ["\u0080" * 2, "\u0080" * i] }, ["\u0081"])
check(/\u0080\u0080\u0080/, (3..4).map {|i| ["\u0080" * 3, "\u0080" * i] }, ["\u0081"])
check(/\u0080\u0080\u0080\u0080/, (4..4).map {|i| ["\u0080" * 4, "\u0080" * i] }, ["\u0081"])
check(/[^\u3042\u3043\u3044]/, %W(a b \u0080 \u3041 \u3045), %W(\u3042 \u3043 \u3044))
check(/a.+/m, %W(a\u0080 a\u0080\u0080 a\u0080\u0080\u0080), %W(a))
check(/a.+z/m, %W(a\u0080z a\u0080\u0080z a\u0080\u0080\u0080z), %W(az))
check(/abc\B.\Bxyz/, %w(abcXxyz abc0xyz), %w(abc|xyz abc-xyz))
check(/\Bxyz/, [%w(xyz abcXxyz), %w(xyz abc0xyz)], %w(abc xyz abc-xyz))
check(/abc\B/, [%w(abc abcXxyz), %w(abc abc0xyz)], %w(abc xyz abc-xyz))
failcheck('(?<foo>abc)\1')
check(/^(A+|B+)(?>\g<1>)*[BC]$/, %w(AC BC ABC BAC AABBC), %w(AABB))
check(/^(A+|B(?>\g<1>)*)[AC]$/, %w(AAAC BBBAAAAC), %w(BBBAAA))
check(/^()(?>\g<1>)*$/, "", "a")
check(/^(?>(?=a)(#{ "a" * 1000 }|))++$/, ["a" * 1000, "a" * 2000, "a" * 3000], ["", "a" * 500, "b" * 1000])
check(eval('/^(?:a?)?$/'), ["", "a"], ["aa"])
check(eval('/^(?:a+)?$/'), ["", "a", "aa"], ["ab"])
check(/^(?:a?)+?$/, ["", "a", "aa"], ["ab"])
check(/^a??[ab]/, [["a", "a"], ["a", "aa"], ["b", "b"], ["a", "ab"]], ["c"])
check(/^(?:a*){3,5}$/, ["", "a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa"], ["b"])
check(/^(?:a+){3,5}$/, ["aaa", "aaaa", "aaaaa", "aaaaaa"], ["", "a", "aa", "b"])
end
def test_parse_look_behind
check(/(?<=A)B(?=C)/, [%w(B ABC)], %w(aBC ABc aBc))
check(/(?<!A)B(?!C)/, [%w(B aBc)], %w(ABC aBC ABc))
failcheck('(?<=.*)')
failcheck('(?<!.*)')
check(/(?<=A|B.)C/, [%w(C AC), %w(C BXC)], %w(C BC))
check(/(?<!A|B.)C/, [%w(C C), %w(C BC)], %w(AC BXC))
assert_not_match(/(?<!aa|b)c/i, "Aac")
assert_not_match(/(?<!b|aa)c/i, "Aac")
end
def test_parse_kg
check(/\A(.)(.)\k<1>(.)\z/, %w(abac abab ....), %w(abcd aaba xxx))
check(/\A(.)(.)\k<-1>(.)\z/, %w(abbc abba ....), %w(abcd aaba xxx))
check(/\A(?<n>.)(?<x>\g<n>){0}(?<y>\k<n+0>){0}\g<x>\g<y>\z/, "aba", "abb")
check(/\A(?<n>.)(?<x>\g<n>){0}(?<y>\k<n+1>){0}\g<x>\g<y>\z/, "abb", "aba")
check(/\A(?<x>..)\k<x>\z/, %w(abab ....), %w(abac abba xxx))
check(/\A(.)(..)\g<-1>\z/, "abcde", %w(.... ......))
failcheck('\k<x>')
failcheck('\k<')
failcheck('\k<>')
failcheck('\k<.>')
failcheck('\k<x.>')
failcheck('\k<1.>')
failcheck('\k<x')
failcheck('\k<x+')
failcheck('()\k<-2>')
failcheck('()\g<-2>')
check(/\A(?<x>.)(?<x>.)\k<x>\z/, %w(aba abb), %w(abc .. ....))
check(/\A(?<x>.)(?<x>.)\k<x>\z/i, %w(aba ABa abb ABb), %w(abc .. ....))
check('\k\g', "kg")
failcheck('(.\g<1>)')
failcheck('(.\g<2>)')
failcheck('(?=\g<1>)')
failcheck('((?=\g<1>))')
failcheck('(\g<1>|.)')
failcheck('(.|\g<1>)')
check(/(!)(?<=(a)|\g<1>)/, ["!"], %w(a))
check(/^(a|b\g<1>c)$/, %w(a bac bbacc bbbaccc), %w(bbac bacc))
check(/^(a|b\g<2>c)(B\g<1>C){0}$/, %w(a bBaCc bBbBaCcCc bBbBbBaCcCcCc), %w(bBbBaCcC BbBaCcCc))
check(/\A(?<n>.|X\g<n>)(?<x>\g<n>){0}(?<y>\k<n+0>){0}\g<x>\g<y>\z/, "XXaXbXXa", %w(XXabXa abb))
check(/\A(?<n>.|X\g<n>)(?<x>\g<n>){0}(?<y>\k<n+1>){0}\g<x>\g<y>\z/, "XaXXbXXb", %w(aXXbXb aba))
failcheck('(?<x>)(?<x>)(\g<x>)')
check(/^(?<x>foo)(bar)\k<x>/, %w(foobarfoo), %w(foobar barfoo))
check(/^(?<a>f)(?<a>o)(?<a>o)(?<a>b)(?<a>a)(?<a>r)(?<a>b)(?<a>a)(?<a>z)\k<a>{9}$/, %w(foobarbazfoobarbaz foobarbazbazbarfoo foobarbazzabraboof), %w(foobar barfoo))
end
def test_parse_curly_brace
check(/\A{/, ["{", ["{", "{x"]])
check(/\A{ /, ["{ ", ["{ ", "{ x"]])
check(/\A{,}\z/, "{,}")
check(/\A{}\z/, "{}")
check(/\Aa{0}+\z/, "", %w(a aa aab))
check(/\Aa{1}+\z/, %w(a aa), ["", "aab"])
check(/\Aa{1,2}b{1,2}\z/, %w(ab aab abb aabb), ["", "aaabb", "abbb"])
check(/(?!x){0,1}/, [ ['', 'ab'], ['', ''] ])
check(/c\z{0,1}/, [ ['c', 'abc'], ['c', 'cab']], ['abd'])
check(/\A{0,1}a/, [ ['a', 'abc'], ['a', '____abc']], ['bcd'])
failcheck('.{100001}')
failcheck('.{0,100001}')
failcheck('.{1,0}')
failcheck('{0}')
end
def test_parse_comment
check(/\A(?#foo\)bar)\z/, "", "a")
failcheck('(?#')
end
def test_char_type
check(/\u3042\d/, ["\u30421", "\u30422"])
# CClassTable cache test
assert_match(/\u3042\d/, "\u30421")
assert_match(/\u3042\d/, "\u30422")
end
def test_char_class
failcheck('[]')
failcheck('[x')
check('\A[]]\z', "]", "")
check('\A[]\.]+\z', %w(] . ]..]), ["", "["])
check(/\A[\u3042]\z/, "\u3042", "\u3042aa")
check(/\A[\u3042\x61]+\z/, ["aa\u3042aa", "\u3042\u3042", "a"], ["", "b"])
check(/\A[\u3042\x61\x62]+\z/, "abab\u3042abab\u3042")
check(/\A[abc]+\z/, "abcba", ["", "ada"])
check(/\A[\w][\W]\z/, %w(a. b!), %w(.. ab))
check(/\A[\s][\S]\z/, [' a', "\n."], [' ', "\n\n", 'a '])
check(/\A[\d][\D]\z/, '0a', %w(00 aa))
check(/\A[\h][\H]\z/, %w(0g ag BH), %w(a0 af GG))
check(/\A[\p{Alpha}]\z/, ["a", "z"], [".", "", ".."])
check(/\A[\p{^Alpha}]\z/, [".", "!"], ["!a", ""])
check(/\A[\xff]\z/, "\xff", ["", "\xfe"])
check(/\A[\80]+\z/, "8008", ["\\80", "\100", "\1000"])
check(/\A[\77]+\z/, "???")
check(/\A[\78]+\z/, "\788\7")
check(/\A[\0]\z/, "\0")
check(/\A[[:0]]\z/, [":", "0"], ["", ":0"])
check(/\A[0-]\z/, ["0", "-"], "0-")
check('\A[a-&&\w]\z', "a", "-")
check('\A[--0]\z', ["-", "/", "0"], ["", "1"])
check('\A[\'--0]\z', %w(* + \( \) 0 ,), ["", ".", "1"])
check(/\A[a-b-]\z/, %w(a b -), ["", "c"])
check('\A[a-b-&&\w]\z', %w(a b), ["", "-"])
check('\A[a-b-&&\W]\z', "-", ["", "a", "b"])
check('\A[a-c-e]\z', %w(a b c e -), %w(d))
check(/\A[a-f&&[^b-c]&&[^e]]\z/, %w(a d f), %w(b c e g 0))
check(/\A[[^b-c]&&[^e]&&a-f]\z/, %w(a d f), %w(b c e g 0))
check(/\A[\n\r\t]\z/, ["\n", "\r", "\t"])
failcheck('[9-1]')
assert_match(/\A\d+\z/, "0123456789")
assert_no_match(/\d/, "\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19")
assert_match(/\A\w+\z/, "09azAZ_")
assert_no_match(/\w/, "\uff10\uff19\uff41\uff5a\uff21\uff3a")
assert_match(/\A\s+\z/, "\r\n\v\f\r\s")
assert_no_match(/\s/, "\u0085")
end
def test_posix_bracket
check(/\A[[:alpha:]0]\z/, %w(0 a), %w(1 .))
check(eval('/\A[[:^alpha:]0]\z/'), %w(0 1 .), "a")
check(eval('/\A[[:alpha\:]]\z/'), %w(a l p h a :), %w(b 0 1 .))
check(eval('/\A[[:alpha:foo]0]\z/'), %w(0 a), %w(1 .))
check(/\A[[:xdigit:]&&[:alpha:]]\z/, "a", %w(g 0))
check('\A[[:abcdefghijklmnopqrstu:]]+\z', "[]")
failcheck('[[:alpha')
failcheck('[[:alpha:')
failcheck('[[:alp:]]')
assert_match(/\A[[:digit:]]+\z/, "\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19")
assert_match(/\A[[:alnum:]]+\z/, "\uff10\uff19\uff41\uff5a\uff21\uff3a")
assert_match(/\A[[:space:]]+\z/, "\r\n\v\f\r\s\u0085")
assert_match(/\A[[:ascii:]]+\z/, "\x00\x7F")
assert_no_match(/[[:ascii:]]/, "\x80\xFF")
end
def test_cclass_R
assert_match /\A\R\z/, "\r"
assert_match /\A\R\z/, "\n"
assert_match /\A\R\z/, "\r\n"
end
def test_cclass_X
assert_match /\A\X\z/, "\u{20 200d}"
assert_match /\A\X\z/, "\u{600 600}"
assert_match /\A\X\z/, "\u{600 20}"
assert_match /\A\X\z/, "\u{261d 1F3FB}"
assert_match /\A\X\z/, "\u{1f600}"
assert_match /\A\X\z/, "\u{20 324}"
assert_match /\A\X\X\z/, "\u{a 324}"
assert_match /\A\X\X\z/, "\u{d 324}"
assert_match /\A\X\z/, "\u{1F477 1F3FF 200D 2640 FE0F}"
assert_match /\A\X\z/, "\u{1F468 200D 1F393}"
assert_match /\A\X\z/, "\u{1F46F 200D 2642 FE0F}"
assert_match /\A\X\z/, "\u{1f469 200d 2764 fe0f 200d 1f469}"
assert_warning('') {/\X/ =~ "\u{a0}"}
end
def test_backward
assert_equal(3, "foobar".rindex(/b.r/i))
assert_equal(nil, "foovar".rindex(/b.r/i))
assert_equal(3, ("foo" + "bar" * 1000).rindex(/#{"bar"*1000}/))
assert_equal(4, ("foo\nbar\nbaz\n").rindex(/bar/i))
end
def test_uninitialized
assert_raise(TypeError) { Regexp.allocate.hash }
assert_raise(TypeError) { Regexp.allocate.eql? Regexp.allocate }
assert_raise(TypeError) { Regexp.allocate == Regexp.allocate }
assert_raise(TypeError) { Regexp.allocate =~ "" }
assert_equal(false, Regexp.allocate === Regexp.allocate)
assert_nil(~Regexp.allocate)
assert_raise(TypeError) { Regexp.allocate.match("") }
assert_raise(TypeError) { Regexp.allocate.to_s }
assert_match(/^#<Regexp:.*>$/, Regexp.allocate.inspect)
assert_raise(TypeError) { Regexp.allocate.source }
assert_raise(TypeError) { Regexp.allocate.casefold? }
assert_raise(TypeError) { Regexp.allocate.options }
assert_equal(Encoding.find("ASCII-8BIT"), Regexp.allocate.encoding)
assert_equal(false, Regexp.allocate.fixed_encoding?)
assert_raise(TypeError) { Regexp.allocate.names }
assert_raise(TypeError) { Regexp.allocate.named_captures }
assert_raise(TypeError) { MatchData.allocate.hash }
assert_raise(TypeError) { MatchData.allocate.regexp }
assert_raise(TypeError) { MatchData.allocate.names }
assert_raise(TypeError) { MatchData.allocate.size }
assert_raise(TypeError) { MatchData.allocate.length }
assert_raise(TypeError) { MatchData.allocate.offset(0) }
assert_raise(TypeError) { MatchData.allocate.begin(0) }
assert_raise(TypeError) { MatchData.allocate.end(0) }
assert_raise(TypeError) { MatchData.allocate.to_a }
assert_raise(TypeError) { MatchData.allocate[:foo] }
assert_raise(TypeError) { MatchData.allocate.captures }
assert_raise(TypeError) { MatchData.allocate.values_at }
assert_raise(TypeError) { MatchData.allocate.pre_match }
assert_raise(TypeError) { MatchData.allocate.post_match }
assert_raise(TypeError) { MatchData.allocate.to_s }
assert_match(/^#<MatchData:.*>$/, MatchData.allocate.inspect)
assert_raise(TypeError) { MatchData.allocate.string }
$~ = MatchData.allocate
assert_raise(TypeError) { $& }
assert_raise(TypeError) { $` }
assert_raise(TypeError) { $' }
assert_raise(TypeError) { $+ }
end
def test_unicode
assert_match(/^\u3042{0}\p{Any}$/, "a")
assert_match(/^\u3042{0}\p{Any}$/, "\u3041")
assert_match(/^\u3042{0}\p{Any}$/, "\0")
assert_match(/^\p{Lo}{4}$/u, "\u3401\u4E01\u{20001}\u{2A701}")
assert_no_match(/^\u3042{0}\p{Any}$/, "\0\0")
assert_no_match(/^\u3042{0}\p{Any}$/, "")
assert_raise(SyntaxError) { eval('/^\u3042{0}\p{' + "\u3042" + '}$/') }
assert_raise(SyntaxError) { eval('/^\u3042{0}\p{' + 'a' * 1000 + '}$/') }
assert_raise(SyntaxError) { eval('/^\u3042{0}\p{foobarbazqux}$/') }
assert_match(/^(\uff21)(a)\1\2$/i, "\uff21A\uff41a")
assert_no_match(/^(\uff21)\1$/i, "\uff21A")
assert_no_match(/^(\uff41)\1$/i, "\uff41a")
assert_match(/^\u00df$/i, "\u00df")
assert_match(/^\u00df$/i, "ss")
#assert_match(/^(\u00df)\1$/i, "\u00dfss") # this must be bug...
assert_match(/^\u00df{2}$/i, "\u00dfss")
assert_match(/^\u00c5$/i, "\u00c5")
assert_match(/^\u00c5$/i, "\u00e5")
assert_match(/^\u00c5$/i, "\u212b")
assert_match(/^(\u00c5)\1\1$/i, "\u00c5\u00e5\u212b")
assert_match(/^\u0149$/i, "\u0149")
assert_match(/^\u0149$/i, "\u02bcn")
#assert_match(/^(\u0149)\1$/i, "\u0149\u02bcn") # this must be bug...
assert_match(/^\u0149{2}$/i, "\u0149\u02bcn")
assert_match(/^\u0390$/i, "\u0390")
assert_match(/^\u0390$/i, "\u03b9\u0308\u0301")
#assert_match(/^(\u0390)\1$/i, "\u0390\u03b9\u0308\u0301") # this must be bug...
assert_match(/^\u0390{2}$/i, "\u0390\u03b9\u0308\u0301")
assert_match(/^\ufb05$/i, "\ufb05")
assert_match(/^\ufb05$/i, "\ufb06")
assert_match(/^\ufb05$/i, "st")
#assert_match(/^(\ufb05)\1\1$/i, "\ufb05\ufb06st") # this must be bug...
assert_match(/^\ufb05{3}$/i, "\ufb05\ufb06st")
assert_match(/^\u03b9\u0308\u0301$/i, "\u0390")
end
def test_unicode_age
assert_match(/^\p{Age=6.0}$/u, "\u261c")
assert_match(/^\p{Age=1.1}$/u, "\u261c")
assert_no_match(/^\P{age=6.0}$/u, "\u261c")
assert_match(/^\p{age=6.0}$/u, "\u31f6")
assert_match(/^\p{age=3.2}$/u, "\u31f6")
assert_no_match(/^\p{age=3.1}$/u, "\u31f6")
assert_no_match(/^\p{age=3.0}$/u, "\u31f6")
assert_no_match(/^\p{age=1.1}$/u, "\u31f6")
assert_match(/^\p{age=6.0}$/u, "\u2754")
assert_no_match(/^\p{age=5.0}$/u, "\u2754")
assert_no_match(/^\p{age=4.0}$/u, "\u2754")
assert_no_match(/^\p{age=3.0}$/u, "\u2754")
assert_no_match(/^\p{age=2.0}$/u, "\u2754")
assert_no_match(/^\p{age=1.1}$/u, "\u2754")
end
MatchData_A = eval("class MatchData_\u{3042} < MatchData; self; end")
def test_matchdata
a = "haystack".match(/hay/)
b = "haystack".match(/hay/)
assert_equal(a, b, '[ruby-core:24748]')
h = {a => 42}
assert_equal(42, h[b], '[ruby-core:24748]')
assert_match(/#<TestRegexp::MatchData_\u{3042}:/, MatchData_A.allocate.inspect)
h = /^(?<@time>\d+): (?<body>.*)/.match("123456: hoge fuga")
assert_equal("123456", h["@time"])
assert_equal("hoge fuga", h["body"])
end
def test_regexp_popped
assert_nothing_raised { eval("a = 1; /\#{ a }/; a") }
assert_nothing_raised { eval("a = 1; /\#{ a }/o; a") }
end
def test_invalid_fragment
bug2547 = '[ruby-core:27374]'
assert_raise(SyntaxError, bug2547) {eval('/#{"\\\\"}y/')}
end
def test_dup_warn
assert_warning(/duplicated/) { Regexp.new('[\u3042\u3043\u3042]') }
assert_warning(/duplicated/) { Regexp.new('[\u3042\u3043\u3043]') }
assert_warning(/\A\z/) { Regexp.new('[\u3042\u3044\u3043]') }
assert_warning(/\A\z/) { Regexp.new('[\u3042\u3045\u3043]') }
assert_warning(/\A\z/) { Regexp.new('[\u3042\u3045\u3044]') }
assert_warning(/\A\z/) { Regexp.new('[\u3042\u3045\u3043-\u3044]') }
assert_warning(/duplicated/) { Regexp.new('[\u3042\u3045\u3042-\u3043]') }
assert_warning(/duplicated/) { Regexp.new('[\u3042\u3045\u3044-\u3045]') }
assert_warning(/\A\z/) { Regexp.new('[\u3042\u3046\u3044]') }
assert_warning(/duplicated/) { Regexp.new('[\u1000-\u2000\u3042-\u3046\u3044]') }
assert_warning(/duplicated/) { Regexp.new('[\u3044\u3041-\u3047]') }
assert_warning(/duplicated/) { Regexp.new('[\u3042\u3044\u3046\u3041-\u3047]') }
bug7471 = '[ruby-core:50344]'
assert_warning('', bug7471) { Regexp.new('[\D]') =~ "\u3042" }
bug8151 = '[ruby-core:53649]'
assert_warning(/\A\z/, bug8151) { Regexp.new('(?:[\u{33}])').to_s }
end
def test_property_warn
assert_in_out_err('-w', 'x=/\p%s/', [], %r"warning: invalid Unicode Property \\p: /\\p%s/")
end
def test_invalid_escape_error
bug3539 = '[ruby-core:31048]'
error = assert_raise(SyntaxError) {eval('/\x/', nil, bug3539)}
assert_match(/invalid hex escape/, error.message)
assert_equal(1, error.message.scan(/.*invalid .*escape.*/i).size, bug3539)
end
def test_raw_hyphen_and_tk_char_type_after_range
bug6853 = '[ruby-core:47115]'
# use Regexp.new instead of literal to ignore a parser warning.
check(Regexp.new('[0-1-\\s]'), [' ', '-'], ['2', 'a'], bug6853)
end
def test_error_message_on_failed_conversion
bug7539 = '[ruby-core:50733]'
assert_equal false, /x/=== 42
assert_raise_with_message(TypeError, 'no implicit conversion of Integer into String', bug7539) {
Regexp.quote(42)
}
end
def test_conditional_expression
bug8583 = '[ruby-dev:47480] [Bug #8583]'
conds = {"xy"=>true, "yx"=>true, "xx"=>false, "yy"=>false}
assert_match_each(/\A((x)|(y))(?(2)y|x)\z/, conds, bug8583)
assert_match_each(/\A((?<x>x)|(?<y>y))(?(<x>)y|x)\z/, conds, bug8583)
bug12418 = '[ruby-core:75694] [Bug #12418]'
assert_raise(RegexpError, bug12418){ Regexp.new('(0?0|(?(5)||)|(?(5)||))?') }
end
def test_options_in_look_behind
assert_nothing_raised {
assert_match_at("(?<=(?i)ab)cd", "ABcd", [[2,4]])
assert_match_at("(?<=(?i:ab))cd", "ABcd", [[2,4]])
assert_match_at("(?<!(?i)ab)cd", "aacd", [[2,4]])
assert_match_at("(?<!(?i:ab))cd", "aacd", [[2,4]])
assert_not_match("(?<=(?i)ab)cd", "ABCD")
assert_not_match("(?<=(?i:ab))cd", "ABCD")
assert_not_match("(?<!(?i)ab)cd", "ABcd")
assert_not_match("(?<!(?i:ab))cd", "ABcd")
}
end
def test_once
pr1 = proc{|i| /#{i}/o}
assert_equal(/0/, pr1.call(0))
assert_equal(/0/, pr1.call(1))
assert_equal(/0/, pr1.call(2))
end
def test_once_recursive
pr2 = proc{|i|
if i > 0
/#{pr2.call(i-1).to_s}#{i}/
else
//
end
}
assert_equal(/(?-mix:(?-mix:(?-mix:)1)2)3/, pr2.call(3))
end
def test_once_multithread
m = Thread::Mutex.new
pr3 = proc{|i|
/#{m.unlock; sleep 0.5; i}/o
}
ary = []
n = 0
th1 = Thread.new{m.lock; ary << pr3.call(n+=1)}
th2 = Thread.new{m.lock; ary << pr3.call(n+=1)}
th1.join; th2.join
assert_equal([/1/, /1/], ary)
end
def test_once_escape
pr4 = proc{|i|
catch(:xyzzy){
/#{throw :xyzzy, i}/o =~ ""
:ng
}
}
assert_equal(0, pr4.call(0))
assert_equal(1, pr4.call(1))
end
def test_eq_tilde_can_be_overridden
assert_separately([], <<-RUBY)
class Regexp
undef =~
def =~(str)
"foo"
end
end
assert_equal("foo", // =~ "")
RUBY
end
def test_invalid_free_at_parse_depth_limit_over
assert_separately([], "#{<<-"begin;"}\n#{<<-"end;"}")
begin;
begin
require '-test-/regexp'
rescue LoadError
else
bug = '[ruby-core:79624] [Bug #13234]'
Bug::Regexp.parse_depth_limit = 10
src = "[" * 100
3.times do
assert_raise_with_message(RegexpError, /parse depth limit over/, bug) do
Regexp.new(src)
end
end
end
end;
end
def test_absent
assert_equal(0, /(?~(a|c)c)/ =~ "abb")
assert_equal("abb", $&)
assert_equal(0, /\/\*((?~\*\/))\*\// =~ "/*abc*def/xyz*/ /* */")
assert_equal("abc*def/xyz", $1)
assert_equal(0, /(?~(a)c)/ =~ "abb")
assert_nil($1)
end
# This assertion is for porting x2() tests in testpy.py of Onigmo.
def assert_match_at(re, str, positions, msg = nil)
re = Regexp.new(re) unless re.is_a?(Regexp)
match = re.match(str)
assert_not_nil match, message(msg) {
"Expected #{re.inspect} to match #{str.inspect}"
}
if match
actual_positions = (0...match.size).map { |i|
[match.begin(i), match.end(i)]
}
assert_equal positions, actual_positions, message(msg) {
"Expected #{re.inspect} to match #{str.inspect} at: #{positions.inspect}"
}
end
end
def assert_match_each(re, conds, msg = nil)
errs = conds.select {|str, match| match ^ (re =~ str)}
msg = message(msg) {
"Expected #{re.inspect} to\n" +
errs.map {|str, match| "\t#{'not ' unless match}match #{str.inspect}"}.join(",\n")
}
assert_empty(errs, msg)
end
end
| 35.466305 | 167 | 0.550593 |
ac5a2b7e352d4126258c22b3d3d451ec9fb53ca9 | 498 | # frozen_string_literal: true
require 'cfn-nag/violation'
require_relative 'base'
class S3BucketEncryptionSetRule < BaseRule
def rule_text
'S3 Bucket should have encryption option set'
end
def rule_type
Violation::WARNING
end
def rule_id
'W41'
end
def audit_impl(cfn_model)
violating_buckets = cfn_model.resources_by_type('AWS::S3::Bucket').select do |bucket|
bucket.bucketEncryption.nil?
end
violating_buckets.map(&:logical_resource_id)
end
end
| 18.444444 | 89 | 0.736948 |
1d92ff24c6c7ff4854e6d82d798de3376fb79b46 | 943 | require 'minitest/autorun'
require 'rest_client'
require 'json'
require 'net/http'
class APITestTopicContains < MiniTest::Unit::TestCase
def setup
url = "http://localhost:3000/api/topics?contains=Citizenship"
#jdata = { :api_token => ENV["FB_API_TOKEN"]}.to_json
#puts jdata
#response = RestClient.get url, :data => jdata, :content_type => :json, :accept => :json
#@data = JSON.parse response.body
uri = URI(url)
req = Net::HTTP::Get.new(uri, 'Content-Type' => 'application/json', 'Authorization' => 'Bearer '+ ENV["FB_API_TOKEN"], 'Accept' => 'application/openflashcards.facebook.v1')
#req.body = jdata
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
res = http.request(req)
end
puts res
@data = res.body
end
def test_id_correct
puts @data.to_s
assert_equal 1, 1
#assert_equal 4, @data['id']
end
end | 27.735294 | 177 | 0.620361 |
e8a6f05ff5aa5315d78fab816caba22e83e9e916 | 918 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module SpecApp
class Application < Rails::Application
config.encoding = "utf-8"
config.cache_classes = true
config.whiny_nils = true
config.eager_load = false
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_dispatch.show_exceptions = false
config.action_controller.allow_forgery_protection = false
config.action_mailer.delivery_method = :test
config.active_support.deprecation = :stderr
config.root = File.expand_path('../..', __FILE__)
# railties.plugins << Rails::Plugin.new(File.expand_path('../../../../..', __FILE__))
end
end
| 26.228571 | 89 | 0.717865 |
f8b1838ebe40eab5f74649a69d0ab298b99b8bd4 | 206 | # frozen_string_literal: true
require 'tmpdir'
require 'optparse'
require 'date'
require 'erb'
require 'context'
require 'session'
require 'parser'
require 'finder'
require 'visualizer'
require 'version'
| 14.714286 | 29 | 0.771845 |
ed63d5cc7615911267036eb98223e4e990f16d92 | 8,886 | # frozen_string_literal: true
RSpec.describe Truemail do
let(:email) { random_email }
let(:custom_configuration) { nil }
shared_examples 'configuration error' do
context 'when global configuration not set or custom configuration not passed' do
specify do
expect { subject }.to raise_error(Truemail::ConfigurationError, Truemail::NOT_CONFIGURED)
end
end
end
describe 'defined constants' do
specify { expect(described_class).to be_const_defined(:INCOMPLETE_CONFIG) }
specify { expect(described_class).to be_const_defined(:NOT_CONFIGURED) }
specify { expect(described_class).to be_const_defined(:VERSION) }
specify { expect(described_class).to be_const_defined(:Configuration) }
specify { expect(described_class).to be_const_defined(:Worker) }
specify { expect(described_class).to be_const_defined(:Executor) }
specify { expect(described_class).to be_const_defined(:Wrapper) }
specify { expect(described_class).to be_const_defined(:Auditor) }
specify { expect(described_class).to be_const_defined(:Validator) }
specify { expect(described_class).to be_const_defined(:Logger) }
specify { expect(described_class).to be_const_defined(:ConfigurationError) }
specify { expect(described_class).to be_const_defined(:TypeError) }
specify { expect(described_class).to be_const_defined(:ArgumentError) }
specify { expect(described_class).to be_const_defined(:RegexConstant) }
specify { expect(described_class).to be_const_defined(:Audit) }
specify { expect(described_class).to be_const_defined(:Validate) }
specify { expect(described_class).to be_const_defined(:Log) }
end
describe 'global configuration methods' do
describe '.configure' do
subject(:configure) { described_class.configure(&config_block) }
let(:config_block) { nil }
context 'without block' do
specify { expect(configure).to be_nil }
specify { expect { configure }.not_to change(described_class, :configuration) }
end
context 'with block' do
context 'without required parameter' do
let(:config_block) { configuration_block }
specify do
expect { configure }
.to raise_error(Truemail::ConfigurationError, Truemail::INCOMPLETE_CONFIG)
end
end
context 'with valid required parameter' do
let(:config_block) { configuration_block(verifier_email: email) }
specify do
expect { configure }
.to change(described_class, :configuration)
.from(nil).to(be_instance_of(Truemail::Configuration))
end
it 'sets attributes into configuration instance' do
expect(configure).to be_an_instance_of(Truemail::Configuration)
expect(described_class.configuration.verifier_email).to eq(email)
end
end
end
end
describe '.reset_configuration!' do
before { described_class.configure(&configuration_block(verifier_email: email)) }
specify do
expect { described_class.reset_configuration! }
.to change(described_class, :configuration)
.from(be_instance_of(Truemail::Configuration)).to(nil)
end
end
describe '.configuration' do
subject(:configuration) { described_class.configuration }
before do
described_class.configure(&configuration_block(
verifier_email: email,
verifier_domain: domain
))
end
let(:domain) { random_domain_name }
let(:new_email) { random_email }
let(:new_domain) { random_domain_name }
let(:new_regex_pattern) { /\A+.\z/ }
let(:new_smtp_error_body_pattern) { /\A\d+\z/ }
specify { expect(configuration).to be_instance_of(Truemail::Configuration) }
it 'accepts to rewrite current configuration settings' do
expect do
configuration.tap(&configuration_block(
verifier_email: new_email,
verifier_domain: new_domain,
email_pattern: new_regex_pattern,
smtp_error_body_pattern: new_smtp_error_body_pattern
))
end
.to change(configuration, :verifier_email)
.from(email).to(new_email)
.and change(configuration, :verifier_domain)
.from(domain).to(new_domain)
.and change(configuration, :email_pattern)
.from(Truemail::RegexConstant::REGEX_EMAIL_PATTERN).to(new_regex_pattern)
.and change(configuration, :smtp_error_body_pattern)
.from(Truemail::RegexConstant::REGEX_SMTP_ERROR_BODY_PATTERN).to(new_smtp_error_body_pattern)
end
end
end
shared_context 'when passed email is not a String' do
context 'when passed email is not a String' do
let(:email) { nil }
specify do
expect { subject }.to raise_error(Truemail::TypeError, Truemail::INVALID_TYPE) # rubocop:disable RSpec/NamedSubject
end
end
end
describe '.validate' do
subject(:validate) { described_class.validate(email, custom_configuration: custom_configuration) }
shared_examples 'returns validator instance' do
specify do
allow(Truemail::Validate::Smtp).to receive(:check).and_return(true)
expect(validate).to be_an_instance_of(Truemail::Validator)
end
end
include_examples 'configuration error'
context 'when passed email is a String' do
context 'when global configuration successfully set' do
before { described_class.configure { |config| config.verifier_email = random_email } }
include_examples 'returns validator instance'
describe 'integration tests' do
let(:target_email) { random_email }
let(:dns_mock_records) { dns_mock_records_by_email(target_email, dimension: 2) }
before do
dns_mock_server.assign_mocks(dns_mock_records)
smtp_mock_server(**smtp_mock_server_options)
described_class.configuration.tap do |config|
config.dns = dns_mock_gateway
config.smtp_port = smtp_mock_server.port
end
end
context 'when checks real email' do
let(:smtp_mock_server_options) { {} }
specify do
expect(described_class.validate(target_email).result).to be_valid
end
end
context 'when checks fake email' do
let(:smtp_mock_server_options) { { not_registered_emails: [target_email] } }
specify do
expect(described_class.validate(target_email).result).not_to be_valid
end
end
end
end
context 'when custom configuration passed' do
let(:custom_configuration) { create_configuration }
include_examples 'returns validator instance'
end
end
include_context 'when passed email is not a String'
end
describe '.valid?' do
subject(:valid_helper) { described_class.valid?(email, custom_configuration: custom_configuration) }
shared_examples 'returns boolean' do
it 'returns boolean from validator result instance' do
allow(Truemail::Validate::Smtp).to receive(:check).and_return(true)
allow_any_instance_of(Truemail::Validator::Result).to receive(:valid?).and_return(true)
expect(valid_helper).to be(true)
end
end
include_examples 'configuration error'
context 'when passed email is a String' do
context 'when global configuration successfully set' do
before { described_class.configure { |config| config.verifier_email = email } }
include_examples 'returns boolean'
end
context 'when custom configuration passed' do
let(:custom_configuration) { create_configuration }
include_examples 'returns boolean'
end
end
include_context 'when passed email is not a String'
end
describe '.host_audit' do
subject(:host_audit) { described_class.host_audit(custom_configuration: custom_configuration) }
shared_examples 'returns auditor instance' do
it 'returns auditor instance' do
expect(Truemail::Auditor).to receive(:new).and_call_original
expect_any_instance_of(Truemail::Auditor).to receive(:run).and_call_original
expect(Truemail::Audit::Ip).to receive(:check).and_return(true)
expect(host_audit).to be_an_instance_of(Truemail::Auditor)
end
end
include_examples 'configuration error'
context 'when global configuration successfully set' do
before { described_class.configure { |config| config.verifier_email = email } }
include_examples 'returns auditor instance'
end
context 'when custom configuration passed' do
let(:custom_configuration) { create_configuration }
include_examples 'returns auditor instance'
end
end
end
| 35.686747 | 123 | 0.684447 |
4a4a480f66c7d6490d4309741ba8de8e5286eaf7 | 1,305 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'uninterruptible/version'
Gem::Specification.new do |spec|
spec.name = "uninterruptible"
spec.version = Uninterruptible::VERSION
spec.authors = ["Dan Wentworth", "Charlie Smurthwaite"]
spec.email = ["[email protected]"]
spec.summary = "Zero-downtime restarts for your trivial socket servers"
spec.description = "Uninterruptible gives your socket server magic restarting powers. Send your running "\
"Uninterruptible server USR1 and it will start a brand new copy of itself which will immediately start handling "\
"new requests while the old server stays alive until all of it's active connections are complete."
spec.homepage = "https://github.com/darkphnx/uninterruptible"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.11"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
end
| 46.607143 | 119 | 0.68659 |
f738fa35353c6ede8dec021dfde86246e9810b22 | 6,202 | #
# Author:: Doug MacEachern (<[email protected]>)
# Copyright:: Copyright 2010-2016, VMware, Inc.
# License:: Apache License, Version 2.0
#
# 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"
class Chef
class Util
class Windows
class NetUser
end
end
end
end
describe Chef::Provider::User::Windows do
before(:each) do
@node = Chef::Node.new
@new_resource = Chef::Resource::User::WindowsUser.new("monkey")
@events = Chef::EventDispatch::Dispatcher.new
@run_context = Chef::RunContext.new(@node, {}, @events)
@current_resource = Chef::Resource::User::WindowsUser.new("monkey")
@net_user = double("Chef::Util::Windows::NetUser")
allow(Chef::Util::Windows::NetUser).to receive(:new).and_return(@net_user)
@provider = Chef::Provider::User::Windows.new(@new_resource, @run_context)
@provider.current_resource = @current_resource
end
it "creates a net_user object with the provided username" do
@new_resource.username "not-monkey"
expect(Chef::Util::Windows::NetUser).to receive(:new).with("not-monkey")
@provider = Chef::Provider::User::Windows.new(@new_resource, @run_context)
end
describe "when comparing the user's current attributes to the desired attributes" do
before do
@new_resource.comment "Adam Jacob"
@new_resource.uid 1000
@new_resource.gid 1000
@new_resource.home "/home/adam"
@new_resource.shell "/usr/bin/zsh"
@new_resource.password "abracadabra"
@provider.current_resource = @new_resource.clone
end
describe "and the attributes match" do
it "doesn't set the comment field to be updated" do
expect(@provider.set_options).not_to have_key(:full_name)
end
it "doesn't set the home directory to be updated" do
expect(@provider.set_options).not_to have_key(:home_dir)
end
it "doesn't set the group id to be updated" do
expect(@provider.set_options).not_to have_key(:primary_group_id)
end
it "doesn't set the user id to be updated" do
expect(@provider.set_options).not_to have_key(:user_id)
end
it "doesn't set the shell to be updated" do
expect(@provider.set_options).not_to have_key(:script_path)
end
it "doesn't set the password to be updated" do
expect(@provider.set_options).not_to have_key(:password)
end
end
describe "and the attributes do not match" do
before do
@current_resource = Chef::Resource::User::WindowsUser.new("adam")
@current_resource.comment "Adam Jacob-foo"
@current_resource.uid 1111
@current_resource.gid 1111
@current_resource.home "/home/adam-foo"
@current_resource.shell "/usr/bin/tcsh"
@current_resource.password "foobarbaz"
@provider.current_resource = @current_resource
end
it "marks the full_name field to be updated" do
expect(@provider.set_options[:full_name]).to eq("Adam Jacob")
end
it "marks the home_dir attribute to be updated" do
expect(@provider.set_options[:home_dir]).to eq("/home/adam")
end
it "ignores the primary_group_id attribute" do
expect(@provider.set_options[:primary_group_id]).to eq(nil)
end
it "marks the user_id attribute to be updated" do
expect(@provider.set_options[:user_id]).to eq(1000)
end
it "marks the script_path attribute to be updated" do
expect(@provider.set_options[:script_path]).to eq("/usr/bin/zsh")
end
it "marks the password attribute to be updated" do
expect(@provider.set_options[:password]).to eq("abracadabra")
end
end
end
describe "when creating the user" do
it "should call @net_user.add with the return of set_options" do
allow(@provider).to receive(:set_options).and_return(:name => "monkey")
expect(@net_user).to receive(:add).with(:name => "monkey")
@provider.create_user
end
end
describe "manage_user" do
before(:each) do
allow(@provider).to receive(:set_options).and_return(:name => "monkey")
end
it "should call @net_user.update with the return of set_options" do
expect(@net_user).to receive(:update).with(:name => "monkey")
@provider.manage_user
end
end
describe "when removing the user" do
it "should call @net_user.delete" do
expect(@net_user).to receive(:delete)
@provider.remove_user
end
end
describe "when checking if the user is locked" do
before(:each) do
@current_resource.password "abracadabra"
end
it "should return true if user is locked" do
allow(@net_user).to receive(:check_enabled).and_return(true)
expect(@provider.check_lock).to eql(true)
end
it "should return false if user is not locked" do
allow(@net_user).to receive(:check_enabled).and_return(false)
expect(@provider.check_lock).to eql(false)
end
end
describe "locking the user" do
it "should call @net_user.disable_account" do
allow(@net_user).to receive(:check_enabled).and_return(true)
expect(@net_user).to receive(:disable_account)
@provider.lock_user
end
end
describe "unlocking the user" do
it "should call @net_user.enable_account" do
allow(@net_user).to receive(:check_enabled).and_return(false)
expect(@net_user).to receive(:enable_account)
@provider.unlock_user
end
end
end
| 33.344086 | 87 | 0.658981 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.