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
1d47020598f7bf5d6470393f22c98625a4745629
812
def read_file(file_name) file = File.open(file_name, "r") data = file.read file.close return data end file_name = "input.txt" arr = read_file(file_name).split("\n") res = [] total = 0 arr.each do |line| points = line.split(" -> ") p1 = points[0].split(",").map(&:to_i) p2 = points[1].split(",").map(&:to_i) if p1[0] == p2[0] x = p1[1] < p2[1] ? p1[1] : p2[1] y = p1[1] < p2[1] ? p2[1] : p1[1] for i in x..y res[p1[0]] ||= {} res[p1[0]][i] ||= 0 total += 1 if res[p1[0]][i] == 1 res[p1[0]][i] += 1 end elsif p1[1] == p2[1] x = p1[0] < p2[0] ? p1[0] : p2[0] y = p1[0] < p2[0] ? p2[0] : p1[0] for i in x..y res[i ] ||= {} res[i][p1[1]] ||= 0 total += 1 if res[i][p1[1]] == 1 res[i][p1[1]] += 1 end end end p total
21.945946
39
0.466749
bf7c52640bb6685e80b4a928dcf16288446900be
1,514
# # Be sure to run `pod lib lint YMSymbolFont.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # Any lines starting with a # are optional, but encouraged # # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = "YMSymbolFont" s.version = "0.25.0" s.summary = "A short description of YMSymbolFont." s.description = <<-DESC An optional longer description of YMSymbolFont * Markdown format. * Don't worry about the indent, we strip it! DESC s.homepage = "https://github.com/hayashi311/YMSymbolFont" # s.screenshots = "www.example.com/screenshots_1", "www.example.com/screenshots_2" s.license = 'MIT' s.author = { "ryota hayashi" => "[email protected]" } s.source = { :git => "https://github.com/hayashi311/YMSymbolFont.git", :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.platform = :ios, '7.0' s.requires_arc = true s.resources = ['Pod/Assets/*.ttf'] s.subspec 'Core' do |cs| cs.source_files = 'Pod/Classes/Core' end s.subspec 'UI' do |us| us.source_files = 'Pod/Classes/UI' end s.default_subspec = 'Core' # s.public_header_files = 'Pod/Classes/**/*.h' s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' end
33.644444
107
0.607001
398b63a39dd19b0c59f86c94d10c2825d71a5e71
1,914
require 'nats/client' require_relative '../spec_helper' module NATSHelper def nats_stub ::NATS.stub(:start) do |_, &blk| return if blk.nil? blk.call end ::NATS.stub(:stop) ::NATS.stub(:request).with('vcap.component.discover') do |_, &blk| return if blk.nil? blk.call(nats_cloud_controller.to_json) blk.call(nats_dea.to_json) blk.call(nats_health_manager.to_json) blk.call(nats_provisioner.to_json) blk.call(nats_router.to_json) end end def nats_cloud_controller { 'credentials' => %w(cc_user cc_password), 'host' => 'CloudControllerHost', 'index' => 0, 'type' => 'CloudController' } end def nats_dea { 'credentials' => %w(dea_user dea_password), 'host' => 'DEAHost', 'index' => 0, 'type' => 'DEA' } end def nats_health_manager { 'credentials' => %w(hm_user hm_password), 'host' => 'HealthManagerHost', 'index' => 0, 'type' => 'HealthManager' } end def nats_provisioner { 'credentials' => %w(provisioner_user provisioner_password), 'host' => 'Test-ProvisionerHost', 'index' => 0, 'type' => 'Test-Provisioner' } end def nats_router { 'credentials' => %w(router_user router_password), 'host' => 'RouterHost', 'index' => 0, 'type' => 'Router' } end def nats_cloud_controller_varz "http://#{ nats_cloud_controller['host'] }/varz" end def nats_dea_varz "http://#{ nats_dea['host'] }/varz" end def nats_health_manager_varz "http://#{ nats_health_manager['host'] }/varz" end def nats_provisioner_varz "http://#{ nats_provisioner['host'] }/varz" end def nats_router_varz "http://#{ nats_router['host'] }/varz" end end
21.75
70
0.565831
3839954bf0bb2f694276087219f3b2c5ea99efab
1,054
# frozen_string_literal: true module Epilog module ContextLogger def with_context(context) push_context(context) yield ensure pop_context end def push_context(context) formatter.push_context(context) end def pop_context formatter.pop_context end end module ContextFormatter def context Thread.current[current_context_key] ||= begin result = {} context_stack.each { |frame| result.merge!(frame) } result end.freeze end def push_context(frame) clear_context context_stack.push(frame) end def pop_context clear_context context_stack.pop end private def clear_context Thread.current[current_context_key] = nil end def context_stack Thread.current[stack_key] ||= [] end def stack_key @stack_key ||= "epilog_context_stack:#{object_id}" end def current_context_key @current_context_key ||= "epilog_context_current:#{object_id}" end end end
17.864407
68
0.650854
03939067c5e6e567480ef80642dc2390cf8135bc
268
cask 'invalid-two-version' do version '1.2.3' version '2.0' sha256 '67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94' url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip" homepage 'https://example.com/local-caffeine' app 'Caffeine.app' end
24.363636
75
0.757463
ed30d9e27a4fa637ebc36d8a80f765b991c459ec
1,330
require 'spec_helper' describe 'selinux::port' do let(:title) { 'myapp' } include_context 'RedHat 7' %w(tcp udp tcp6 udp6).each do |protocol| context "valid protocol #{protocol}" do let(:params) do { context: 'http_port_t', port: 8080, protocol: protocol } end it { should contain_exec("add_http_port_t_8080_#{protocol}").with(command: "semanage port -a -t http_port_t -p #{protocol} 8080") } end context "protocol #{protocol} and port as range" do let(:params) do { context: 'http_port_t', port: '8080-8089', protocol: protocol } end it { should contain_exec("add_http_port_t_8080-8089_#{protocol}").with(command: "semanage port -a -t http_port_t -p #{protocol} 8080-8089") } end end context 'invalid protocol' do let(:params) do { context: 'http_port_t', port: 8080, protocol: 'bad' } end it { expect { is_expected.to compile }.to raise_error(%r{error during compilation}) } end context 'no protocol' do let(:params) do { context: 'http_port_t', port: 8080 } end it { should contain_exec('add_http_port_t_8080').with(command: 'semanage port -a -t http_port_t 8080') } end end
26.078431
147
0.592481
e907f456b4b436f15707861a639afbd0ac9c5cf5
103
class Persistence::AverageSnapshotsGeneratorService < Cosmoslike::AverageSnapshotsGeneratorService end
34.333333
98
0.902913
212fb0e62460c5f5a66cf05247762bb28184f714
1,680
# Copyright © 2011-2020 MUSC Foundation for Research Development~ # All rights reserved.~ # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:~ # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.~ # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following~ # disclaimer in the documentation and/or other materials provided with the distribution.~ # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products~ # derived from this software without specific prior written permission.~ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,~ # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT~ # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL~ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS~ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR~ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.~ require "rails_helper" RSpec.describe HumanSubjectsInfo, type: :model do it { is_expected.to belong_to(:protocol) } end
62.222222
146
0.794643
626f1c71e849e595df06697889324521826f8877
3,252
HabitHub::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both thread web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. # config.action_dispatch.rack_cache = true # Disable Rails's static asset server (Apache or nginx will already do this). config.serve_static_assets = false # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Generate digests for assets URLs. config.assets.digest = true # Version of your assets, change this if you want to expire all your assets. config.assets.version = '1.0' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Set to :debug to see everything in the log. config.log_level = :info # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # config.assets.precompile += %w( search.js ) # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Disable automatic flushing of the log to improve performance. # config.autoflush_log = false # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new end
40.148148
104
0.756765
9101e284e8858cea65910dab375b9cbcfda6b9bc
332
cask 'sr' do version '1.0.0' sha256 '0ceb12f56974b916d186ce3c475750b5e0f010f2733dde8d25bfb48f42b0ecce' url "https://github.com/merikan/nativefier-apps/releases/download/sr-v#{version}/sr-v#{version}-darwin-x64.tgz" name 'Massenger' homepage 'https://github.com/merikan/nativefier-apps' app 'sr-darwin-x64/sr.app' end
27.666667
113
0.759036
61300ff5da266dc60680b447f1e86ddb8bf5cd14
28,150
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::ApiManagement::Mgmt::V2017_03_01 # # ApiManagement Client # class ApiIssue include MsRestAzure # # Creates and initializes a new instance of the ApiIssue class. # @param client service class for accessing basic functionality. # def initialize(client) @client = client end # @return [ApiManagementClient] reference to the ApiManagementClient attr_reader :client # # Gets the entity state (Etag) version of the Issue for an API specified by its # identifier. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param api_id [String] API identifier. Must be unique in the current API # Management service instance. # @param issue_id [String] Issue identifier. Must be unique in the current API # Management service instance. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def head(resource_group_name, service_name, api_id, issue_id, custom_headers:nil) response = head_async(resource_group_name, service_name, api_id, issue_id, custom_headers:custom_headers).value! nil end # # Gets the entity state (Etag) version of the Issue for an API specified by its # identifier. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param api_id [String] API identifier. Must be unique in the current API # Management service instance. # @param issue_id [String] Issue identifier. Must be unique in the current API # Management service instance. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def head_with_http_info(resource_group_name, service_name, api_id, issue_id, custom_headers:nil) head_async(resource_group_name, service_name, api_id, issue_id, custom_headers:custom_headers).value! end # # Gets the entity state (Etag) version of the Issue for an API specified by its # identifier. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param api_id [String] API identifier. Must be unique in the current API # Management service instance. # @param issue_id [String] Issue identifier. Must be unique in the current API # Management service instance. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def head_async(resource_group_name, service_name, api_id, issue_id, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'service_name is nil' if service_name.nil? fail ArgumentError, "'service_name' should satisfy the constraint - 'MaxLength': '50'" if !service_name.nil? && service_name.length > 50 fail ArgumentError, "'service_name' should satisfy the constraint - 'MinLength': '1'" if !service_name.nil? && service_name.length < 1 fail ArgumentError, "'service_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'" if !service_name.nil? && service_name.match(Regexp.new('^^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$$')).nil? fail ArgumentError, 'api_id is nil' if api_id.nil? fail ArgumentError, "'api_id' should satisfy the constraint - 'MaxLength': '256'" if !api_id.nil? && api_id.length > 256 fail ArgumentError, "'api_id' should satisfy the constraint - 'MinLength': '1'" if !api_id.nil? && api_id.length < 1 fail ArgumentError, "'api_id' should satisfy the constraint - 'Pattern': '^[^*#&+:<>?]+$'" if !api_id.nil? && api_id.match(Regexp.new('^^[^*#&+:<>?]+$$')).nil? fail ArgumentError, 'issue_id is nil' if issue_id.nil? fail ArgumentError, "'issue_id' should satisfy the constraint - 'MaxLength': '256'" if !issue_id.nil? && issue_id.length > 256 fail ArgumentError, "'issue_id' should satisfy the constraint - 'MinLength': '1'" if !issue_id.nil? && issue_id.length < 1 fail ArgumentError, "'issue_id' should satisfy the constraint - 'Pattern': '^[^*#&+:<>?]+$'" if !issue_id.nil? && issue_id.match(Regexp.new('^^[^*#&+:<>?]+$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/issues/{issueId}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'serviceName' => service_name,'apiId' => api_id,'issueId' => issue_id,'subscriptionId' => @client.subscription_id}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:head, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result end promise.execute end # # Gets the details of the Issue for an API specified by its identifier. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param api_id [String] API identifier. Must be unique in the current API # Management service instance. # @param issue_id [String] Issue identifier. Must be unique in the current API # Management service instance. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [IssueContract] operation results. # def get(resource_group_name, service_name, api_id, issue_id, custom_headers:nil) response = get_async(resource_group_name, service_name, api_id, issue_id, custom_headers:custom_headers).value! response.body unless response.nil? end # # Gets the details of the Issue for an API specified by its identifier. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param api_id [String] API identifier. Must be unique in the current API # Management service instance. # @param issue_id [String] Issue identifier. Must be unique in the current API # Management service instance. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def get_with_http_info(resource_group_name, service_name, api_id, issue_id, custom_headers:nil) get_async(resource_group_name, service_name, api_id, issue_id, custom_headers:custom_headers).value! end # # Gets the details of the Issue for an API specified by its identifier. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param api_id [String] API identifier. Must be unique in the current API # Management service instance. # @param issue_id [String] Issue identifier. Must be unique in the current API # Management service instance. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def get_async(resource_group_name, service_name, api_id, issue_id, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'service_name is nil' if service_name.nil? fail ArgumentError, "'service_name' should satisfy the constraint - 'MaxLength': '50'" if !service_name.nil? && service_name.length > 50 fail ArgumentError, "'service_name' should satisfy the constraint - 'MinLength': '1'" if !service_name.nil? && service_name.length < 1 fail ArgumentError, "'service_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'" if !service_name.nil? && service_name.match(Regexp.new('^^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$$')).nil? fail ArgumentError, 'api_id is nil' if api_id.nil? fail ArgumentError, "'api_id' should satisfy the constraint - 'MaxLength': '256'" if !api_id.nil? && api_id.length > 256 fail ArgumentError, "'api_id' should satisfy the constraint - 'MinLength': '1'" if !api_id.nil? && api_id.length < 1 fail ArgumentError, "'api_id' should satisfy the constraint - 'Pattern': '^[^*#&+:<>?]+$'" if !api_id.nil? && api_id.match(Regexp.new('^^[^*#&+:<>?]+$$')).nil? fail ArgumentError, 'issue_id is nil' if issue_id.nil? fail ArgumentError, "'issue_id' should satisfy the constraint - 'MaxLength': '256'" if !issue_id.nil? && issue_id.length > 256 fail ArgumentError, "'issue_id' should satisfy the constraint - 'MinLength': '1'" if !issue_id.nil? && issue_id.length < 1 fail ArgumentError, "'issue_id' should satisfy the constraint - 'Pattern': '^[^*#&+:<>?]+$'" if !issue_id.nil? && issue_id.match(Regexp.new('^^[^*#&+:<>?]+$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/issues/{issueId}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'serviceName' => service_name,'apiId' => api_id,'issueId' => issue_id,'subscriptionId' => @client.subscription_id}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::ApiManagement::Mgmt::V2017_03_01::Models::IssueContract.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Creates a new Issue for an API or updates an existing one. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param api_id [String] API identifier. Must be unique in the current API # Management service instance. # @param issue_id [String] Issue identifier. Must be unique in the current API # Management service instance. # @param parameters [IssueContract] Create parameters. # @param if_match [String] ETag of the Issue Entity. ETag should match the # current entity state from the header response of the GET request or it should # be * for unconditional update. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [IssueContract] operation results. # def create_or_update(resource_group_name, service_name, api_id, issue_id, parameters, if_match:nil, custom_headers:nil) response = create_or_update_async(resource_group_name, service_name, api_id, issue_id, parameters, if_match:if_match, custom_headers:custom_headers).value! response.body unless response.nil? end # # Creates a new Issue for an API or updates an existing one. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param api_id [String] API identifier. Must be unique in the current API # Management service instance. # @param issue_id [String] Issue identifier. Must be unique in the current API # Management service instance. # @param parameters [IssueContract] Create parameters. # @param if_match [String] ETag of the Issue Entity. ETag should match the # current entity state from the header response of the GET request or it should # be * for unconditional update. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def create_or_update_with_http_info(resource_group_name, service_name, api_id, issue_id, parameters, if_match:nil, custom_headers:nil) create_or_update_async(resource_group_name, service_name, api_id, issue_id, parameters, if_match:if_match, custom_headers:custom_headers).value! end # # Creates a new Issue for an API or updates an existing one. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param api_id [String] API identifier. Must be unique in the current API # Management service instance. # @param issue_id [String] Issue identifier. Must be unique in the current API # Management service instance. # @param parameters [IssueContract] Create parameters. # @param if_match [String] ETag of the Issue Entity. ETag should match the # current entity state from the header response of the GET request or it should # be * for unconditional update. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def create_or_update_async(resource_group_name, service_name, api_id, issue_id, parameters, if_match:nil, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'service_name is nil' if service_name.nil? fail ArgumentError, "'service_name' should satisfy the constraint - 'MaxLength': '50'" if !service_name.nil? && service_name.length > 50 fail ArgumentError, "'service_name' should satisfy the constraint - 'MinLength': '1'" if !service_name.nil? && service_name.length < 1 fail ArgumentError, "'service_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'" if !service_name.nil? && service_name.match(Regexp.new('^^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$$')).nil? fail ArgumentError, 'api_id is nil' if api_id.nil? fail ArgumentError, "'api_id' should satisfy the constraint - 'MaxLength': '256'" if !api_id.nil? && api_id.length > 256 fail ArgumentError, "'api_id' should satisfy the constraint - 'MinLength': '1'" if !api_id.nil? && api_id.length < 1 fail ArgumentError, "'api_id' should satisfy the constraint - 'Pattern': '^[^*#&+:<>?]+$'" if !api_id.nil? && api_id.match(Regexp.new('^^[^*#&+:<>?]+$$')).nil? fail ArgumentError, 'issue_id is nil' if issue_id.nil? fail ArgumentError, "'issue_id' should satisfy the constraint - 'MaxLength': '256'" if !issue_id.nil? && issue_id.length > 256 fail ArgumentError, "'issue_id' should satisfy the constraint - 'MinLength': '1'" if !issue_id.nil? && issue_id.length < 1 fail ArgumentError, "'issue_id' should satisfy the constraint - 'Pattern': '^[^*#&+:<>?]+$'" if !issue_id.nil? && issue_id.match(Regexp.new('^^[^*#&+:<>?]+$$')).nil? fail ArgumentError, 'parameters is nil' if parameters.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['If-Match'] = if_match unless if_match.nil? request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::ApiManagement::Mgmt::V2017_03_01::Models::IssueContract.mapper() request_content = @client.serialize(request_mapper, parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/issues/{issueId}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'serviceName' => service_name,'apiId' => api_id,'issueId' => issue_id,'subscriptionId' => @client.subscription_id}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:put, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 201 || status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? # Deserialize Response if status_code == 201 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::ApiManagement::Mgmt::V2017_03_01::Models::IssueContract.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::ApiManagement::Mgmt::V2017_03_01::Models::IssueContract.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Deletes the specified Issue from an API. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param api_id [String] API identifier. Must be unique in the current API # Management service instance. # @param issue_id [String] Issue identifier. Must be unique in the current API # Management service instance. # @param if_match [String] ETag of the Issue Entity. ETag should match the # current entity state from the header response of the GET request or it should # be * for unconditional update. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def delete(resource_group_name, service_name, api_id, issue_id, if_match, custom_headers:nil) response = delete_async(resource_group_name, service_name, api_id, issue_id, if_match, custom_headers:custom_headers).value! nil end # # Deletes the specified Issue from an API. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param api_id [String] API identifier. Must be unique in the current API # Management service instance. # @param issue_id [String] Issue identifier. Must be unique in the current API # Management service instance. # @param if_match [String] ETag of the Issue Entity. ETag should match the # current entity state from the header response of the GET request or it should # be * for unconditional update. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def delete_with_http_info(resource_group_name, service_name, api_id, issue_id, if_match, custom_headers:nil) delete_async(resource_group_name, service_name, api_id, issue_id, if_match, custom_headers:custom_headers).value! end # # Deletes the specified Issue from an API. # # @param resource_group_name [String] The name of the resource group. # @param service_name [String] The name of the API Management service. # @param api_id [String] API identifier. Must be unique in the current API # Management service instance. # @param issue_id [String] Issue identifier. Must be unique in the current API # Management service instance. # @param if_match [String] ETag of the Issue Entity. ETag should match the # current entity state from the header response of the GET request or it should # be * for unconditional update. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def delete_async(resource_group_name, service_name, api_id, issue_id, if_match, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'service_name is nil' if service_name.nil? fail ArgumentError, "'service_name' should satisfy the constraint - 'MaxLength': '50'" if !service_name.nil? && service_name.length > 50 fail ArgumentError, "'service_name' should satisfy the constraint - 'MinLength': '1'" if !service_name.nil? && service_name.length < 1 fail ArgumentError, "'service_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'" if !service_name.nil? && service_name.match(Regexp.new('^^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$$')).nil? fail ArgumentError, 'api_id is nil' if api_id.nil? fail ArgumentError, "'api_id' should satisfy the constraint - 'MaxLength': '256'" if !api_id.nil? && api_id.length > 256 fail ArgumentError, "'api_id' should satisfy the constraint - 'MinLength': '1'" if !api_id.nil? && api_id.length < 1 fail ArgumentError, "'api_id' should satisfy the constraint - 'Pattern': '^[^*#&+:<>?]+$'" if !api_id.nil? && api_id.match(Regexp.new('^^[^*#&+:<>?]+$$')).nil? fail ArgumentError, 'issue_id is nil' if issue_id.nil? fail ArgumentError, "'issue_id' should satisfy the constraint - 'MaxLength': '256'" if !issue_id.nil? && issue_id.length > 256 fail ArgumentError, "'issue_id' should satisfy the constraint - 'MinLength': '1'" if !issue_id.nil? && issue_id.length < 1 fail ArgumentError, "'issue_id' should satisfy the constraint - 'Pattern': '^[^*#&+:<>?]+$'" if !issue_id.nil? && issue_id.match(Regexp.new('^^[^*#&+:<>?]+$$')).nil? fail ArgumentError, 'if_match is nil' if if_match.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['If-Match'] = if_match unless if_match.nil? request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/issues/{issueId}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'serviceName' => service_name,'apiId' => api_id,'issueId' => issue_id,'subscriptionId' => @client.subscription_id}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:delete, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 204 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result end promise.execute end end end
55.304519
233
0.693606
1d4264c98aa7189fa59767f3ea15a25c464fef41
1,763
require "webrat/integrations/rails" require "action_controller/record_identifier" module Webrat class RailsAdapter #:nodoc: include ActionController::RecordIdentifier attr_reader :integration_session def initialize(session) @integration_session = session end def get(url, data, headers = nil) do_request(:get, url, data, headers) end def post(url, data, headers = nil) do_request(:post, url, data, headers) end def put(url, data, headers = nil) do_request(:put, url, data, headers) end def delete(url, data, headers = nil) do_request(:delete, url, data, headers) end def response_body response.body end def response_code response.code.to_i end def xml_content_type? response.headers["Content-Type"].to_s =~ /xml/ end protected def do_request(http_method, url, data, headers) #:nodoc: update_protocol(url) integration_session.send(http_method, normalize_url(url), data, headers) end # remove protocol, host and anchor def normalize_url(href) #:nodoc: uri = URI.parse(href) normalized_url = [] normalized_url << "#{uri.scheme}://" if uri.scheme normalized_url << uri.host if uri.host normalized_url << ":#{uri.port}" if uri.port && ![80,443].include?(uri.port) normalized_url << uri.path if uri.path normalized_url << "?#{uri.query}" if uri.query normalized_url.join end def update_protocol(href) #:nodoc: if href =~ /^https:/ integration_session.https!(true) elsif href =~ /^http:/ integration_session.https!(false) end end def response #:nodoc: integration_session.response end end end
23.824324
82
0.647192
39cca27ad2199cc7f339ee88ade9bbb3333c7eb8
386
class AuthorSessionsController < ApplicationController def new; end def create if login(params[:email], params[:password]) flash.notice = 'Successfully Logged in.' redirect_to(articles_path) else flash.now.alert = 'Login failed.' render action: :new end end def destroy logout redirect_to(:authors, notice: 'Logged out!') end end
20.315789
54
0.670984
4a7cf91926dcc8a78ff54faca847d407578c1132
5,682
require "test_helper" require "remotable" require "support/bespoke" require "rr" class BespokeTest < ActiveSupport::TestCase include RR::Adapters::TestUnit teardown do def model.new_resource BespokeResource.new end def model.find_by(remote_attr, value) nil end end # ========================================================================= # # Finding # # ========================================================================= # test "should be able to find resources by different attributes" do new_tenant_slug = "not_found" assert_equal 0, BespokeTenant.where(:slug => new_tenant_slug).count, "There's not supposed to be a BespokeTenant with the slug #{new_tenant_slug}." def model.find_by(attribute, value) BespokeResource.new(:slug => value) end new_tenant = BespokeTenant.find_by_slug(new_tenant_slug) assert_not_nil new_tenant, "A remote @tenant was not found with the slug #{new_tenant_slug.inspect}" end test "should create a record locally when fetching a new remote resource" do new_tenant_slug = "17" assert_equal 0, BespokeTenant.where(:slug => new_tenant_slug).count, "There's not supposed to be a BespokeTenant with the slug #{new_tenant_slug}." def model.find_by(attribute, value) BespokeResource.new(:slug => value) end assert_difference "BespokeTenant.count", +1 do new_tenant = BespokeTenant.find_by_slug(new_tenant_slug) assert_not_nil new_tenant, "A remote tenant was not found with the id #{new_tenant_slug.inspect}" end end test "if a resource is neither local nor remote, raise an exception with the bang method" do new_tenant_slug = "not_found3" assert_equal 0, BespokeTenant.where(:slug => new_tenant_slug).count, "There's not supposed to be a BespokeTenant with the slug #{new_tenant_slug}." assert_raises ActiveRecord::RecordNotFound do BespokeTenant.find_by_slug!(new_tenant_slug) end end # ========================================================================= # # Updating # # ========================================================================= # test "should update a record remotely when updating one locally" do @tenant = Factory(:bespoke_tenant) new_name = "Totally Wonky" # RemoteTenant.run_simulation do |s| # s.show(@tenant.remote_id, { # :id => @tenant.remote_id, # :slug => @tenant.slug, # :church_name => @tenant.name # }) # s.update(@tenant.remote_id) # # @tenant.nosync = false # @tenant.name = "Totally Wonky" # assert_equal true, @tenant.any_remote_changes? # # @tenant.save! # # pending "Not sure how to test that an update happened" # end end test "should fail to update a record locally when failing to update one remotely" do @tenant = Factory(:bespoke_tenant, :nosync => false) def model.find_by(attribute, value) BespokeResource.new(attribute => value) end def resource.save false end def resource.errors {:name => ["is already taken"]} end @tenant.name = "Totally Wonky" assert_raises(ActiveRecord::RecordInvalid) do @tenant.save! end assert_equal ["is already taken"], @tenant.errors[:name] end # ========================================================================= # # Creating # # ========================================================================= # test "should create a record remotely when creating one locally" do @tenant = BespokeTenant.new({ :slug => "brand_new", :name => "Brand New" }) assert_nil @tenant.remote_resource @tenant.save! assert_not_nil @tenant.remote_resource end test "should fail to create a record locally when failing to create one remotely" do @tenant = BespokeTenant.new({ :slug => "brand_new", :name => "Brand New" }) def model.new_resource resource = BespokeResource.new def resource.save; false; end def resource.errors; {:name => ["is already taken"]}; end resource end assert_raises(ActiveRecord::RecordInvalid) do @tenant.save! end assert_equal ["is already taken"], @tenant.errors[:name] end # ========================================================================= # # Destroying # # ========================================================================= # test "should destroy a record remotely when destroying one locally" do @tenant = Factory(:bespoke_tenant, :nosync => false) mock(resource).destroy { true } @tenant.destroy end test "should fail to destroy a record locally when failing to destroy one remotely" do @tenant = Factory(:bespoke_tenant, :nosync => false) mock(resource).destroy { raise StandardError } assert_raises(StandardError) do @tenant.destroy end end test "should delete a local record when a remote record has been deleted" do @tenant = Factory(:bespoke_tenant, :expires_at => 1.year.ago) def model.find_by(remote_attr, value) nil end assert_difference "BespokeTenant.count", -1 do @tenant = BespokeTenant.find_by_slug(@tenant.slug) assert_equal nil, @tenant end end private def model BespokeTenant.remote_model end def resource @tenant.remote_resource end end
28.69697
104
0.57163
6214cfba71349b40070cd6909243a4b405b842a0
14,564
=begin #UltraCart Rest API V2 #UltraCart REST API Version 2 OpenAPI spec version: 2.0.0 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.15-SNAPSHOT =end require 'date' module UltracartClient class Cart attr_accessor :affiliate # The ISO-4217 three letter base currency code of the account attr_accessor :base_currency_code attr_accessor :billing attr_accessor :buysafe # Unique identifier for this cart attr_accessor :cart_id attr_accessor :checkout # Coupons attr_accessor :coupons # The ISO-4217 three letter currency code the customer is viewing prices in attr_accessor :currency_code attr_accessor :currency_conversion attr_accessor :customer_profile # The exchange rate if the customer is viewing a different currency than the base attr_accessor :exchange_rate attr_accessor :gift attr_accessor :gift_certificate # Items attr_accessor :items # The ISO-631 three letter code the customer would like to checkout with attr_accessor :language_iso_code # True if the customer is logged into their profile attr_accessor :logged_in attr_accessor :marketing # Merchant ID this cart is associated with attr_accessor :merchant_id attr_accessor :payment # Properties associated with the cart attr_accessor :properties attr_accessor :settings attr_accessor :shipping attr_accessor :summary attr_accessor :taxes attr_accessor :upsell_after # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'affiliate' => :'affiliate', :'base_currency_code' => :'base_currency_code', :'billing' => :'billing', :'buysafe' => :'buysafe', :'cart_id' => :'cart_id', :'checkout' => :'checkout', :'coupons' => :'coupons', :'currency_code' => :'currency_code', :'currency_conversion' => :'currency_conversion', :'customer_profile' => :'customer_profile', :'exchange_rate' => :'exchange_rate', :'gift' => :'gift', :'gift_certificate' => :'gift_certificate', :'items' => :'items', :'language_iso_code' => :'language_iso_code', :'logged_in' => :'logged_in', :'marketing' => :'marketing', :'merchant_id' => :'merchant_id', :'payment' => :'payment', :'properties' => :'properties', :'settings' => :'settings', :'shipping' => :'shipping', :'summary' => :'summary', :'taxes' => :'taxes', :'upsell_after' => :'upsell_after' } end # Attribute type mapping. def self.swagger_types { :'affiliate' => :'CartAffiliate', :'base_currency_code' => :'String', :'billing' => :'CartBilling', :'buysafe' => :'CartBuysafe', :'cart_id' => :'String', :'checkout' => :'CartCheckout', :'coupons' => :'Array<CartCoupon>', :'currency_code' => :'String', :'currency_conversion' => :'CartCurrencyConversion', :'customer_profile' => :'CartCustomerProfile', :'exchange_rate' => :'Float', :'gift' => :'CartGift', :'gift_certificate' => :'CartGiftCertificate', :'items' => :'Array<CartItem>', :'language_iso_code' => :'String', :'logged_in' => :'BOOLEAN', :'marketing' => :'CartMarketing', :'merchant_id' => :'String', :'payment' => :'CartPayment', :'properties' => :'Array<CartProperty>', :'settings' => :'CartSettings', :'shipping' => :'CartShipping', :'summary' => :'CartSummary', :'taxes' => :'CartTaxes', :'upsell_after' => :'CartUpsellAfter' } 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?(:'affiliate') self.affiliate = attributes[:'affiliate'] end if attributes.has_key?(:'base_currency_code') self.base_currency_code = attributes[:'base_currency_code'] end if attributes.has_key?(:'billing') self.billing = attributes[:'billing'] end if attributes.has_key?(:'buysafe') self.buysafe = attributes[:'buysafe'] end if attributes.has_key?(:'cart_id') self.cart_id = attributes[:'cart_id'] end if attributes.has_key?(:'checkout') self.checkout = attributes[:'checkout'] end if attributes.has_key?(:'coupons') if (value = attributes[:'coupons']).is_a?(Array) self.coupons = value end end if attributes.has_key?(:'currency_code') self.currency_code = attributes[:'currency_code'] end if attributes.has_key?(:'currency_conversion') self.currency_conversion = attributes[:'currency_conversion'] end if attributes.has_key?(:'customer_profile') self.customer_profile = attributes[:'customer_profile'] end if attributes.has_key?(:'exchange_rate') self.exchange_rate = attributes[:'exchange_rate'] end if attributes.has_key?(:'gift') self.gift = attributes[:'gift'] end if attributes.has_key?(:'gift_certificate') self.gift_certificate = attributes[:'gift_certificate'] end if attributes.has_key?(:'items') if (value = attributes[:'items']).is_a?(Array) self.items = value end end if attributes.has_key?(:'language_iso_code') self.language_iso_code = attributes[:'language_iso_code'] end if attributes.has_key?(:'logged_in') self.logged_in = attributes[:'logged_in'] end if attributes.has_key?(:'marketing') self.marketing = attributes[:'marketing'] end if attributes.has_key?(:'merchant_id') self.merchant_id = attributes[:'merchant_id'] end if attributes.has_key?(:'payment') self.payment = attributes[:'payment'] end if attributes.has_key?(:'properties') if (value = attributes[:'properties']).is_a?(Array) self.properties = value end end if attributes.has_key?(:'settings') self.settings = attributes[:'settings'] end if attributes.has_key?(:'shipping') self.shipping = attributes[:'shipping'] end if attributes.has_key?(:'summary') self.summary = attributes[:'summary'] end if attributes.has_key?(:'taxes') self.taxes = attributes[:'taxes'] end if attributes.has_key?(:'upsell_after') self.upsell_after = attributes[:'upsell_after'] 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 !@base_currency_code.nil? && @base_currency_code.to_s.length > 3 invalid_properties.push('invalid value for "base_currency_code", the character length must be smaller than or equal to 3.') end if !@currency_code.nil? && @currency_code.to_s.length > 3 invalid_properties.push('invalid value for "currency_code", the character length must be smaller than or equal to 3.') end if !@language_iso_code.nil? && @language_iso_code.to_s.length > 3 invalid_properties.push('invalid value for "language_iso_code", the character length must be smaller than or equal to 3.') 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 !@base_currency_code.nil? && @base_currency_code.to_s.length > 3 return false if !@currency_code.nil? && @currency_code.to_s.length > 3 return false if !@language_iso_code.nil? && @language_iso_code.to_s.length > 3 true end # Custom attribute writer method with validation # @param [Object] base_currency_code Value to be assigned def base_currency_code=(base_currency_code) if !base_currency_code.nil? && base_currency_code.to_s.length > 3 fail ArgumentError, 'invalid value for "base_currency_code", the character length must be smaller than or equal to 3.' end @base_currency_code = base_currency_code end # Custom attribute writer method with validation # @param [Object] currency_code Value to be assigned def currency_code=(currency_code) if !currency_code.nil? && currency_code.to_s.length > 3 fail ArgumentError, 'invalid value for "currency_code", the character length must be smaller than or equal to 3.' end @currency_code = currency_code end # Custom attribute writer method with validation # @param [Object] language_iso_code Value to be assigned def language_iso_code=(language_iso_code) if !language_iso_code.nil? && language_iso_code.to_s.length > 3 fail ArgumentError, 'invalid value for "language_iso_code", the character length must be smaller than or equal to 3.' end @language_iso_code = language_iso_code 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 && affiliate == o.affiliate && base_currency_code == o.base_currency_code && billing == o.billing && buysafe == o.buysafe && cart_id == o.cart_id && checkout == o.checkout && coupons == o.coupons && currency_code == o.currency_code && currency_conversion == o.currency_conversion && customer_profile == o.customer_profile && exchange_rate == o.exchange_rate && gift == o.gift && gift_certificate == o.gift_certificate && items == o.items && language_iso_code == o.language_iso_code && logged_in == o.logged_in && marketing == o.marketing && merchant_id == o.merchant_id && payment == o.payment && properties == o.properties && settings == o.settings && shipping == o.shipping && summary == o.summary && taxes == o.taxes && upsell_after == o.upsell_after 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 [affiliate, base_currency_code, billing, buysafe, cart_id, checkout, coupons, currency_code, currency_conversion, customer_profile, exchange_rate, gift, gift_certificate, items, language_iso_code, logged_in, marketing, merchant_id, payment, properties, settings, shipping, summary, taxes, upsell_after].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 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 = UltracartClient.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
31.52381
313
0.625034
62dff1a79bf593913007189d1d0f9742a9eadbd5
3,143
# frozen_string_literal: true require "octicons" module Primer # `Octicon` renders an <%= link_to_octicons %> with <%= link_to_system_arguments_docs %>. # `Octicon` can also be rendered with the `primer_octicon` helper, which accepts the same arguments. class OcticonComponent < Primer::Component status :beta SIZE_DEFAULT = :small SIZE_MEDIUM = :medium SIZE_MAPPINGS = { SIZE_DEFAULT => 16, SIZE_MEDIUM => 24 }.freeze SIZE_OPTIONS = SIZE_MAPPINGS.keys # @example Default # <%= render(Primer::OcticonComponent.new(:check)) %> # <%= render(Primer::OcticonComponent.new(icon: :check)) %> # # @example Medium # <%= render(Primer::OcticonComponent.new(:people, size: :medium)) %> # # @example Helper # <%= primer_octicon(:check) %> # # @param icon_name [Symbol, String] Name of <%= link_to_octicons %> to use. # @param icon [Symbol, String] Name of <%= link_to_octicons %> to use. # @param size [Symbol] <%= one_of(Primer::OcticonComponent::SIZE_MAPPINGS, sort: false) %> # @param use_symbol [Boolean] EXPERIMENTAL (May change or be removed) - Set to true when using with <%= link_to_component(Primer::OcticonSymbolsComponent) %>. # @param system_arguments [Hash] <%= link_to_system_arguments_docs %> def initialize(icon_name = nil, icon: nil, size: SIZE_DEFAULT, use_symbol: false, **system_arguments) icon_key = icon_name || icon # Don't allow sizes under 16px if system_arguments[:height].present? && system_arguments[:height].to_i < 16 || system_arguments[:width].present? && system_arguments[:width].to_i < 16 system_arguments.delete(:height) system_arguments.delete(:width) end cache_key = Primer::Octicon::Cache.get_key( symbol: icon_key, size: size, height: system_arguments[:height], width: system_arguments[:width] ) @system_arguments = system_arguments @system_arguments[:tag] = :svg @system_arguments[:aria] ||= {} @use_symbol = use_symbol if @system_arguments[:aria][:label] || @system_arguments[:"aria-label"] @system_arguments[:role] = "img" else @system_arguments[:aria][:hidden] = true end if (cache_icon = Primer::Octicon::Cache.read(cache_key)) @icon = cache_icon else # Filter out classify options to prevent them from becoming invalid html attributes. # Note height and width are both classify options and valid html attributes. octicon_options = { height: SIZE_MAPPINGS[fetch_or_fallback(SIZE_OPTIONS, size, SIZE_DEFAULT)] }.merge(@system_arguments.slice(:height, :width)) @icon = Octicons::Octicon.new(icon_key, octicon_options) Primer::Octicon::Cache.set(cache_key, @icon) end @system_arguments[:classes] = class_names( @icon.options[:class], @system_arguments[:classes] ) @system_arguments.merge!(@icon.options.except(:class, :'aria-hidden')) end def self._after_compile Primer::Octicon::Cache.preload! end end end
36.126437
162
0.655743
1de92f56b3333ff08916837c9df89ecb3150ddea
277
# frozen_string_literal: true FactoryBot.define do factory :x509_commit_signature, class: 'CommitSignatures::X509CommitSignature' do commit_sha { Digest::SHA1.hexdigest(SecureRandom.hex) } project x509_certificate verification_status { :verified } end end
25.181818
83
0.768953
bf18332a8eb0c0f3f621ad08238106b4e89e7c40
994
# frozen_string_literal: true return if Rails.env.production? namespace :spec do desc 'GitLab | RSpec | Run unit tests' RSpec::Core::RakeTask.new(:unit, :rspec_opts) do |t, args| require_dependency 'quality/test_level' t.pattern = Quality::TestLevel.new.pattern(:unit) t.rspec_opts = args[:rspec_opts] end desc 'GitLab | RSpec | Run integration tests' RSpec::Core::RakeTask.new(:integration, :rspec_opts) do |t, args| require_dependency 'quality/test_level' t.pattern = Quality::TestLevel.new.pattern(:integration) t.rspec_opts = args[:rspec_opts] end desc 'GitLab | RSpec | Run system tests' RSpec::Core::RakeTask.new(:system, :rspec_opts) do |t, args| require_dependency 'quality/test_level' t.pattern = Quality::TestLevel.new.pattern(:system) t.rspec_opts = args[:rspec_opts] end desc 'Run the code examples in spec/requests/api' RSpec::Core::RakeTask.new(:api) do |t| t.pattern = 'spec/requests/api/**/*_spec.rb' end end
31.0625
67
0.705231
2108a8677aa5fc1caf27db2d632866e8abe399fb
11,282
require 'base64' require 'ws/dummy_ws' require 'time' module Ldash # The unix timestamp Discord IDs are based on DISCORD_EPOCH = 1_420_070_400_000 # Format time to Discord's format def self.format_time(time) time.iso8601 end # Generic data base class, so I don't have to write the same kind of initializer over and over again class DataObject def self.data_attribute(name, &proc) @data_attributes ||= [] @data_attributes << { name: name, proc: proc } attr_accessor(name) end def initialize(data = {}) @session = $session attrs = self.class.instance_variable_get('@data_attributes') attrs.each do |attr| val = data[attr[:name]] val = attr[:proc].call($session, self) if !val && attr[:proc] instance_variable_set("@#{attr[:name]}", val) end end end # Discord user class User < DataObject data_attribute :username data_attribute :id, &:generate_id data_attribute(:discriminator) { |s| s.generate_discrim(@username) } data_attribute :avatar data_attribute :email data_attribute :password data_attribute :verified data_attribute :bot def id_format { id: @id.to_s } end def compact result = { username: @username.to_s, id: @id.to_s, discriminator: @discriminator.to_s, avatar: @avatar.to_s } # Only add the bot tag if it's actually true result[:bot] = true if @bot result end # The email will only ever be defined on a possible bot user def bot_user? [email protected]? end def bot_user_format compact.merge(verified: @verified, email: @email.to_s) end end # Users on servers class Member < DataObject data_attribute :user data_attribute :server # Server wide voice status data_attribute(:mute) { false } data_attribute(:deaf) { false } data_attribute :voice_channel data_attribute(:joined_at) { Time.now } data_attribute(:roles) { [] } data_attribute(:game) { nil } data_attribute(:status) { 'online' } def in_voice_channel? !@voice_channel.nil? end # Format used in the READY and GUILD_CREATE members list def guild_member_format { mute: @mute, deaf: @deaf, joined_at: Ldash.format_time(@joined_at), user: @user.compact, roles: @roles.map(&:id).map(&:to_s) } end # Format used in the READY and GUILD_CREATE presences list def presence_format { user: @user.id_format, status: @status, game: game_object } end # Format used in the READY and GUILD_CREATE voice state list def voice_state_format { user_id: @user.id.to_s, suppress: false, # TODO: voice states self_mute: false, # TODO: voice states self_deaf: false, # TODO: voice states mute: @mute, deaf: @deaf, session_id: @session.id, channel_id: @voice_channel ? @voice_channel.id : nil } end private def game_object return nil unless @game { name: @game } end end # Class for user avatars and server icons class Avatar < DataObject data_attribute :hash data_attribute :image_data # to_s should just be the hash alias_method :to_s, :hash end # Channels class Channel < DataObject data_attribute :id, &:generate_id data_attribute :name data_attribute :topic data_attribute :position data_attribute :permission_overwrites data_attribute :server data_attribute :type data_attribute :bitrate data_attribute :recipient def private? [email protected]? end # Format used in READY and GUILD_CREATE def guild_channel_format { type: @type, topic: @topic, id: @id.to_s, name: @name, position: @position, permission_overwrites: permission_overwrites_format, bitrate: @bitrate } end # Format used in CHANNEL_CREATE (private or public), CHANNEL_DELETE (private or public) and CHANNEL_UPDATE def channel_create_format if private? { id: @id.to_s, is_private: true, recipient: @recipient.compact } else { guild_id: @server.id.to_s, id: @id.to_s, is_private: false, name: @name, permission_overwrites: permission_overwrites_format, position: @position, topic: @topic, type: @type, bitrate: @bitrate } end end # Format used in the READY private_channels array def private_channels_format { recipient: @recipient.compact, is_private: true, id: @id.to_s } end private def permission_overwrites_format [ { # TODO: change this default overwrite format into actual data type: role, id: @server.id.to_s, deny: 0, allow: 0 } ] end end # Roles class Role < DataObject data_attribute :id, &:generate_id DEFAULT_PERMISSIONS = 36_953_089 data_attribute(:permissions) { DEFAULT_PERMISSIONS } data_attribute :server data_attribute :position data_attribute :name data_attribute :hoist data_attribute :colour # Format used if this role is embedded into guild data (e.g. in READY or GUILD_CREATE) def guild_role_format { position: @position, permissions: @permissions, managed: false, # TODO: investigate what this is (probably integration stuff) id: @id.to_s, name: @name, hoist: @hoist, color: @colour # damn American spelling } end end # Discord servers class Server < DataObject data_attribute :id, &:generate_id data_attribute :name data_attribute :icon data_attribute :owner_id data_attribute(:afk_timeout) { 300 } data_attribute :afk_channel data_attribute(:bot_joined_at) { Time.now } data_attribute :roles do |_, this| # @everyone role Role.new(id: this.id, # role ID = server ID name: '@everyone', server: this, position: -1, hoist: false, colour: 0) end data_attribute :channels do |_, this| [ # #general text channel Channel.new(id: this.id, name: 'general', server: this, type: 'text', position: 0), # General voice channel Channel.new(id: this.id + 1, name: 'General', server: this, type: 'voice', bitrate: 64_000) ] end data_attribute :members do [] end data_attribute(:region) { 'london' } def large? @session.large?(@members.length) end def member_count @members.length end # Format used in READY and GUILD_CREATE def guild_format channels = @channels.map(&:guild_channel_format) roles = @roles.map(&:guild_role_format) members = tiny_members.map(&:guild_member_format) presences = tiny_members.map(&:presence_format) voice_states = tiny_members.select(&:in_voice_channel?).map(&:voice_state_format) { afk_timeout: @afk_timeout, joined_at: Ldash.format_time(@bot_joined_at), afk_channel_id: @afk_channel.id, id: @id.to_s, icon: @icon, name: @name, large: large?, owner_id: @owner_id.to_s, region: @region, member_count: member_count, channels: channels, roles: roles, members: members, presences: presences, voice_states: voice_states } end # Format used when a guild is unavailable due to an outage def unavailable_format { id: @id.to_s, unavailable: true } end private # Get a list of members according to large_threshold def tiny_members return @members unless large? @members.select { |e| e.status != :offline } end end # The default user in case l- needs one but none exists DEFAULT_USER = User.new(id: 66237334693085184, username: 'meew0', avatar: 'd18a450706c3b6c379f7e2329f64c9e7', discriminator: 3569, email: '[email protected]', password: 'hunter2', verified: true) # Mixin to generate discrims module DiscrimGenerator def generate_discrim(username) discrims = discrims_for_username(username) raise "Can't find a new discrim for username #{username} - too many users with the same username! Calm down with your presets" if discrims.length == 9999 generated = nil loop do generated = rand(1..9999) break unless discrims.include? generated end generated end private def discrims_for_username(username) @users.select { |e| e.username == username }.map(&:discriminator) end end # L- session class Session attr_accessor :users, :private_channels, :servers, :messages, :tokens attr_accessor :ws attr_accessor :large_threshold, :heartbeat_interval attr_reader :id def initialize @users = [] @private_channels = [] @servers = [] @messages = [] @tokens = [] @token_num = 0 @large_threshold = 100 # TODO @heartbeat_interval = 41_250 # Discord doesn't always use this exact interval but it seems common enough to use it as the default @ws = DummyWS.new @id = object_id.to_s(16).rjust(32, '0') end def load_preset(name) instance_eval(File.read("presets/#{name}.rb")) end def ws? [email protected]? end def create_token(user) # The first part of a token is the bot user ID, base 64 encoded. first_part = Base64.encode64(user.id.to_s).strip # The second part is seconds since Jan 1 2011, base 64 encoded. second_part = Base64.encode64([@token_num].pack('Q>').sub(/^\x00+/, '')).strip # The third part is apparently a HMAC - we don't care about that so just generate a random string # WTF kind of library would rely on this anyway third_part = Base64.encode64([*0..17].map { rand(0..255) }.pack('C*')).strip token = "#{first_part}.#{second_part}.#{third_part}" @tokens << token token end # Generates an ID according to Discord's snowflake system def generate_id(_) accurate_timestamp = (Time.now.to_f * 1000).round time_part = (accurate_timestamp - DISCORD_EPOCH) << 22 random_part = rand(0...2**22) time_part | random_part end def large?(member_count) member_count >= @large_threshold end include DiscrimGenerator def token?(token) @tokens.include? token end def bot_user user = @users.find(&:bot_user_format) # If none exists, use the default user user || DEFAULT_USER end end end
24.262366
159
0.603262
399688c6f109fad0aea121033aebb260689046a7
420
cask 'waterfox' do version '53.0.3' sha256 'b3ba545beeb1383f90a9bad90704848cb71a517356e14ca1e77db565efd43f07' # storage-waterfox.netdna-ssl.com was verified as official when first introduced to the cask url "https://storage-waterfox.netdna-ssl.com/releases/osx64/installer/Waterfox%20#{version.before_comma}%20Setup.dmg" name 'Waterfox' homepage 'https://www.waterfoxproject.org/' app 'Waterfox.app' end
35
119
0.785714
e83fe99754116fe1ce85bbc5fbcfb9d6ad2b9394
37,470
# frozen_string_literal: true require "generators/generators_test_helper" require "rails/generators/rails/app/app_generator" require "generators/shared_generator_tests" DEFAULT_APP_FILES = %w( .gitignore .ruby-version README.md Gemfile Rakefile config.ru app/assets/config/manifest.js app/assets/images app/javascript app/javascript/channels app/javascript/channels/consumer.js app/javascript/channels/index.js app/javascript/packs/application.js app/assets/stylesheets app/assets/stylesheets/application.css app/channels/application_cable/channel.rb app/channels/application_cable/connection.rb app/controllers app/controllers/application_controller.rb app/controllers/concerns app/helpers app/helpers/application_helper.rb app/mailers app/mailers/application_mailer.rb app/models app/models/application_record.rb app/models/concerns app/jobs app/jobs/application_job.rb app/views/layouts app/views/layouts/application.html.erb app/views/layouts/mailer.html.erb app/views/layouts/mailer.text.erb bin/rails bin/rake bin/setup bin/yarn config/application.rb config/boot.rb config/cable.yml config/environment.rb config/environments config/environments/development.rb config/environments/production.rb config/environments/test.rb config/initializers config/initializers/application_controller_renderer.rb config/initializers/assets.rb config/initializers/backtrace_silencers.rb config/initializers/cookies_serializer.rb config/initializers/content_security_policy.rb config/initializers/filter_parameter_logging.rb config/initializers/inflections.rb config/initializers/mime_types.rb config/initializers/wrap_parameters.rb config/locales config/locales/en.yml config/puma.rb config/routes.rb config/credentials.yml.enc config/spring.rb config/storage.yml db db/seeds.rb lib lib/tasks lib/assets log package.json public storage test/application_system_test_case.rb test/test_helper.rb test/fixtures test/fixtures/files test/channels/application_cable/connection_test.rb test/controllers test/models test/helpers test/mailers test/integration test/system vendor tmp tmp/cache tmp/cache/assets tmp/storage ) class AppGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper arguments [destination_root] # brings setup, teardown, and some tests include SharedGeneratorTests def default_files ::DEFAULT_APP_FILES end def test_skip_bundle assert_not_called(generator([destination_root], skip_bundle: true, skip_webpack_install: true), :bundle_command) do quietly { generator.invoke_all } # skip_bundle is only about running bundle install, ensure the Gemfile is still # generated. assert_file "Gemfile" end end def test_assets run_generator assert_file("app/views/layouts/application.html.erb", /stylesheet_link_tag\s+'application', media: 'all', 'data-turbolinks-track': 'reload'/) assert_file("app/views/layouts/application.html.erb", /javascript_pack_tag\s+'application', 'data-turbolinks-track': 'reload'/) assert_file("app/assets/stylesheets/application.css") assert_file("app/javascript/packs/application.js") end def test_application_job_file_present run_generator assert_file("app/jobs/application_job.rb") end def test_invalid_application_name_raises_an_error content = capture(:stderr) { run_generator [File.join(destination_root, "43-things")] } assert_equal "Invalid application name 43-things. Please give a name which does not start with numbers.\n", content end def test_invalid_application_name_is_fixed run_generator [File.join(destination_root, "things-43")] assert_file "things-43/config/environment.rb", /Rails\.application\.initialize!/ assert_file "things-43/config/application.rb", /^module Things43$/ end def test_application_new_exits_with_non_zero_code_on_invalid_application_name quietly { system "rails new test --no-rc" } assert_equal false, $?.success? end def test_application_new_exits_with_message_and_non_zero_code_when_generating_inside_existing_rails_directory app_root = File.join(destination_root, "myfirstapp") run_generator [app_root] output = nil Dir.chdir(app_root) do output = `rails new mysecondapp` end assert_equal "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\nType 'rails' for help.\n", output assert_equal false, $?.success? end def test_application_new_show_help_message_inside_existing_rails_directory app_root = File.join(destination_root, "myfirstapp") run_generator [app_root] output = Dir.chdir(app_root) do `rails new --help` end assert_match(/rails new APP_PATH \[options\]/, output) assert_equal true, $?.success? end def test_application_name_is_detected_if_it_exists_and_app_folder_renamed app_root = File.join(destination_root, "myapp") app_moved_root = File.join(destination_root, "myapp_moved") run_generator [app_root] stub_rails_application(app_moved_root) do Rails.application.stub(:is_a?, -> *args { Rails::Application }) do FileUtils.mv(app_root, app_moved_root) # make sure we are in correct dir FileUtils.cd(app_moved_root) generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_moved_root, shell: @shell generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_file "myapp_moved/config/environment.rb", /Rails\.application\.initialize!/ end end end def test_app_update_generates_correct_session_key app_root = File.join(destination_root, "myapp") run_generator [app_root] stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell generator.send(:app_const) quietly { generator.send(:update_config_files) } end end def test_new_application_use_json_serializer run_generator assert_file("config/initializers/cookies_serializer.rb", /Rails\.application\.config\.action_dispatch\.cookies_serializer = :json/) end def test_new_application_not_include_api_initializers run_generator assert_no_file "config/initializers/cors.rb" end def test_new_application_doesnt_need_defaults run_generator assert_no_file "config/initializers/new_framework_defaults_6_1.rb" end def test_new_application_load_defaults app_root = File.join(destination_root, "myfirstapp") run_generator [app_root] output = nil assert_file "#{app_root}/config/application.rb", /\s+config\.load_defaults #{Rails::VERSION::STRING.to_f}/ Dir.chdir(app_root) do output = `SKIP_REQUIRE_WEBPACKER=true ./bin/rails r "puts Rails.application.config.assets.unknown_asset_fallback"` end assert_equal "false\n", output end def test_csp_initializer_include_connect_src_example run_generator assert_file "config/initializers/content_security_policy.rb" do |content| assert_match(/# policy\.connect_src/, content) end end def test_app_update_keep_the_cookie_serializer_if_it_is_already_configured app_root = File.join(destination_root, "myapp") run_generator [app_root] stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_file("#{app_root}/config/initializers/cookies_serializer.rb", /Rails\.application\.config\.action_dispatch\.cookies_serializer = :json/) end end def test_app_update_set_the_cookie_serializer_to_marshal_if_it_is_not_already_configured app_root = File.join(destination_root, "myapp") run_generator [app_root] FileUtils.rm("#{app_root}/config/initializers/cookies_serializer.rb") stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_file("#{app_root}/config/initializers/cookies_serializer.rb", /Valid options are :json, :marshal, and :hybrid\.\nRails\.application\.config\.action_dispatch\.cookies_serializer = :marshal/) end end def test_app_update_create_new_framework_defaults app_root = File.join(destination_root, "myapp") run_generator [app_root] assert_no_file "#{app_root}/config/initializers/new_framework_defaults_6_1.rb" stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], { update: true }, { destination_root: app_root, shell: @shell } generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_file "#{app_root}/config/initializers/new_framework_defaults_6_1.rb" end end def test_app_update_does_not_create_rack_cors app_root = File.join(destination_root, "myapp") run_generator [app_root] stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_no_file "#{app_root}/config/initializers/cors.rb" end end def test_app_update_does_not_remove_rack_cors_if_already_present app_root = File.join(destination_root, "myapp") run_generator [app_root] FileUtils.touch("#{app_root}/config/initializers/cors.rb") stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_file "#{app_root}/config/initializers/cors.rb" end end def test_app_update_does_not_generate_yarn_contents_when_bin_yarn_is_not_used app_root = File.join(destination_root, "myapp") run_generator [app_root, "--skip-javascript"] stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], { update: true, skip_javascript: true }, { destination_root: app_root, shell: @shell } generator.send(:app_const) quietly { generator.send(:update_bin_files) } assert_no_file "#{app_root}/bin/yarn" assert_file "#{app_root}/bin/setup" do |content| assert_no_match(/system\('bin\/yarn'\)/, content) end end end def test_app_update_does_not_generate_assets_initializer_when_skip_sprockets_is_given app_root = File.join(destination_root, "myapp") run_generator [app_root, "--skip-sprockets"] stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], { update: true, skip_sprockets: true }, { destination_root: app_root, shell: @shell } generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_no_file "#{app_root}/config/initializers/assets.rb" end end def test_app_update_does_not_generate_spring_contents_when_skip_spring_is_given app_root = File.join(destination_root, "myapp") run_generator [app_root, "--skip-spring"] stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], { update: true, skip_spring: true }, { destination_root: app_root, shell: @shell } generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_no_file "#{app_root}/config/spring.rb" end end def test_app_update_does_not_generate_action_cable_contents_when_skip_action_cable_is_given app_root = File.join(destination_root, "myapp") run_generator [app_root, "--skip-action-cable"] stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], { update: true, skip_action_cable: true }, { destination_root: app_root, shell: @shell } generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_no_file "#{app_root}/config/cable.yml" assert_file "#{app_root}/config/environments/production.rb" do |content| assert_no_match(/config\.action_cable/, content) end assert_no_file "#{app_root}/test/channels/application_cable/connection_test.rb" end end def test_app_update_does_not_generate_bootsnap_contents_when_skip_bootsnap_is_given app_root = File.join(destination_root, "myapp") run_generator [app_root, "--skip-bootsnap"] stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], { update: true, skip_bootsnap: true }, { destination_root: app_root, shell: @shell } generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_file "#{app_root}/config/boot.rb" do |content| assert_no_match(/require 'bootsnap\/setup'/, content) end end end def test_gem_for_active_storage run_generator assert_file "Gemfile", /^# gem 'image_processing'/ end def test_gem_for_active_storage_when_skip_active_storage_is_given run_generator [destination_root, "--skip-active-storage"] assert_no_gem "image_processing" end def test_app_update_does_not_generate_active_storage_contents_when_skip_active_storage_is_given app_root = File.join(destination_root, "myapp") run_generator [app_root, "--skip-active-storage"] stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], { update: true, skip_active_storage: true }, { destination_root: app_root, shell: @shell } generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_file "#{app_root}/config/environments/development.rb" do |content| assert_no_match(/config\.active_storage/, content) end assert_file "#{app_root}/config/environments/production.rb" do |content| assert_no_match(/config\.active_storage/, content) end assert_file "#{app_root}/config/environments/test.rb" do |content| assert_no_match(/config\.active_storage/, content) end assert_no_file "#{app_root}/config/storage.yml" end end def test_app_update_does_not_generate_active_storage_contents_when_skip_active_record_is_given app_root = File.join(destination_root, "myapp") run_generator [app_root, "--skip-active-record"] stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], { update: true, skip_active_record: true }, { destination_root: app_root, shell: @shell } generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_file "#{app_root}/config/environments/development.rb" do |content| assert_no_match(/config\.active_storage/, content) end assert_file "#{app_root}/config/environments/production.rb" do |content| assert_no_match(/config\.active_storage/, content) end assert_file "#{app_root}/config/environments/test.rb" do |content| assert_no_match(/config\.active_storage/, content) end assert_no_file "#{app_root}/config/storage.yml" end end def test_generator_skips_action_mailbox_when_skip_action_mailbox_is_given run_generator [destination_root, "--skip-action-mailbox"] assert_file "#{application_path}/config/application.rb", /#\s+require\s+["']action_mailbox\/engine["']/ end def test_generator_skips_action_mailbox_when_skip_active_record_is_given run_generator [destination_root, "--skip-active-record"] assert_file "#{application_path}/config/application.rb", /#\s+require\s+["']action_mailbox\/engine["']/ end def test_generator_skips_action_mailbox_when_skip_active_storage_is_given run_generator [destination_root, "--skip-active-storage"] assert_file "#{application_path}/config/application.rb", /#\s+require\s+["']action_mailbox\/engine["']/ end def test_generator_skips_action_text_when_skip_action_text_is_given run_generator [destination_root, "--skip-action-text"] assert_file "#{application_path}/config/application.rb", /#\s+require\s+["']action_text\/engine["']/ end def test_generator_skips_action_text_when_skip_active_record_is_given run_generator [destination_root, "--skip-active-record"] assert_file "#{application_path}/config/application.rb", /#\s+require\s+["']action_text\/engine["']/ end def test_generator_skips_action_text_when_skip_active_storage_is_given run_generator [destination_root, "--skip-active-storage"] assert_file "#{application_path}/config/application.rb", /#\s+require\s+["']action_text\/engine["']/ end def test_app_update_does_not_change_config_target_version app_root = File.join(destination_root, "myapp") run_generator [app_root, "--skip-spring"] FileUtils.cd(app_root) do config = "config/application.rb" content = File.read(config) File.write(config, content.gsub(/config\.load_defaults #{Rails::VERSION::STRING.to_f}/, "config.load_defaults 5.1")) quietly { system("bin/rails app:update") } end assert_file "#{app_root}/config/application.rb", /\s+config\.load_defaults 5\.1/ end def test_app_update_does_not_change_app_name_when_app_name_is_hyphenated_name app_root = File.join(destination_root, "hyphenated-app") run_generator [app_root, "-d", "postgresql"] assert_file "#{app_root}/config/database.yml" do |content| assert_match(/hyphenated_app_development/, content) assert_no_match(/hyphenated-app_development/, content) end assert_file "#{app_root}/config/cable.yml" do |content| assert_match(/hyphenated_app/, content) assert_no_match(/hyphenated-app/, content) end stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], { update: true }, { destination_root: app_root, shell: @shell } generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_file "#{app_root}/config/cable.yml" do |content| assert_match(/hyphenated_app/, content) assert_no_match(/hyphenated-app/, content) end end end def test_application_names_are_not_singularized run_generator [File.join(destination_root, "hats")] assert_file "hats/config/environment.rb", /Rails\.application\.initialize!/ end def test_gemfile_has_no_whitespace_errors run_generator absolute = File.expand_path("Gemfile", destination_root) File.open(absolute, "r") do |f| f.each_line do |line| assert_no_match %r{/^[ \t]+$/}, line end end end def test_config_database_is_added_by_default run_generator assert_file "config/database.yml", /sqlite3/ if defined?(JRUBY_VERSION) assert_gem "activerecord-jdbcsqlite3-adapter" else assert_gem "sqlite3", "'~> 1.4'" end end def test_config_mysql_database run_generator([destination_root, "-d", "mysql"]) assert_file "config/database.yml", /mysql/ if defined?(JRUBY_VERSION) assert_gem "activerecord-jdbcmysql-adapter" else assert_gem "mysql2", "'~> 0.5'" end end def test_config_database_app_name_with_period run_generator [File.join(destination_root, "common.usage.com"), "-d", "postgresql"] assert_file "common.usage.com/config/database.yml", /common_usage_com/ end def test_config_postgresql_database run_generator([destination_root, "-d", "postgresql"]) assert_file "config/database.yml", /postgresql/ if defined?(JRUBY_VERSION) assert_gem "activerecord-jdbcpostgresql-adapter" else assert_gem "pg", "'>= 0.18', '< 2.0'" end end def test_config_jdbcmysql_database run_generator([destination_root, "-d", "jdbcmysql"]) assert_file "config/database.yml", /mysql/ assert_gem "activerecord-jdbcmysql-adapter" end def test_config_jdbcsqlite3_database run_generator([destination_root, "-d", "jdbcsqlite3"]) assert_file "config/database.yml", /sqlite3/ assert_gem "activerecord-jdbcsqlite3-adapter" end def test_config_jdbcpostgresql_database run_generator([destination_root, "-d", "jdbcpostgresql"]) assert_file "config/database.yml", /postgresql/ assert_gem "activerecord-jdbcpostgresql-adapter" end def test_config_jdbc_database run_generator([destination_root, "-d", "jdbc"]) assert_file "config/database.yml", /jdbc/ assert_file "config/database.yml", /mssql/ assert_gem "activerecord-jdbc-adapter" end if defined?(JRUBY_VERSION) def test_config_jdbc_database_when_no_option_given run_generator assert_file "config/database.yml", /sqlite3/ assert_gem "activerecord-jdbcsqlite3-adapter" end end def test_generator_defaults_to_puma_version run_generator [destination_root] assert_gem "puma", "'~> 4.1'" end def test_generator_if_skip_puma_is_given run_generator [destination_root, "--skip-puma"] assert_no_file "config/puma.rb" assert_no_gem "puma" end def test_generator_has_assets_gems run_generator assert_gem "sass-rails" end def test_action_cable_redis_gems run_generator assert_file "Gemfile", /^# gem 'redis'/ end def test_generator_if_skip_test_is_given run_generator [destination_root, "--skip-test"] assert_file "config/application.rb", /#\s+require\s+["']rails\/test_unit\/railtie["']/ assert_no_gem "capybara" assert_no_gem "selenium-webdriver" assert_no_gem "webdrivers" assert_no_directory("test") end def test_generator_if_skip_system_test_is_given run_generator [destination_root, "--skip-system-test"] assert_no_gem "capybara" assert_no_gem "selenium-webdriver" assert_no_gem "webdrivers" assert_directory("test") assert_no_directory("test/system") end def test_does_not_generate_system_test_files_if_skip_system_test_is_given run_generator [destination_root, "--skip-system-test"] Dir.chdir(destination_root) do quietly { `./bin/rails g scaffold User` } assert_no_file("test/application_system_test_case.rb") assert_no_file("test/system/users_test.rb") end end def test_javascript_is_skipped_if_required run_generator [destination_root, "--skip-javascript"] assert_no_file "app/javascript" assert_file "app/views/layouts/application.html.erb" do |contents| assert_match(/stylesheet_link_tag\s+'application', media: 'all' %>/, contents) assert_no_match(/javascript_pack_tag\s+'application'/, contents) end end def test_inclusion_of_jbuilder run_generator assert_gem "jbuilder" end def test_inclusion_of_a_debugger run_generator if defined?(JRUBY_VERSION) || RUBY_ENGINE == "rbx" assert_no_gem "byebug" else assert_gem "byebug" end end def test_inclusion_of_listen_related_configuration_by_default run_generator if /darwin|linux/.match?(RbConfig::CONFIG["host_os"]) assert_listen_related_configuration else assert_no_listen_related_configuration end end def test_inclusion_of_listen_related_configuration_on_other_rubies ruby_engine = Object.send(:remove_const, :RUBY_ENGINE) Object.const_set(:RUBY_ENGINE, "MyRuby") run_generator if /darwin|linux/.match?(RbConfig::CONFIG["host_os"]) assert_listen_related_configuration else assert_no_listen_related_configuration end ensure Object.send(:remove_const, :RUBY_ENGINE) Object.const_set(:RUBY_ENGINE, ruby_engine) end def test_non_inclusion_of_listen_related_configuration_if_skip_listen run_generator [destination_root, "--skip-listen"] assert_no_listen_related_configuration end def test_evented_file_update_checker_config run_generator assert_file "config/environments/development.rb" do |content| if /darwin|linux/.match?(RbConfig::CONFIG["host_os"]) assert_match(/^\s*config\.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) else assert_match(/^\s*# config\.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) end end end def test_template_from_dir_pwd FileUtils.cd(Rails.root) assert_match(/It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"])) end def test_usage_read_from_file assert_called(File, :read, returns: "USAGE FROM FILE") do assert_equal "USAGE FROM FILE", Rails::Generators::AppGenerator.desc end end def test_default_usage assert_called(Rails::Generators::AppGenerator, :usage_path, returns: nil) do assert_match(/Create rails files for app generator/, Rails::Generators::AppGenerator.desc) end end def test_default_namespace assert_match "rails:app", Rails::Generators::AppGenerator.namespace end def test_file_is_added_for_backwards_compatibility action :file, "lib/test_file.rb", "heres test data" assert_file "lib/test_file.rb", "heres test data" end def test_pretend_option output = run_generator [File.join(destination_root, "myapp"), "--pretend"] assert_no_match(/run bundle install/, output) assert_no_match(/run git init/, output) end def test_quiet_option output = run_generator [File.join(destination_root, "myapp"), "--quiet"] assert_empty output end def test_force_option_overwrites_every_file_except_master_key run_generator [File.join(destination_root, "myapp")] output = run_generator [File.join(destination_root, "myapp"), "--force"] assert_match(/force/, output) assert_no_match("force config/master.key", output) end def test_application_name_with_spaces path = File.join(destination_root, "foo bar") # This also applies to MySQL apps but not with SQLite run_generator [path, "-d", "postgresql"] assert_file "foo bar/config/database.yml", /database: foo_bar_development/ end def test_web_console run_generator assert_gem "web-console" end def test_web_console_with_dev_option run_generator [destination_root, "--dev", "--skip-bundle"] assert_file "Gemfile" do |content| assert_match(/gem 'web-console',\s+github: 'rails\/web-console'/, content) assert_no_match(/\Agem 'web-console', '>= 3\.3\.0'\z/, content) end end def test_web_console_with_edge_option run_generator [destination_root, "--edge"] assert_file "Gemfile" do |content| assert_match(/gem 'web-console',\s+github: 'rails\/web-console'/, content) assert_no_match(/\Agem 'web-console', '>= 3\.3\.0'\z/, content) end end def test_generation_runs_bundle_install generator([destination_root], skip_webpack_install: true) assert_bundler_command_called("install") end def test_generation_use_original_bundle_environment generator([destination_root], skip_webpack_install: true) mock_original_env = -> do { "BUNDLE_RUBYONRAILS__ORG" => "user:pass" } end ensure_environment_is_set = -> *_args do assert_equal "user:pass", ENV["BUNDLE_RUBYONRAILS__ORG"] end Bundler.stub :original_env, mock_original_env do generator.stub :exec_bundle_command, ensure_environment_is_set do quietly { generator.invoke_all } end end end def test_dev_option generator([destination_root], dev: true, skip_webpack_install: true) assert_bundler_command_called("install") rails_path = File.expand_path("../../..", Rails.root) assert_file "Gemfile", /^gem\s+["']rails["'],\s+path:\s+["']#{Regexp.escape(rails_path)}["']$/ end def test_edge_option generator([destination_root], edge: true, skip_webpack_install: true) assert_bundler_command_called("install") assert_file "Gemfile", %r{^gem\s+["']rails["'],\s+github:\s+["']#{Regexp.escape("rails/rails")}["']$} end def test_spring run_generator assert_gem "spring" assert_file("config/environments/test.rb") do |contents| assert_match("config.cache_classes = false", contents) end end def test_bundler_binstub generator([destination_root], skip_webpack_install: true) assert_bundler_command_called("binstubs bundler") end def test_spring_binstubs jruby_skip "spring doesn't run on JRuby" generator([destination_root], skip_webpack_install: true) assert_bundler_command_called("exec spring binstub --all") end def test_spring_no_fork jruby_skip "spring doesn't run on JRuby" assert_called_with(Process, :respond_to?, [[:fork], [:fork], [:fork]], returns: false) do run_generator assert_no_gem "spring" end end def test_skip_spring run_generator [destination_root, "--skip-spring"] assert_no_file "config/spring.rb" assert_no_gem "spring" assert_file("config/environments/test.rb") do |contents| assert_match("config.cache_classes = true", contents) end end def test_spring_with_dev_option run_generator [destination_root, "--dev", "--skip-bundle"] assert_no_gem "spring" end def test_skip_javascript_option command_check = -> command, *_ do @called ||= 0 if command == "webpacker:install" @called += 1 assert_equal 0, @called, "webpacker:install expected not to be called, but was called #{@called} times." end end generator([destination_root], skip_javascript: true).stub(:rails_command, command_check) do generator.stub :bundle_command, nil do quietly { generator.invoke_all } end end assert_no_gem "webpacker" assert_file "config/initializers/content_security_policy.rb" do |content| assert_no_match(/policy\.connect_src/, content) end end def test_webpack_option_with_js_framework command_check = -> command, *_ do case command when "webpacker:install" @webpacker ||= 0 @webpacker += 1 assert_equal 1, @webpacker, "webpacker:install expected to be called once, but was called #{@webpacker} times." when "webpacker:install:react" @react ||= 0 @react += 1 assert_equal 1, @react, "webpacker:install:react expected to be called once, but was called #{@react} times." end end generator([destination_root], webpack: "react").stub(:rails_command, command_check) do generator.stub :bundle_command, nil do quietly { generator.invoke_all } end end assert_gem "webpacker" end def test_skip_webpack_install command_check = -> command do if command == "webpacker:install" assert false, "webpacker:install expected not to be called." end end generator([destination_root], skip_webpack_install: true).stub(:rails_command, command_check) do quietly { generator.invoke_all } end assert_gem "webpacker" assert_no_file "config/webpacker.yml" output = Dir.chdir(destination_root) do `rails --help` end assert_match(/The most common rails commands are:/, output) assert_equal true, $?.success? end def test_generator_if_skip_turbolinks_is_given run_generator [destination_root, "--skip-turbolinks"] assert_no_gem "turbolinks" assert_file "app/views/layouts/application.html.erb" do |content| assert_no_match(/data-turbolinks-track/, content) end assert_file "app/javascript/packs/application.js" do |content| assert_no_match(/turbolinks/, content) end end def test_bootsnap run_generator [destination_root, "--no-skip-bootsnap"] unless defined?(JRUBY_VERSION) assert_gem "bootsnap" assert_file "config/boot.rb" do |content| assert_match(/require 'bootsnap\/setup'/, content) end else assert_no_gem "bootsnap" assert_file "config/boot.rb" do |content| assert_no_match(/require 'bootsnap\/setup'/, content) end end end def test_skip_bootsnap run_generator [destination_root, "--skip-bootsnap"] assert_no_gem "bootsnap" assert_file "config/boot.rb" do |content| assert_no_match(/require 'bootsnap\/setup'/, content) end end def test_bootsnap_with_dev_option run_generator [destination_root, "--dev", "--skip-bundle"] assert_no_gem "bootsnap" assert_file "config/boot.rb" do |content| assert_no_match(/require 'bootsnap\/setup'/, content) end end def test_inclusion_of_ruby_version run_generator assert_file "Gemfile" do |content| assert_match(/ruby '#{RUBY_VERSION}'/, content) end assert_file ".ruby-version" do |content| if ENV["RBENV_VERSION"] assert_match(/#{ENV["RBENV_VERSION"]}/, content) elsif ENV["rvm_ruby_string"] assert_match(/#{ENV["rvm_ruby_string"]}/, content) else assert_match(/#{RUBY_ENGINE}-#{RUBY_ENGINE_VERSION}/, content) end assert content.end_with?("\n"), "expected .ruby-version to end with newline" end end def test_version_control_initializes_git_repo run_generator [destination_root] assert_directory ".git" end def test_create_keeps run_generator folders_with_keep = %w( app/assets/images app/controllers/concerns app/models/concerns lib/tasks lib/assets log test/fixtures/files test/controllers test/mailers test/models test/helpers test/integration tmp tmp/pids ) folders_with_keep.each do |folder| assert_file("#{folder}/.keep") end end def test_psych_gem run_generator gem_regex = /gem 'psych',\s+'~> 2\.0',\s+platforms: :rbx/ assert_file "Gemfile" do |content| if defined?(Rubinius) assert_match(gem_regex, content) else assert_no_match(gem_regex, content) end end end def test_after_bundle_callback path = "http://example.org/rails_template" template = +%{ after_bundle { run 'echo ran after_bundle' } } template.instance_eval "def read; self; end" # Make the string respond to read check_open = -> *args do assert_equal [ path, "Accept" => "application/x-thor-template" ], args template end sequence = ["git init", "install", "binstubs bundler", "exec spring binstub --all", "webpacker:install", "echo ran after_bundle"] @sequence_step ||= 0 ensure_bundler_first = -> command, options = nil do assert_equal sequence[@sequence_step], command, "commands should be called in sequence #{sequence}" @sequence_step += 1 end generator([destination_root], template: path).stub(:open, check_open, template) do generator.stub(:bundle_command, ensure_bundler_first) do generator.stub(:run, ensure_bundler_first) do generator.stub(:rails_command, ensure_bundler_first) do quietly { generator.invoke_all } end end end end assert_equal 6, @sequence_step end def test_gitignore run_generator assert_file ".gitignore" do |content| assert_match(/config\/master\.key/, content) end end def test_system_tests_directory_generated run_generator assert_directory("test/system") assert_file("test/system/.keep") end unless Gem.win_platform? def test_master_key_is_only_readable_by_the_owner run_generator stat = File.stat("config/master.key") assert_equal "100600", sprintf("%o", stat.mode) end end private def stub_rails_application(root) Rails.application.config.root = root Rails.application.class.stub(:name, "Myapp") do yield end end def action(*args, &block) capture(:stdout) { generator.send(*args, &block) } end def assert_gem(gem, constraint = nil) if constraint assert_file "Gemfile", /^\s*gem\s+["']#{gem}["'], #{constraint}$*/ else assert_file "Gemfile", /^\s*gem\s+["']#{gem}["']$*/ end end def assert_no_gem(gem) assert_file "Gemfile" do |content| assert_no_match(gem, content) end end def assert_listen_related_configuration assert_gem "listen" assert_file "config/environments/development.rb" do |content| assert_match(/^\s*config\.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) end end def assert_no_listen_related_configuration assert_no_gem "listen" assert_file "config/environments/development.rb" do |content| assert_match(/^\s*# config\.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) end end def assert_bundler_command_called(target_command) command_check = -> (command, env = {}) do @command_called ||= 0 case command when target_command @command_called += 1 assert_equal 1, @command_called, "#{command} expected to be called once, but was called #{@command_called} times." end end generator.stub :bundle_command, command_check do quietly { generator.invoke_all } end end end
32.190722
172
0.720763
7af0b2de6d00db5aea8f34e00a08c482d90c7f58
466
class Terraspace::CLI::New class Module < Sequence component_options.each { |args| class_option(*args) } argument :name def create_module puts "=> Creating test for new module: #{name}" plugin_template_source(@options[:lang], "module") # IE: plugin_template_source("hcl", "module") dest = "app/modules/#{name}" dest = "#{@options[:project_name]}/#{dest}" if @options[:project_name] directory ".", dest end end end
29.125
101
0.645923
18e6baaf8f1a19bb089b851388d147b5012a3013
644
# == Schema Information # # Table name: signatures # # id :integer not null, primary key # created_at :datetime # updated_at :datetime # name :text not null # source :string(255) # description :text # category :string(255) # line_type :string(255) # risk :integer # require 'rails_helper' RSpec.describe Signature, type: :model do ## TODO association may not be needed # causes crash: PG::UndefinedTable: ERROR: relation "signature_fps" does not exist #it { should have_many(:signature_fps) } it "valid record" do expect(build(:signature)).to be_valid end end
23.851852
86
0.645963
4a571bc061b1c497a425e446fe87ac782981469c
1,060
module FactoryGirl module Syntax # Extends ActiveRecord::Base to provide a make class method, which is a # shortcut for FactoryGirl.create. # # Usage: # # require 'factory_girl/syntax/make' # # FactoryGirl.define do # factory :user do # name 'Billy Bob' # email '[email protected]' # end # end # # User.make(:name => 'Johnny') # # This syntax was derived from Pete Yandell's machinist. module Make module ActiveRecord #:nodoc: def self.included(base) # :nodoc: base.extend ClassMethods end module ClassMethods #:nodoc: def make(overrides = {}) FactoryGirl.factory_by_name(name.underscore).run(Proxy::Build, overrides) end def make!(overrides = {}) FactoryGirl.factory_by_name(name.underscore).run(Proxy::Create, overrides) end end end end end end ActiveRecord::Base.send(:include, FactoryGirl::Syntax::Make::ActiveRecord)
23.043478
86
0.590566
1a3abca8f9e76c20e26ccffe4ae3134749fb7490
1,381
# encoding: UTF-8 require_dependency "cor1440_gen/concerns/controllers/proyectosfinancieros_controller" module Cor1440Gen class ProyectosfinancierosController < Heb412Gen::ModelosController include Cor1440Gen::Concerns::Controllers::ProyectosfinancierosController before_action :set_proyectofinanciero, only: [:show, :edit, :update, :destroy] skip_before_action :set_proyectofinanciero, only: [:validar] load_and_authorize_resource class: Cor1440Gen::Proyectofinanciero, only: [:new, :create, :destroy, :edit, :update, :index, :show, :objetivospf] def atributos_index [ :id, :nombre ] + [ :financiador_ids => [] ] + [ :fechainicio_localizada, :fechacierre_localizada, :responsable, :proyectofinanciero_usuario, ] + [ :compromisos, :monto, :observaciones, :objetivopf, :indicadorobjetivo, :resultadopf, :indicadorpf, :actividadpf ] end def atributos_show atributos_index - [ :objetivopf, :indicadorobjetivo, :resultadopf, :indicadorpf, :actividadpf ] + [ :marcologico, :caracterizacion, :beneficiario, :plantillahcm, :anexo_proyectofinanciero ] end end end
23.40678
85
0.611151
3380eae097a9e39a8e3bf4702f6958bc9bb5af85
1,114
# frozen_string_literal: true require "spec_helper" require_relative "./../../lib/bu_pr/configuration" describe BuPr::Configuration do let(:opts) { {} } let(:config) { described_class.new(opts) } describe "attr_accessors" do subject { config } it "responds to accessors" do is_expected.to respond_to(:branch) is_expected.to respond_to(:branch=) is_expected.to respond_to(:title) is_expected.to respond_to(:title=) is_expected.to respond_to(:token) is_expected.to respond_to(:token=) is_expected.to respond_to(:repo) is_expected.to respond_to(:repo=) end end describe "#valid?" do subject { config.valid? } before do config.token = "dummy" config.repo = "mmyoji/bu_pr" end context "w/ valid attrs" do it { is_expected.to eq true } end context "w/o token" do before do config.token = "" end it { is_expected.to eq false } end context "w/o repo" do before do config.repo = "" end it { is_expected.to eq false } end end end
19.892857
50
0.61939
ab9d1406941370d2310616c5eed62d0131c9e0b6
133
class ApplicationController < ActionController::Base def fallback_index_html render :file => 'public/index.html' end end
16.625
52
0.744361
abc63d661b33ae708f634a98ba8f8dd7bd18a634
544
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Category.create([ { name: 'Family', priority: 1 }, { name: 'Sports', priority: 2 }, { name: 'Entertainment', priority: 3 }, { name: 'Politics', priority: 4 } ])
36.266667
115
0.674632
87bf1b92720b4ada9426c11482b813cba3a01da0
1,256
# # Be sure to run `pod lib lint LYViewKit.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'LYViewKit' s.version = '0.1.0' s.summary = 'LYViewKit SDK.' s.homepage = 'https://github.com/yyly/LYViewKit' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'yyly' => '[email protected]' } s.source = { :git => 'https://github.com/yyly/LYViewKit.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '9.0' s.source_files = 'LYViewKit/Classes/LYViewKit.h' s.subspec 'CoverView' do |c| c.source_files = 'LYViewKit/Classes/CoverView/**/*.{h,m}' c.dependency 'Masonry' end # s.resource_bundles = { # 'LYViewKit' => ['LYViewKit/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' end
33.052632
98
0.618631
b9f00baf9a7f914fbff72d84fbe5b266f7a846ad
4,191
require File.dirname(__FILE__) + '/spec_helper' include Babygitter::FolderAnalysisMethods describe Babygitter::FolderAnalysisMethods do before(:each) do Babygitter.marked_folders = [] Babygitter.use_whitelist = false end it "should create usuable regexs by level" do "folder_level_1/folder_level_2/file".scan(BRANCH.build_regexp(1)).to_s.should == "folder_level_1" "folder_level_1/folder_level_2/file".scan(BRANCH.build_regexp(2)).to_s.should == "folder_level_1/folder_level_2" "folder_level_1/folder_level_2/file".scan(BRANCH.build_regexp(3)).to_s.should == "" end it "should create an array map for plotting lines commit by folder" do BRANCH.create_hash_map(["bin", "lib", "test"]).should == {""=> 0, "lib"=> 0, "bin"=> 0, "test"=> 0} end it "should fully map out the folders by depth" do BRANCH.get_array_of_mapped_folder_names.should == [["bin", "lib", "test"], ["lib/grit", "test/fixtures"]] end it "should find the right key for the hash" do BRANCH.find_key(3, BRANCH.commits.first.stats.to_diffstat.flatten.first).should == "lib/grit" BRANCH.find_key(2, BRANCH.commits.first.stats.to_diffstat.flatten.first).should == "lib/grit" BRANCH.find_key(1, BRANCH.commits.first.stats.to_diffstat.flatten.first).should == "lib" end it 'should map out the diffs by folder, level and date' do BRANCH.get_folder_commits_by_week_and_level(2)[0..2].should == [{"test/fixtures"=>42, ""=>79, "lib/grit"=>564, "lib"=>19, "bin"=>0, "test"=>294}, {"test/fixtures"=>131, ""=>6, "lib/grit"=>121, "lib"=>6, "bin"=>0, "test"=>60}, {"test/fixtures"=>0, ""=>181, "lib/grit"=>53, "lib"=>1, "bin"=>0, "test"=>52}] BRANCH.get_folder_commits_by_week_and_level(1)[0..2].should == [{""=>79, "lib"=>583, "bin"=>0, "test"=>336}, {""=>6, "lib"=>127, "bin"=>0, "test"=>191}, {""=>181, "lib"=>54, "bin"=>0, "test"=>52}] end it 'should map out the diffs by folder, level, date and take off blacklisted folders' do Babygitter.marked_folders = ['lib', 'bin', 'Program Folder'] BRANCH.get_folder_commits_by_week_and_level(1)[0..2].should == [{"test"=>336}, {"test"=>191}, {"test"=>52}] end it 'should map out the diffs by folder, level date and for whitelist folder if option is on' do Babygitter.use_whitelist = true Babygitter.marked_folders = ['test'] BRANCH.get_folder_commits_by_week_and_level(1)[0..2].should == [{"test"=>336}, {"test"=>191}, {"test"=>52}] end it "should plot the points out correctly by level of depth" do BRANCH.plot_folder_points(1).should == {""=>[0, 79, 85, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 274, 284, 284, 284, 284, 284, 284, 284, 285, 285, 285, 286, 286, 286, 286], "lib"=>[0, 583, 710, 764, 790, 790, 790, 790, 790, 790, 790, 790, 836, 836, 836, 874, 908, 920, 921, 942, 1074, 1117, 1123, 1169, 1188, 1188, 1190, 1251, 1256, 1256], "test"=>[0, 336, 527, 579, 1269, 1269, 1269, 1269, 1269, 1269, 1269, 1269, 1291, 1291, 1291, 1327, 1574, 1574, 1591, 2272, 2498, 3748, 3751, 3815, 3834, 3834, 3839, 3870, 3870, 3870], "bin"=>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]} BRANCH.plot_folder_points(2).should == {""=>[0, 79, 85, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 274, 284, 284, 284, 284, 284, 284, 284, 285, 285, 285, 286, 286, 286, 286], "test/fixtures"=>[0, 42, 173, 173, 783, 783, 783, 783, 783, 783, 783, 783, 784, 784, 784, 784, 985, 985, 985, 1646, 1748, 2903, 2905, 2910, 2910, 2910, 2910, 2910, 2910, 2910], "lib/grit"=>[0, 564, 685, 738, 763, 763, 763, 763, 763, 763, 763, 763, 809, 809, 809, 843, 876, 888, 889, 910, 1041, 1084, 1090, 1135, 1154, 1154, 1155, 1214, 1219, 1219], "lib"=>[0, 19, 25, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 31, 32, 32, 32, 32, 33, 33, 33, 34, 34, 34, 35, 37, 37, 37], "test"=>[0, 294, 354, 406, 486, 486, 486, 486, 486, 486, 486, 486, 507, 507, 507, 543, 589, 589, 606, 626, 750, 845, 846, 905, 924, 924, 929, 960, 960, 960], "bin"=>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]} end end
59.871429
132
0.619423
1143d10c4918a704ac15ab21436ba103bf154b47
2,072
class Bsdsfv < Formula desc "SFV utility tools" homepage "https://bsdsfv.sourceforge.io/" url "https://downloads.sourceforge.net/project/bsdsfv/bsdsfv/1.18/bsdsfv-1.18.tar.gz" sha256 "577245da123d1ea95266c1628e66a6cf87b8046e1a902ddd408671baecf88495" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "1f2a24ab528de05007b43da3e52628380f4bf6acf8d0d9d2d52cd3defd0c429c" sha256 cellar: :any_skip_relocation, big_sur: "3fe4cd9e74eb5d55bf3ecc10a675600ade3b4f0d56b94d2bcfd9d71e91cae302" sha256 cellar: :any_skip_relocation, catalina: "3abfd33001c44edc6b03905559f8565f923001aa1ccc3a3247ebd073d226ccaa" sha256 cellar: :any_skip_relocation, mojave: "e500396c1a26993727df9ccc8d878e0a4fbc353326206dffcbd18b9fc8071247" sha256 cellar: :any_skip_relocation, high_sierra: "28bee35fbc8c0be9e1182287c58340898d29d9ba0f910109974af6efcb5cd61f" sha256 cellar: :any_skip_relocation, sierra: "38b9d278b430e250b384c5ba2baf3e74dfe0771c5ceea45686022ecb01616ee2" sha256 cellar: :any_skip_relocation, el_capitan: "404ec03e044a019a487adfab90012a29a6655fe67b907d9b4e9a46d4f6c57a9b" sha256 cellar: :any_skip_relocation, yosemite: "fd15cb46a9499bcd1182e8fe4a6ae1de9fb77ced85186601ef6c6579a22d9c51" sha256 cellar: :any_skip_relocation, x86_64_linux: "0af32dda6454f7bed3a7c476ac500f8826dc9ab48b56604205245f1ea491ace6" # linuxbrew-core end # bug report: # https://sourceforge.net/p/bsdsfv/bugs/1/ # Patch from MacPorts patch :DATA def install bin.mkpath inreplace "Makefile" do |s| s.change_make_var! "INSTALL_PREFIX", prefix s.change_make_var! "INDENT", "indent" s.gsub! " ${INSTALL_PROGRAM} bsdsfv ${INSTALL_PREFIX}/bin", " ${INSTALL_PROGRAM} bsdsfv #{bin}/" end system "make", "all" system "make", "install" end end __END__ --- a/bsdsfv.c 2012-09-25 07:31:03.000000000 -0500 +++ b/bsdsfv.c 2012-09-25 07:31:08.000000000 -0500 @@ -44,5 +44,5 @@ typedef struct sfvtable { char filename[FNAMELEN]; - int crc; + unsigned int crc; int found; } SFVTABLE;
43.166667
139
0.772683
38fefe988365747e63238bd263bab10bd150f220
4,098
# encoding: utf-8 require 'spec_helper' describe 'hidden input' do include FormtasticSpecHelper before do @output_buffer = '' mock_everything @form = semantic_form_for(@new_post) do |builder| concat(builder.input(:secret, :as => :hidden)) concat(builder.input(:author_id, :as => :hidden, :value => 99)) concat(builder.input(:published, :as => :hidden, :input_html => {:value => true})) concat(builder.input(:reviewer, :as => :hidden, :input_html => {:class => 'new_post_reviewer', :id => 'new_post_reviewer'})) concat(builder.input(:author, :as => :hidden, :value => 'direct_value', :input_html => {:value => "formtastic_value"})) end end it_should_have_input_wrapper_with_class("hidden") it_should_have_input_wrapper_with_id("post_secret_input") it_should_not_have_a_label it "should generate a input field" do output_buffer.concat(@form) if Formtastic::Util.rails3? output_buffer.should have_tag("form li input#post_secret") output_buffer.should have_tag("form li input#post_secret[@type=\"hidden\"]") output_buffer.should have_tag("form li input#post_secret[@name=\"post[secret]\"]") end it "should pass any explicitly specified value - using :value" do output_buffer.concat(@form) if Formtastic::Util.rails3? output_buffer.should have_tag("form li input#post_author_id[@type=\"hidden\"][@value=\"99\"]") end # Handle Formtastic :input_html options for consistency. it "should pass any explicitly specified value - using :input_html options" do output_buffer.concat(@form) if Formtastic::Util.rails3? output_buffer.should have_tag("form li input#post_published[@type=\"hidden\"][@value=\"true\"]") end it "should pass any option specified using :input_html" do output_buffer.concat(@form) if Formtastic::Util.rails3? output_buffer.should have_tag("form li input#new_post_reviewer[@type=\"hidden\"][@class=\"new_post_reviewer\"]") end it "should prefer :input_html over directly supplied options" do output_buffer.concat(@form) if Formtastic::Util.rails3? output_buffer.should have_tag("form li input#post_author[@type=\"hidden\"][@value=\"formtastic_value\"]") end it "should not render inline errors" do @errors = mock('errors') @errors.stub!(:[]).with(:secret).and_return(["foo", "bah"]) @new_post.stub!(:errors).and_return(@errors) form = semantic_form_for(@new_post) do |builder| concat(builder.input(:secret, :as => :hidden)) end output_buffer.concat(form) if Formtastic::Util.rails3? output_buffer.should_not have_tag("form li p.inline-errors") output_buffer.should_not have_tag("form li ul.errors") end it "should not render inline hints" do form = semantic_form_for(@new_post) do |builder| concat(builder.input(:secret, :as => :hidden, :hint => "all your base are belong to use")) end output_buffer.concat(form) if Formtastic::Util.rails3? output_buffer.should_not have_tag("form li p.inline-hints") output_buffer.should_not have_tag("form li ul.hints") end describe "when namespace is provided" do before do @output_buffer = '' mock_everything @form = semantic_form_for(@new_post, :namespace => 'context2') do |builder| concat(builder.input(:secret, :as => :hidden)) concat(builder.input(:author_id, :as => :hidden, :value => 99)) concat(builder.input(:published, :as => :hidden, :input_html => {:value => true})) concat(builder.input(:reviewer, :as => :hidden, :input_html => {:class => 'new_post_reviewer', :id => 'new_post_reviewer'})) concat(builder.input(:author, :as => :hidden, :value => 'direct_value', :input_html => {:value => "formtastic_value"})) end end attributes_to_check = [:secret, :author_id, :published, :reviewer, :author] attributes_to_check.each do |a| it_should_have_input_wrapper_with_id("context2_post_#{a}_input") end (attributes_to_check - [:reviewer]).each do |a| it_should_have_input_with_id("context2_post_#{a}") end end end
39.028571
132
0.693265
389e10e807777f123a8787d6a0811097fc7da2b7
618
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: flow/entities/event.proto require 'google/protobuf' Google::Protobuf::DescriptorPool.generated_pool.build do add_file("flow/entities/event.proto", :syntax => :proto3) do add_message "flow.entities.Event" do optional :type, :string, 1 optional :transaction_id, :bytes, 2 optional :transaction_index, :uint32, 3 optional :event_index, :uint32, 4 optional :payload, :bytes, 5 end end end module Entities Event = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("flow.entities.Event").msgclass end
29.428571
98
0.723301
edd51ca3236290bf1530b5ff1c954462fb62f054
1,104
module Gamefic module World module Players include Gamefic::World::Entities include Gamefic::World::Commands # An array of entities that are currently connected to users. # # @return [Array<Gamefic::Actor>] def players @players ||= [] end def player_class cls = nil STDERR.puts "Modifying player_class this way is deprecated. Use set_player_class instead" unless cls.nil? @player_class = cls unless cls.nil? @player_class ||= Gamefic::Actor end # @param cls [Class] def set_player_class cls unless cls < Gamefic::Active && cls <= Gamefic::Entity raise ArgumentError, "Player class must be an active entity" end @player_class = cls end # Make a character that a player will control on introduction. # # @return [Gamefic::Actor] def make_player_character cast player_class, name: 'yourself', synonyms: 'self myself you me', proper_named: true end alias get_player_character make_player_character end end end
29.052632
113
0.639493
9184c565617d577940c1769983173fca43b1abaa
703
require "qup" describe Qup do let( :path ) { temp_dir( "qup" ) } let( :uri ) { "maildir://#{path}" } it "should have a version" do Qup::VERSION.should =~ ( %r[\A\d+\.\d+\.\d+\Z] ) end describe '#open' do it 'returns a new session' do s = Qup.open( uri ) s.closed?.should be_false end it 'yields a new session' do Qup.open( uri ) do |s| s.closed?.should be_false end end it 'closes a session at the end of the block' do save_s = nil Qup.open( uri ) do |s| s.closed?.should be_false save_s = s end save_s.closed?.should be_true end end it "opens a new session" do end end
18.5
52
0.544808
ff5237893a4b4ae6f3f69f92ab1b90b5376bdc1e
3,871
require_relative '../../../spec_helper' require 'rexml/document' module Aws module Stubbing module Protocols describe EC2 do describe '#stub_data' do def normalize(xml) result = String.new # REXML only accepts mutable strings REXML::Document.new(xml).write(result, 2) result.strip end let(:api) { ApiHelper.sample_ec2::Client.api } let(:operation) { api.operation(:describe_instances) } it 'returns a stubbed http response' do resp = EC2.new.stub_data(api, operation, {}) expect(resp).to be_kind_of(Seahorse::Client::Http::Response) expect(resp.status_code).to eq(200) end it 'populates the content-type header' do resp = EC2.new.stub_data(api, operation, {}) expect(resp.headers['content-type']).to eq('text/xml;charset=UTF-8') expect(resp.headers['server']).to eq('AmazonEC2') end it 'populates the body with the stub data' do data = { reservations: [ { reservation_id: 'reservation-id', owner_id: 'owner-id', groups: [ { group_id: 'group-id', group_name: 'group-name', } ], instances: [ { instance_id: 'i-12345678', image_id: 'ami-12345678', state: { code: 16, name: 'running', }, tags: [ { key: 'Abc', value: 'mno' }, { key: 'Name', value: '' } ] } ] } ] } resp = EC2.new.stub_data(api, operation, data) expect(normalize(resp.body.string)).to eq(normalize(<<-XML)) <DescribeInstancesResponse xmlns="http://ec2.amazonaws.com/doc/#{api.version}/"> <requestId>stubbed-request-id</requestId> <reservationSet> <item> <reservationId>reservation-id</reservationId> <ownerId>owner-id</ownerId> <groupSet> <item> <groupName>group-name</groupName> <groupId>group-id</groupId> </item> </groupSet> <instancesSet> <item> <instanceId>i-12345678</instanceId> <imageId>ami-12345678</imageId> <instanceState> <code>16</code> <name>running</name> </instanceState> <tagSet> <item> <key>Abc</key> <value>mno</value> </item> <item> <key>Name</key> <value/> </item> </tagSet> </item> </instancesSet> </item> </reservationSet> </DescribeInstancesResponse> XML end end end end end end
36.518868
94
0.366055
d552caa9b161f09f976cd26aeddf2f14c2253a9d
1,497
# frozen_string_literal: true module CarrierWave module Storage class AWSOptions MULTIPART_TRESHOLD = 15 * 1024 * 1024 attr_reader :uploader def initialize(uploader) @uploader = uploader end def read_options aws_read_options end def write_options(new_file) { acl: uploader.aws_acl, body: new_file.to_file, content_type: new_file.content_type }.merge(aws_attributes).merge(aws_write_options) end def move_options(file) { acl: uploader.aws_acl, multipart_copy: file.size >= MULTIPART_TRESHOLD }.merge(aws_attributes).merge(aws_write_options) end alias copy_options move_options def expiration_options(options = {}) uploader_expiration = uploader.aws_authenticated_url_expiration { expires_in: uploader_expiration }.merge(options) end def cloudfront_options(options={}) opts = {} options.each_pair do |key, val| opts[key.to_s.gsub(/_/, '-')] = val end opts end private def aws_attributes attributes = uploader.aws_attributes return {} if attributes.nil? attributes.respond_to?(:call) ? attributes.call : attributes end def aws_read_options uploader.aws_read_options || {} end def aws_write_options uploader.aws_write_options || {} end end end end
22.681818
71
0.617902
e945079eff5a6fe9b792583c7129bd8e0623bf1d
120
class AddCasaToRegistrant < ActiveRecord::Migration def change add_column :registrants, :casa, :boolean end end
20
51
0.766667
7a7f2671cb961da12450e62a16976ec64c98977e
1,107
Pod::Spec.new do |s| s.name = "MLSModel" s.version = "1.0.0" s.summary = "统一模型管理" s.description = <<-DESC 统一管理模型,提供便捷方法 DESC s.homepage = "http://www.minlison.cn" s.license = "MIT" s.author = { "Minlison" => "[email protected]" } s.platform = :ios, "8.0" s.source = { :git => "https://github.com/Minlison/MLSModel.git", :tag => "v#{s.version}" } s.documentation_url = "https://minlison.cn/article/mlsmodel" s.requires_arc = true s.static_framework = true s.default_subspec = 'Core' s.subspec 'Core' do |ss| ss.source_files = "Classes/Core/**/*.{h,m}" ss.public_header_files = "Classes/Core/**/*.h" ss.dependency 'MLSModel/MLSYYModelModify' end s.subspec 'MLSYYModelModify' do |ss| ss.source_files = "Classes/YYModelModify/**/*.{h,m}" ss.public_header_files = "Classes/YYModelModify/**/NSObject+MLSYYModel.h" end # s.subspec 'Mock' do |ss| # ss.source_files = "Classes/Mock/**/*.{h,m}" # ss.public_header_files = "Classes/Mock/**/*.h" # end end
30.75
98
0.588979
11353a67413dfa910f7fbbf805d085f7b14636c0
702
class ApplicationHelper::Toolbar::MiqPoliciesCenter < ApplicationHelper::Toolbar::Basic button_group('miq_policy_vmdb', [ select( :miq_policy_vmdb_choice, nil, t = N_('Configuration'), t, :items => [ button( :miq_policy_new, 'pficon pficon-add-circle-o fa-lg', t = proc do _('Add a New %{model} %{mode} Policy') % { :model => ui_lookup(:model => @sb[:nodeid].camelize), :mode => _(@sb[:mode]).capitalize } end, t, :url_parms => "?typ=basic", :klass => ApplicationHelper::Button::ButtonNewDiscover), ] ), ]) end
28.08
87
0.507123
1cf0681a1c00a6f3449ce630aff5b5a89396db60
161
module Profilum module Landing class ApplicationMailer < ActionMailer::Base default from: '[email protected]' layout 'mailer' end end end
17.888889
48
0.689441
acc8a3f2daccd191d563fd18695a92553cf13358
10,260
require 'rhoconnect-adapters' require 'vendor/sugar/sugar' module RhoconnectAdapters module CRM module Sugar class Adapter < SourceAdapter attr_accessor :crm_object attr_accessor :fields def initialize(source) super(source) @fields = {} @crm_object = self.class.name @default_user_team_name = nil @title_fields = ['id'] end def configure_fields # initialize fields map @fields = get_object_settings['Query_Fields'] @field_picklists = {} static_picklists = get_object_settings['StaticPicklist'] if static_picklists != nil static_picklists.each do |element_name, values| @field_picklists[element_name] = values end end @object_fields = get_object_settings['ObjectFields'] @object_fields = {} if @object_fields == nil # title fields are used in metadata to show # records in the list @title_fields = get_object_settings['TitleFields'] @fields end def get_object_settings return @object_settings if @object_settings begin @object_settings = RhoconnectAdapters::CRM::Field.load_file(File.join(ROOT_PATH,'vendor','sugar','settings',"#{crm_object}.yml")) rescue Exception => e puts "Error opening CRMObjects settings file: #{e}" puts e.backtrace.join("\n") raise e end end def get_picklists begin fields.each do |element_name, element_def| data_type = element_def['Type'] # for picklists - get values # but only for those that are not # already defined if data_type == 'Picklist' and not @field_picklists.has_key?(element_name) @field_picklists[element_name] = get_picklist(element_name) end end rescue RestClient::Exception => e raise e end end def get_picklist(element_name) # check if we already have it in Store picklist = Store.get_data("#{crm_object}:#{element_name}_picklist",Array) return picklist if picklist.size != 0 field_options = get_module._module.fields[element_name]['options'] Store.put_data("#{crm_object}:#{element_name}_picklist", field_options.keys) field_options.keys end def get_user_team_name # retrieve default user team id (it is needed in create method) return @default_user_team_name unless @default_user_team_name == nil @default_user_team_name = Store.get_value("#{current_user.login}:default_user_team_name") if @default_user_team_name == nil team_id = @namespace.session.connection.get_user_team_id team_id.gsub!(/^"(.*?)"$/,'\1') team_mod = @namespace.const_get('Team') @default_user_team_name = team_mod.find_by_id(team_id).name Store.set_value("#{current_user.login}:default_user_team_name", @default_user_team_name) end @default_user_team_name end def login @uri = Store.get_value("#{current_user.login}:service_url") session_object_id = Store.get_value("#{current_user.login}:session_object_id") session_cur = SugarCRM.sessions[session_object_id.to_i] @namespace = SugarCRM.sessions[session_object_id.to_i].namespace_const # obtain default user's Team Name (used in create operations) get_user_team_name # get options for object's attributes get_picklists end def query(params=nil) # # Straightforward way to query data. Dot not fit for large result sets. # # @result = {} # conditions = {:conditions=>{}} # conditions[:conditions][:assigned_user_id] = @namespace.current_user.id # results = get_results(conditions) # @result = create_result_hash(results) # Use stash_result to paginate into result sets conditions = {:conditions=>{}} conditions[:conditions][:assigned_user_id] = @namespace.current_user.id offset, page_sz = 0, 100 conditions[:limit] = page_sz loop do conditions[:offset] = offset results = get_results(conditions) @result = create_result_hash(results) rec_num = @result.size stash_result break if rec_num < page_sz offset += page_sz end end def metadata # define the metadata show_fields = [] new_fields = [] edit_fields = [] model_name = "" + crm_object model_name[0] = model_name[0,1].downcase record_sym = '@' + "#{model_name}" fields.each do |element_name,element_def| next if element_name == 'id' # 1) - read-only show fields field_type = 'labeledvalueli' field = { :name => "#{model_name}\[#{element_name}\]", :label => element_def['Label'], :type => field_type, :value => "{{#{record_sym}/#{element_name}}}" } show_fields << field new_field = field.clone new_field[:type] = 'labeledinputli' new_field.delete(:value) case element_def['Type'] when 'Picklist' new_field[:type] = 'select' values = [] values.concat @field_picklists[element_name] new_field[:values] = values new_field[:value] = values[0] when 'object' end new_fields << new_field edit_field = new_field.clone edit_field[:value] = "{{#{record_sym}/#{element_name}}}" edit_fields << edit_field end # Show show_list = { :name => 'list', :type => 'list', :children => show_fields } show_form = { :name => "#{crm_object}_show", :type => 'show_form', :title => "#{crm_object} details", :object => "#{crm_object}", :model => "#{model_name}", :id => "{{#{record_sym}/object}}}", :children => [show_list] } # New new_list = show_list.clone new_list[:children] = new_fields new_form = { :type => 'new_form', :title => "New #{crm_object}", :object => "#{crm_object}", :model => "#{model_name}", :children => [new_list] } # Edit edit_list = show_list.clone edit_list[:children] = edit_fields edit_form = { :type => 'update_form', :title => "Edit #{crm_object}", :object => "#{crm_object}", :model => "#{model_name}", :id => "{{#{record_sym}/object}}", :children => [edit_list] } # Index title_field_metadata = @title_fields.collect { |field_name | "{{#{field_name.to_s}}} " }.join(' ') object_rec = { :object => "#{crm_object}", :id => "{{object}}", :type => 'linkobj', :text => "#{title_field_metadata}" } index_form = { :object => "#{crm_object}", :title => "#{crm_object.pluralize}", :type => 'index_form', :children => [object_rec], :repeatable => "{{#{record_sym.pluralize}}}" } # return JSON { 'index' => index_form, 'show' => show_form, 'new' => new_form, 'edit' => edit_form }.to_json end def sync # Manipulate @result before it is saved, or save it # yourself using the Rhoconnect::Store interface. # By default, super is called below which simply saves @result super end def create(create_hash) new_obj = get_module.new attributes = new_obj.attributes copy_keys_to_obj(create_hash, new_obj) new_obj.send 'assigned_user_id=', @namespace.current_user.id new_obj.send 'team_name=', get_user_team_name new_obj.send 'team_count=', '1' new_obj.save! new_obj.id end def update(update_hash) # step 1: get the id from the update hash result = get_module.find_by_id(update_hash['id']) copy_keys_to_obj(update_hash, result) result.save! update_hash['id'] end def delete(delete_hash) result = get_module.find_by_id(delete_hash['id']) result.delete delete_hash['id'] end def logoff end def get_module @namespace.const_get(crm_object) end def get_results(conditions) get_module.all(conditions) end def copy_keys_to_obj(source_hash, target) keys = source_hash.keys keys.each do |key| target.send key + '=', source_hash[key] end end def create_result_hash(results) ret_hash = {} if results.is_a?(Array) results_array = results else results_array = [results] end results_array.each do |result| attributes = result.attributes result_hash = {} fields.each do |element_name, element_def| value = attributes[element_name] if (value != nil && value.is_a?(Array) == false) result_hash[element_name] = value end end id = result.id ret_hash[id.to_s] = result_hash end ret_hash end end end end end
33.096774
141
0.533041
385a077532e4126bd09bece5714e2b80427a9951
1,880
class CoursesController < ApplicationController authorize_resource def new @course = Course.new end def create @course = Course.new(course_params) if @course.save redirect_to @course else render 'new' end end def show if Course.exists?(params[:id]) @course = Course.find(params[:id]) @first_option_candidature = Candidature.where("course1_id = ?", @course.id) @first_option_candidature = @first_option_candidature.select{|t| t.semester.open} @second_option_candidature = Candidature.where("course2_id = ?", @course.id) @second_option_candidature = @second_option_candidature.select{|t| t.semester.open} @third_option_candidature = Candidature.where("course3_id = ?", @course.id) @third_option_candidature = @third_option_candidature.select{|t| t.semester.open} @fourth_option_candidature = Candidature.where("course4_id = ?", @course.id) @fourth_option_candidature = @fourth_option_candidature.select{|t| t.semester.open} else redirect_to courses_path end end def index @courses = Course.all.order(:course_code) end def edit if Course.exists?(params[:id]) @course = Course.find(params[:id]) @course.course_code.sub!(Department.find_by(:id => @course.department_id).code, "") else redirect_to courses_path end end def update if not Course.exists? params[:id] # TODO alert failure redirect_to course_path return end @course = Course.find(params[:id]) if @course.update(course_params) redirect_to @course else render 'edit' end end def destroy @course = Course.find(params[:id]) @course.destroy redirect_to courses_path end private def course_params params.require(:course).permit(:name, :course_code, :department_id) end end
24.736842
89
0.681383
266ebfcfb2020e462927bd4309630e0a1df0a6b1
1,761
require_domain_file describe ManageIQ::Automate::Cloud::VM::Provisioning::Naming::VmName do let(:provision) { MiqProvision.new } let(:root_object) { Spec::Support::MiqAeMockObject.new.tap { |ro| ro["miq_provision"] = provision } } let(:service) { Spec::Support::MiqAeMockService.new(root_object).tap { |s| s.object = {'vm_prefix' => "abc"} } } let(:classification) { FactoryGirl.create(:classification, :tag => tag, :name => "environment") } let(:classification2) do FactoryGirl.create(:classification, :tag => tag2, :parent => classification, :name => "prod") end let(:tag) { FactoryGirl.create(:tag, :name => "/managed/environment") } let(:tag2) { FactoryGirl.create(:tag, :name => "/managed/environment/production") } context "#main" do it "no vm name from dialog" do provision.update_attributes(:options => {:number_of_vms => 200}) described_class.new(service).main expect(service.object['vmname']).to eq('abc$n{3}') end it "vm name from dialog" do provision.update_attributes(:options => {:number_of_vms => 200, :vm_name => "drew"}) described_class.new(service).main expect(service.object['vmname']).to eq('drew$n{3}') end it "use model and environment tag" do provision.update_attributes(:options => {:number_of_vms => 200, :vm_tags => [classification2.id]}) described_class.new(service).main expect(service.object['vmname']).to eq('abcpro$n{3}') end it "provisions single vm" do provision.update_attributes(:options => {:number_of_vms => 1}) described_class.new(service).main expect(service.object['vmname']).to eq('abc$n{3}') end end end
34.529412
114
0.637706
e91b0bf429178203ddd6a164d463686cad493822
3,045
class Zurl < Formula desc "HTTP and WebSocket client worker with ZeroMQ interface" homepage "https://github.com/fanout/zurl" url "https://dl.bintray.com/fanout/source/zurl-1.4.7.tar.bz2" sha256 "ffe8bb1268c62241050e8d57472a0877e1374db31e6777c5498693685770a90e" bottle do cellar :any sha256 "87d3d44429695a671cfbcc7e43cf6a12bde243df79ddd2f8bd595005b7a473fb" => :yosemite sha256 "365190727ac5dd5901fb2a02a37635a7b6a4e82a536845a4511c55d78b28ff21" => :mavericks sha256 "e1bbc70ee4a8aa687dd6c61e7b9fba5d6da2dc9092572eb03b314c8b4aafc448" => :mountain_lion end depends_on "pkg-config" => :build depends_on "curl" if MacOS.version < :lion depends_on "qt" depends_on "zeromq" depends_on "qjson" resource "pyzmq" do url "https://pypi.python.org/packages/source/p/pyzmq/pyzmq-14.6.0.tar.gz" sha256 "7746806ff94f1e8c1e843644c6bbd3b9aaeb1203c2eaf38879adc23dbd5c35bb" end def install system "./configure", "--prefix=#{prefix}" system "make" system "make", "install" end test do conffile = testpath/"zurl.conf" ipcfile = testpath/"zurl-req" runfile = testpath/"test.py" resource("pyzmq").stage { system "python", *Language::Python.setup_install_args(testpath/"vendor") } conffile.write(<<-EOS.undent [General] in_req_spec=ipc://#{ipcfile} defpolicy=allow timeout=10 EOS ) runfile.write(<<-EOS.undent import json import threading from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import zmq class TestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write('test response\\n') port = None def server_worker(c): global port server = HTTPServer(('', 0), TestHandler) port = server.server_address[1] c.acquire() c.notify() c.release() try: server.serve_forever() except: server.server_close() c = threading.Condition() c.acquire() server_thread = threading.Thread(target=server_worker, args=(c,)) server_thread.daemon = True server_thread.start() c.wait() c.release() ctx = zmq.Context() sock = ctx.socket(zmq.REQ) sock.connect('ipc://#{ipcfile}') req = {'id': '1', 'method': 'GET', 'uri': 'http://localhost:%d/test' % port} sock.send('J' + json.dumps(req)) poller = zmq.Poller() poller.register(sock, zmq.POLLIN) socks = dict(poller.poll(15000)) assert(socks.get(sock) == zmq.POLLIN) resp = json.loads(sock.recv()[1:]) assert('type' not in resp) assert(resp['body'] == 'test response\\n') EOS ) pid = fork do exec "#{bin}/zurl", "--config=#{conffile}" end begin ENV["PYTHONPATH"] = testpath/"vendor/lib/python2.7/site-packages" system "python", runfile ensure Process.kill("TERM", pid) Process.wait(pid) end end end
29.563107
104
0.643021
1d34f63a46835e185f28ed92195d0afb3a604dd4
58
# this is a comments # this is another comment ; ;
4.833333
25
0.603448
0151ca161ff10c69655c233d59d20a7a6ca99486
299
module YidunContentModeration class SyncVideosResultJob < ApplicationJob def perform # TODO 暂时只处理只有一个Application的场景 application = Application.first application.video_callback_results! if application.tasks.pending.where("created_at >= ?", 1.days.ago).first end end end
27.181818
113
0.752508
eda11575c6ccf615c028dccba27eac8f1d95a983
260
require "lita" Lita.load_locales Dir[File.expand_path( File.join("..", "..", "locales", "*.yml"), __FILE__ )] require "lita/handlers/lookup_host" Lita::Handlers::LookupHost.template_root File.expand_path( File.join("..", "..", "templates"), __FILE__ )
20
58
0.676923
91fb67d1d49660ac5bd8429c0304060b98f59e63
192
# db/migrate/02_add_favorite_food_to_artists.rb class AddFavoriteFoodToArtists < ActiveRecord::Migration[4.2] def change add_column :artists, :favorite_food, :string end end
21.333333
61
0.755208
1dfb2c8200d3dd019028fb70fba2037f8a5462ad
1,685
require_relative "helper" module Ruby class TestAssignmentRuby < MiniTest::Test include RubyTests def test_local lst = compile( "foo = bar") assert_equal LocalAssignment , lst.class end def test_local_name lst = compile( "foo = bar") assert_equal :foo , lst.name end def test_instance lst = compile( "@foo = bar") assert_equal IvarAssignment , lst.class end def test_instance_name lst = compile( "@foo = bar") assert_equal :foo , lst.name end def test_const lst = compile( "@foo = 5") assert_equal IvarAssignment , lst.class end end class TestAssignmentSolLocal < MiniTest::Test include RubyTests def setup @lst = compile( "foo = bar").to_sol end def test_tos assert_equal "foo = self.bar()" , @lst.to_s end def test_local assert_equal Sol::LocalAssignment , @lst.class end def test_bar assert_equal Sol::SendStatement , @lst.value.class end def test_local_name assert_equal :foo , @lst.name end end class TestAssignmentSolInst < MiniTest::Test include RubyTests def setup @lst = compile( "@foo = bar").to_sol end def test_tos assert_equal "@foo = self.bar()" , @lst.to_s end def test_instance assert_equal Sol::IvarAssignment , @lst.class end def test_instance_name assert_equal :foo , @lst.name end end class TestAssignmentSolConst < MiniTest::Test include RubyTests def setup @lst = compile( "foo = 5").to_sol end def test_const assert_equal Sol::IntegerConstant , @lst.value.class end end end
23.732394
58
0.640356
5dc84e29ad6f4e39eb3340724d3f45e89d09cd0a
801
# This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # Require this file using `require "spec_helper"` to ensure that it is only # loaded once. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration module Fixtures def fixture(name) File.join(File.dirname(__FILE__), 'fixtures', name) end end RSpec.configure do |config| config.run_all_when_everything_filtered = true config.filter_run :focus config.include Fixtures # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = 'random' end
30.807692
77
0.739076
6aa29082c4226ec559d00b3e94c57f45f73b2a4a
406
require_relative "./test_helper" require "text/porter_stemming" class PorterStemmingTest < Test::Unit::TestCase def test_cases inputs = data_file('porter_stemming_input.txt').split(/\n/) outputs = data_file('porter_stemming_output.txt').split(/\n/) inputs.zip(outputs).each do |word, expected_output| assert_equal expected_output, Text::PorterStemming.stem(word) end end end
25.375
67
0.738916
1de931287d05a3e377faeb4343b3980db390f9b3
1,053
# frozen_string_literal: true $LOAD_PATH.push File.expand_path('lib', __dir__) require_relative 'lib/apex_charts/version' Gem::Specification.new do |spec| spec.name = 'apexcharts' spec.version = ApexCharts::VERSION spec.authors = ['Adrian Setyadi'] spec.email = ['[email protected]'] spec.homepage = 'https://github.com/styd/apexcharts.rb' spec.summary = 'Awesome charts for your ruby app' spec.description = 'Create beautiful, interactive, and responsive web charts in ' \ 'ruby app powered by apexcharts.js.' spec.license = 'MIT' spec.files = Dir['{lib,vendor}/**/*', 'LICENSE', 'README.md'] spec.add_dependency 'smart_kv', '~> 0.2.8' spec.add_dependency 'dry-schema', '~> 1.5' spec.add_development_dependency 'bundler' spec.add_development_dependency 'nokogiri' spec.add_development_dependency 'pry' spec.add_development_dependency 'rake' spec.add_development_dependency 'rspec' spec.add_development_dependency 'rubocop' spec.add_development_dependency 'simplecov' end
32.90625
68
0.716049
0854be9b8ce5fe2310f49d95acd21e093e221a6d
2,169
require 'rest-client' require 'nokogiri' require_relative '../sentry_helper' require_relative './base_clinic' module HeywoodHealthcare SIGN_UP_URL = 'https://gardnervaccinations.as.me/schedule.php'.freeze API_URL = 'https://gardnervaccinations.as.me/schedule.php?action=showCalendar&fulldate=1&owner=21588707&template=class'.freeze SITE_NAME = 'Heywood Healthcare in Gardner, MA'.freeze def self.all_clinics(storage, logger) SentryHelper.catch_errors(logger, 'HeywoodHealthcare') do logger.info '[HeywoodHealthcare] Checking site' unless appointments? logger.info '[HeywoodHealthcare] No appointments available' return [] end fetch_appointments.map do |date, appointments| logger.info "[HeywoodHealthcare] Found #{appointments} appointments on #{date}" Clinic.new(storage, SITE_NAME, date, appointments, SIGN_UP_URL) end end end def self.appointments? res = RestClient.get(SIGN_UP_URL) if /There are no appointment types available for scheduling/ =~ res false else true end end def self.fetch_appointments res = RestClient.post( API_URL, { 'type' => '', 'calendar' => '', 'skip' => true, 'options[qty]' => 1, 'options[numDays]' => 27, 'ignoreAppointment' => '', 'appointmentType' => '', 'calendarID' => '', } ) html = Nokogiri::HTML(res.body) html.search('.class-signup-container').each_with_object(Hash.new(0)) do |row, h| link = row.search('a.btn-class-signup') next unless link.any? date = Date.parse(link[0]['data-readable-date']).strftime('%m/%d/%Y') row.search('.num-slots-available-container .babel-ignore').each do |appointments| h[date] += appointments.text.to_i end end end class Clinic < BaseClinic attr_reader :name, :date, :appointments, :link def initialize(storage, name, date, appointments, link) super(storage) @name = name @date = date @appointments = appointments @link = link end def title "#{name} on #{date}" end end end
27.807692
128
0.640848
bbb520bb8650cd29aee45c0b8cf8538b21720e1d
1,073
class Encounter < Entry field :admitType, as: :admit_type, type: Hash field :dischargeDisposition, as: :discharge_disposition, type: Hash field :admitTime, as: :admit_time, type: Integer field :dischargeTime, as: :discharge_time, type: Integer field :principalDiagnosis, as: :principal_diagnosis, type: Hash field :diagnosis, type: Hash embeds_one :transferTo, class_name: "Transfer" embeds_one :transferFrom, class_name: "Transfer" embeds_one :facility, class_name: "HealthDataStandards::Facility" embeds_one :reason, class_name: "Entry" belongs_to :performer, class_name: "HealthDataStandards::Provider" alias :transfer_to :transferTo alias :transfer_to= :transferTo= alias :transfer_from :transferFrom alias :transfer_from= :transferFrom= def shift_dates(date_diff) super if self.facility self.facility.shift_dates(date_diff) end self.admitTime = (self.admitTime.nil?) ? nil : self.admitTime + date_diff self.dischargeTime = (self.dischargeTime.nil?) ? nil : self.dischargeTime + date_diff end end
33.53125
89
0.745573
5dc3f960e38fd424d4a19e3708253245855f5a16
844
require "jwt" module AuthToken # More information on jwt available at # http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#rfc.section.4.1.6 def self.issue_token(payload, exp = 24.hours.from_now, secret = nil, aud = nil, header_fields = {}) payload["iat"] = DateTime.now.to_i # issued at claim payload["exp"] = exp.to_i # Default expiration set to 24 hours. payload["aud"] = aud || Rails.application.secrets.auth0_client_id JWT.encode( payload, secret || Rails.application.secrets.auth0_client_secret, "HS512", header_fields, ) end def self.valid?(token, secret = nil) decode(token, secret, true) end def self.decode(token, secret, validate = true) JWT.decode(token, secret || Rails.application.secrets.auth0_client_secret, validate) end end
31.259259
101
0.680095
08383dc48cce18efdcea6af672f1a34eab102e5a
875
class Mas < Formula desc "Mac App Store command-line interface" homepage "https://github.com/mas-cli/mas" url "https://github.com/mas-cli/mas/archive/v1.4.1.tar.gz" sha256 "4fd91c13b46d403b52dbee3891adb3cd6571e07ad20cf58de0100c9f695e6c24" head "https://github.com/mas-cli/mas.git" bottle do cellar :any_skip_relocation sha256 "b7585ced3a93d60e95357e93d729913a6f628fda82359e77c6553c2e802c50dc" => :high_sierra sha256 "af5be6aa9902d9cfc2aa69dbf313441a7c201463d516face721f900ceae9556b" => :sierra end depends_on :xcode => ["9.0", :build] def install xcodebuild "-project", "mas-cli.xcodeproj", "-scheme", "mas-cli Release", "-configuration", "Release", "SYMROOT=build" bin.install "build/mas" end test do assert_equal version.to_s, shell_output("#{bin}/mas version").chomp end end
31.25
93
0.705143
913cce3096852546c7ef88693366fdf0dd6346f7
2,592
require 'spec_helper' describe "configuration" do let(:config) { Geolocal.configuration } it "has the right defaults" do # reset the configuration so we get the default configuration, # not the test configuration that the spec_helper has set up. Geolocal.reset_configuration defaults = Geolocal.configuration # these need to match the description in the readme expect(defaults.provider).to eq 'Geolocal::Provider::DB_IP' expect(defaults.module).to eq 'Geolocal' expect(defaults.file).to eq 'lib/geolocal.rb' expect(defaults.tmpdir).to eq 'tmp/geolocal' expect(defaults.ipv4).to eq true expect(defaults.ipv6).to eq true expect(defaults.quiet).to eq false expect(defaults.countries).to eq({}) end describe "reset method" do before :each do Geolocal.configure do |conf| conf.module = "Changed" end end it "resets the configuration" do expect(Geolocal.configuration.module).to eq "Changed" Geolocal.reset_configuration expect(Geolocal.configuration.module).to eq "Geolocal" end end describe "module names" do it "can handle typical module names" do module_name = "GeoRangeFinderID::QuickLook" Geolocal.configure do |g| g.module = module_name end expect(config.module).to eq module_name expect(config.file).to eq "lib/geo_range_finder_id/quick_look.rb" end it "can handle a pathological module name" do module_name = "Geolocal::Provider::DB_IP" Geolocal.configure do |g| g.module = module_name end expect(config.module).to eq module_name expect(config.file).to eq "lib/geolocal/provider/db_ip.rb" end end describe "to_hash" do it "can do the conversion" do expect(config.to_hash).to eq({ provider: 'Geolocal::Provider::DB_IP', module: 'Geolocal', file: 'lib/geolocal.rb', tmpdir: 'tmp/geolocal', ipv4: true, ipv6: true, quiet: true, countries: {} }) end end describe "module paths" do it "includes the correct provider when running as a gem" do expect(Kernel).to receive(:require).with('geolocal/provider/db_ip') config.require_provider_file end it "includes the correct provider when running locally" do expect(Kernel).to receive(:require).with('geolocal/provider/db_ip') { raise LoadError } expect(Kernel).to receive(:require).with('./lib/geolocal/provider/db_ip.rb') config.require_provider_file end end end
28.173913
93
0.667052
1df2dfe0c9e796336730a563ac51f3fcd274f739
993
# -*- encoding: utf-8 -*- # stub: naught 1.1.0 ruby lib Gem::Specification.new do |s| s.name = "naught" s.version = "1.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Avdi Grimm"] s.date = "2015-09-08" s.description = "Naught is a toolkit for building Null Objects" s.email = ["[email protected]"] s.homepage = "https://github.com/avdi/naught" s.licenses = ["MIT"] s.rubygems_version = "2.4.8" s.summary = "Naught is a toolkit for building Null Objects" s.installed_by_version = "2.4.8" 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_development_dependency(%q<bundler>, ["~> 1.3"]) else s.add_dependency(%q<bundler>, ["~> 1.3"]) end else s.add_dependency(%q<bundler>, ["~> 1.3"]) end end
30.090909
105
0.654582
e8181a5999021b12f8026acdbf2f858aec4698d4
1,480
# frozen_string_literal: true module Logux module Process class Batch attr_reader :stream, :batch def initialize(stream:, batch:) @stream = stream @batch = batch end def call last_chunk = batch.size - 1 preprocessed_batch.map.with_index do |chunk, index| case chunk[:type] when :action process_action(chunk: chunk.slice(:action, :meta)) when :auth process_auth(chunk: chunk[:auth]) end stream.write(',') if index != last_chunk end end def process_action(chunk:) Logux::Process::Action.new(stream: stream, chunk: chunk).call end def process_auth(chunk:) Logux::Process::Auth.new(stream: stream, chunk: chunk).call end def preprocessed_batch @preprocessed_batch ||= batch.map do |chunk| case chunk[0] when 'action' preprocess_action(chunk) when 'auth' preprocess_auth(chunk) end end end def preprocess_action(chunk) { type: :action, action: Logux::Actions.new(chunk[1]), meta: Logux::Meta.new(chunk[2]) } end def preprocess_auth(chunk) { type: :auth, auth: Logux::Auth.new(node_id: chunk[1], credentials: chunk[2], auth_id: chunk[3]) } end end end end
24.666667
69
0.537162
1dbebfe125b40cd58056332aa9bc1d173709bb76
857
# frozen_string_literal: true # require 'rails/generators/base' # require 'securerandom' module OidcProvider class InstallGenerator < Rails::Generators::Base source_root File.expand_path('templates', __dir__) desc "Creates a OIDCProvider initializer." def copy_initializer_file copy_file "initializer.rb", "config/initializers/oidc_provider.rb" end def setup_routes route "get '/.well-known/:id', to: 'oidc_provider/discovery#show'" route "mount OIDCProvider::Engine, at: '/accounts/oauth'" end # def copy_locale # copy_file "../../../config/locales/en.yml", "config/locales/devise.en.yml" # end # def show_readme # readme "README" if behavior == :invoke # end # def rails_4? # Rails::VERSION::MAJOR == 4 # end end end
23.805556
84
0.635939
79643c70f3aef05b9e2a2805ab249ee5585e824f
13,174
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20150812163030) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" enable_extension "hstore" create_table "accounts", force: :cascade do |t| t.string "first_name", limit: 40 t.string "last_name", limit: 40 t.string "email", limit: 100 t.string "hashed_password", limit: 255 t.datetime "created_at" t.datetime "updated_at" t.hstore "identities" t.string "language", limit: 3, default: "eng" t.string "document_language", limit: 3, default: "eng" end add_index "accounts", ["email"], name: "index_accounts_on_email", unique: true, using: :btree add_index "accounts", ["identities"], name: "index_accounts_on_identites", using: :gin create_table "annotations", force: :cascade do |t| t.integer "organization_id", null: false t.integer "account_id", null: false t.integer "document_id", null: false t.integer "page_number", null: false t.integer "access", null: false t.text "title", null: false t.text "content" t.string "location", limit: 40 t.datetime "created_at" t.datetime "updated_at" t.boolean "moderation_approval" end add_index "annotations", ["document_id"], name: "index_annotations_on_document_id", using: :btree create_table "app_constants", force: :cascade do |t| t.string "key", limit: 255 t.string "value", limit: 255 end create_table "collaborations", force: :cascade do |t| t.integer "project_id", null: false t.integer "account_id", null: false t.integer "creator_id" end create_table "docdata", force: :cascade do |t| t.integer "document_id", null: false t.hstore "data" end add_index "docdata", ["data"], name: "index_docdata_on_data", using: :gin create_table "document_reviewers", force: :cascade do |t| t.integer "account_id", null: false t.integer "document_id", null: false t.datetime "created_at" t.datetime "updated_at" end create_table "documents", force: :cascade do |t| t.integer "organization_id", null: false t.integer "account_id", null: false t.integer "access", null: false t.integer "page_count", default: 0, null: false t.string "title", limit: 1000, null: false t.string "slug", limit: 255, null: false t.string "source", limit: 1000 t.string "language", limit: 3 t.text "description" t.string "calais_id", limit: 40 t.date "publication_date" t.datetime "created_at" t.datetime "updated_at" t.text "related_article" t.text "detected_remote_url" t.text "remote_url" t.datetime "publish_at" t.boolean "text_changed", default: false, null: false t.integer "hit_count", default: 0, null: false t.integer "public_note_count", default: 0, null: false t.integer "reviewer_count", default: 0, null: false t.integer "file_size", default: 0, null: false t.integer "char_count", default: 0, null: false t.string "original_extension", limit: 255 t.text "file_hash" end add_index "documents", ["access"], name: "index_documents_on_access", using: :btree add_index "documents", ["account_id"], name: "index_documents_on_account_id", using: :btree add_index "documents", ["file_hash"], name: "index_documents_on_file_hash", using: :btree add_index "documents", ["hit_count"], name: "index_documents_on_hit_count", using: :btree add_index "documents", ["public_note_count"], name: "index_documents_on_public_note_count", using: :btree create_table "entities", force: :cascade do |t| t.integer "organization_id", null: false t.integer "account_id", null: false t.integer "document_id", null: false t.integer "access", null: false t.string "kind", limit: 40, null: false t.string "value", limit: 255, null: false t.float "relevance", default: 0.0, null: false t.string "calais_id", limit: 40 t.text "occurrences" end add_index "entities", ["document_id"], name: "index_metadata_on_document_id", using: :btree add_index "entities", ["kind"], name: "index_metadata_on_kind", using: :btree create_table "entity_dates", force: :cascade do |t| t.integer "organization_id", null: false t.integer "account_id", null: false t.integer "document_id", null: false t.integer "access", null: false t.date "date", null: false t.text "occurrences" end add_index "entity_dates", ["document_id", "date"], name: "index_metadata_dates_on_document_id_and_date", unique: true, using: :btree create_table "featured_reports", force: :cascade do |t| t.string "url", limit: 255, null: false t.string "title", limit: 255, null: false t.string "organization", limit: 255, null: false t.date "article_date", null: false t.text "writeup", null: false t.integer "present_order", default: 0 t.datetime "created_at" t.datetime "updated_at" end create_table "memberships", force: :cascade do |t| t.integer "organization_id", null: false t.integer "account_id", null: false t.integer "role", null: false t.boolean "default", default: false t.boolean "concealed", default: false end add_index "memberships", ["account_id"], name: "index_memberships_on_account_id", using: :btree add_index "memberships", ["organization_id"], name: "index_memberships_on_organization_id", using: :btree create_table "organizations", force: :cascade do |t| t.string "name", limit: 100, null: false t.string "slug", limit: 100, null: false t.datetime "created_at" t.datetime "updated_at" t.boolean "demo", default: false, null: false t.string "language", limit: 3 t.string "document_language", limit: 3 end add_index "organizations", ["name"], name: "index_organizations_on_name", unique: true, using: :btree add_index "organizations", ["slug"], name: "index_organizations_on_slug", unique: true, using: :btree create_table "pages", force: :cascade do |t| t.integer "organization_id", null: false t.integer "account_id", null: false t.integer "document_id", null: false t.integer "access", null: false t.integer "page_number", null: false t.text "text", null: false t.integer "start_offset" t.integer "end_offset" end add_index "pages", ["document_id"], name: "index_pages_on_document_id", using: :btree add_index "pages", ["page_number"], name: "index_pages_on_page_number", using: :btree add_index "pages", ["start_offset", "end_offset"], name: "index_pages_on_start_offset_and_end_offset", using: :btree create_table "pending_memberships", force: :cascade do |t| t.string "first_name", limit: 255, null: false t.string "last_name", limit: 255, null: false t.string "email", limit: 255, null: false t.string "organization_name", limit: 255, null: false t.string "usage", limit: 255, null: false t.string "editor", limit: 255 t.string "website", limit: 255 t.boolean "validated", default: false, null: false t.text "notes" t.integer "organization_id" t.hstore "fields" t.datetime "created_at" t.datetime "updated_at" end create_table "processing_jobs", force: :cascade do |t| t.integer "account_id", null: false t.integer "cloud_crowd_id", null: false t.string "title", limit: 255, null: false t.integer "document_id" t.string "action" t.string "options" t.boolean "complete", default: false end add_index "processing_jobs", ["account_id"], name: "index_processing_jobs_on_account_id", using: :btree add_index "processing_jobs", ["action"], name: "index_processing_jobs_on_action", using: :btree add_index "processing_jobs", ["cloud_crowd_id"], name: "index_processing_jobs_on_cloud_crowd_id", using: :btree add_index "processing_jobs", ["document_id"], name: "index_processing_jobs_on_document_id", using: :btree create_table "project_memberships", force: :cascade do |t| t.integer "project_id", null: false t.integer "document_id", null: false end add_index "project_memberships", ["document_id"], name: "index_project_memberships_on_document_id", using: :btree add_index "project_memberships", ["project_id"], name: "index_project_memberships_on_project_id", using: :btree create_table "projects", force: :cascade do |t| t.integer "account_id" t.string "title", limit: 255 t.text "description" t.boolean "hidden", default: false, null: false end add_index "projects", ["account_id"], name: "index_labels_on_account_id", using: :btree create_table "remote_urls", force: :cascade do |t| t.integer "document_id", null: false t.string "url", limit: 255, null: false t.integer "hits", default: 0, null: false end create_table "sections", force: :cascade do |t| t.integer "organization_id", null: false t.integer "account_id", null: false t.integer "document_id", null: false t.text "title", null: false t.integer "page_number", null: false t.integer "access", null: false end add_index "sections", ["document_id"], name: "index_sections_on_document_id", using: :btree create_table "security_keys", force: :cascade do |t| t.string "securable_type", limit: 40, null: false t.integer "securable_id", null: false t.string "key", limit: 40 end create_table "verification_requests", force: :cascade do |t| t.datetime "created_at" t.datetime "updated_at" t.string "requester_email", limit: 255, null: false t.string "requester_first_name", limit: 255, null: false t.string "requester_last_name", limit: 255, null: false t.text "requester_notes" t.string "organization_name", limit: 255, null: false t.string "organization_url", limit: 255 t.string "approver_email", limit: 255, null: false t.string "approver_first_name", limit: 255, null: false t.string "approver_last_name", limit: 255, null: false t.string "country", limit: 255, null: false t.text "verification_notes" t.integer "status", default: 1, null: false t.boolean "agreed_to_terms", default: false, null: false t.boolean "authorized_posting", default: false, null: false t.string "signup_key", limit: 255 t.integer "account_id" t.string "industry" t.text "use_case" t.text "reference_links" t.boolean "marketing_optin", default: false t.boolean "in_market", default: false t.string "requester_position" end end
46.224561
134
0.596326
08986839ca2fc8805b99cc2b05fd08aa3555e7d9
1,786
module Raddocs # Configure Raddocs # @see Raddocs.configure Raddocs.configure # @example # Raddocs.configure do |config| # # config is this class # config.api_name = "My API" # end class Configuration # Configures a new setting, creates two methods # # @param name [Symbol] name of the setting # @param opts [Hash] # @option opts [Object] default default value of setting def self.add_setting(name, opts = {}) define_method("#{name}=") { |value| settings[name] = value } define_method("#{name}") do if settings.has_key?(name) settings[name] elsif opts[:default].respond_to?(:call) opts[:default].call(self) else opts[:default] end end end # @!attribute docs_dir # @return [String] defaults to 'doc/api' add_setting :docs_dir, :default => "doc/api" # @!attribute guides_dir # @return [String] defaults to 'doc/guides' add_setting :guides_dir, :default => "doc/guides" # @!attribute docs_mime_type # @return [Regexp] defaults to Regexp.new("text/docs\+plain") add_setting :docs_mime_type, :default => /text\/docs\+plain/ # @!attribute api_name # @return [String] defaults to "Api Documentation" add_setting :api_name, :default => "Api Documentation" # @!attribute include_bootstrap # @return [Boolean] defaults to true add_setting :include_bootstrap, :default => true # @!attribute external_css # @return [Array] array of Strings, defaults to [] add_setting :external_css, :default => [] # @!attribute url_prefix # @return [String] defaults to nil add_setting :url_prefix, :default => nil private def settings @settings ||= {} end end end
28.349206
66
0.632139
d51fca4568e3b7e065f349f230406a4848a6a06a
606
class TagsController < ApplicationController def show @tag = Tag.where(id: params[:id]).to_a[0] @blogposts = @tag.blogposts.paginate(:page => params[:page]) end def index @tags = Tag.order("name") end def search @tags = "" @results = [] end def find @tags = params[:tags] #TODO: use database operations to make this search faster (a LOT faster) tag_array = @tags.split(/\s*,\s*/) @results = Blogpost.all.delete_if {|p| !(tag_array-p.taglist).empty?} if @results.empty? flash.now[:notice] = "There are no posts with that combination of tags" end render 'search' end end
25.25
74
0.669967
395eddf61ff062ebd857025f692058beea89fcab
949
require "serverspec" set :backend, :exec describe "Redis client installation" do describe package("redis-tools") do it { should be_installed } end end describe "Redis server installation" do describe package("redis-server") do it { should be_installed } end describe file("/var/lib/redis") do it { should be_a_directory } it { should be_owned_by "redis" } it { should be_grouped_into "redis" } it { should be_mode 750 } end describe service("redis-server") do it { should be_enabled } it { should be_running } end describe file("/etc/redis/redis.conf") do it { should be_a_file } it { should be_owned_by "root" } it { should be_grouped_into "root" } it { should be_mode 644 } end describe file("/etc/default/redis-server") do it { should be_a_file } it { should be_owned_by "root" } it { should be_grouped_into "root" } it { should be_mode 644 } end end
22.595238
47
0.667018
ed3aa26505b1005ce863232fb15f827f3ad1462f
3,311
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2011, Google Inc. All Rights Reserved. # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # This example creates new ad units under a the effective root ad unit. To # determine which ad units exist, run get_inventory_tree.rb or # get_all_ad_units.rb. require 'securerandom' require 'ad_manager_api' def create_ad_units(ad_manager, number_of_ad_units_to_create) # Get the InventoryService and the NetworkService. inventory_service = ad_manager.service(:InventoryService, API_VERSION) network_service = ad_manager.service(:NetworkService, API_VERSION) # Get the effective root ad unit ID of the network. effective_root_ad_unit_id = network_service.get_current_network[:effective_root_ad_unit_id] puts 'Using effective root ad unit: %d' % effective_root_ad_unit_id # Create the creative placeholder. creative_placeholder = { :size => {:width => 300, :height => 250, :is_aspect_ratio => false}, :environment_type => 'BROWSER' } # Create an array to store local ad unit objects. ad_units = (1..number_of_ad_units_to_create).map do |index| { :name => 'Ad_Unit #%d - %s' % [index, SecureRandom.uuid()], :parent_id => effective_root_ad_unit_id, :description => 'Ad unit description.', :target_window => 'BLANK', # Set the size of possible creatives that can match this ad unit. :ad_unit_sizes => [creative_placeholder] } end # Create the ad units on the server. created_ad_units = inventory_service.create_ad_units(ad_units) if created_ad_units.to_a.size > 0 created_ad_units.each do |ad_unit| puts 'Ad unit with ID %d, name "%s", and status "%s" was created.' % [ad_unit[:id], ad_unit[:name], ad_unit[:status]] end else puts 'No ad units were created.' end end if __FILE__ == $0 API_VERSION = :v202011 # Get AdManagerApi instance and load configuration from ~/ad_manager_api.yml. ad_manager = AdManagerApi::Api.new # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in # the configuration file or provide your own logger: # ad_manager.logger = Logger.new('ad_manager_xml.log') begin number_of_ad_units_to_create = 5 create_ad_units(ad_manager, number_of_ad_units_to_create) # HTTP errors. rescue AdsCommon::Errors::HttpError => e puts "HTTP Error: %s" % e # API errors. rescue AdManagerApi::Errors::ApiException => e puts "Message: %s" % e.message puts 'Errors:' e.errors.each_with_index do |error, index| puts "\tError [%d]:" % (index + 1) error.each do |field, value| puts "\t\t%s: %s" % [field, value] end end end end
33.785714
79
0.691332
6afa3541b16db860ec3504103b33c8bbbaef39b3
11,734
# frozen_string_literal: true RSpec.shared_context 'mock swagger example' do before :all do module Entities class Something < OpenStruct class << self # Representable doesn't have documentation method, mock this def documentation { id: { type: Integer, desc: 'Identity of Something' }, text: { type: String, desc: 'Content of something.' }, links: { type: 'link', is_array: true }, others: { type: 'text', is_array: false } } end end end class UseResponse < OpenStruct class << self def documentation { :description => { type: String }, '$responses' => { is_array: true } } end end end class ResponseItem < OpenStruct class << self def documentation { id: { type: Integer }, name: { type: String } } end end end class UseNestedWithAddress < OpenStruct; end class TypedDefinition < OpenStruct; end class UseItemResponseAsType < OpenStruct; end class OtherItem < OpenStruct; end class EnumValues < OpenStruct; end class AliasedThing < OpenStruct; end class FourthLevel < OpenStruct; end class ThirdLevel < OpenStruct; end class SecondLevel < OpenStruct; end class FirstLevel < OpenStruct; end class QueryInputElement < OpenStruct; end class QueryInput < OpenStruct; end class ApiError < OpenStruct; end class SecondApiError < OpenStruct; end class RecursiveModel < OpenStruct; end class DocumentedHashAndArrayModel < OpenStruct; end module NestedModule class ApiResponse < OpenStruct; end end end end let(:swagger_definitions_models) do { 'ApiError' => { 'type' => 'object', 'properties' => { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } } }, 'RecursiveModel' => { 'type' => 'object', 'properties' => { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } } }, 'UseResponse' => { 'type' => 'object', 'properties' => { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } } }, 'DocumentedHashAndArrayModel' => { 'type' => 'object', 'properties' => { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } } } } end let(:swagger_nested_type) do { 'ApiError' => { 'type' => 'object', 'properties' => { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } }, 'description' => 'This returns something' }, 'UseItemResponseAsType' => { 'type' => 'object', 'properties' => { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } }, 'description' => 'This returns something' } } end let(:swagger_entity_as_response_object) do { 'UseResponse' => { 'type' => 'object', 'properties' => { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } }, 'description' => 'This returns something' }, 'ApiError' => { 'type' => 'object', 'properties' => { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } }, 'description' => 'This returns something' } } end let(:swagger_params_as_response_object) do { 'ApiError' => { 'type' => 'object', 'properties' => { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } }, 'description' => 'This returns something' } } end let(:swagger_typed_defintion) do { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } } end let(:swagger_json) do { 'info' => { 'title' => 'The API title to be displayed on the API homepage.', 'description' => 'A description of the API.', 'termsOfServiceUrl' => 'www.The-URL-of-the-terms-and-service.com', 'contact' => { 'name' => 'Contact name', 'email' => '[email protected]', 'url' => 'Contact URL' }, 'license' => { 'name' => 'The name of the license.', 'url' => 'www.The-URL-of-the-license.org' }, 'version' => '0.0.1' }, 'swagger' => '2.0', 'produces' => ['application/json'], 'host' => 'example.org', 'basePath' => '/api', 'tags' => [ { 'name' => 'other_thing', 'description' => 'Operations about other_things' }, { 'name' => 'thing', 'description' => 'Operations about things' }, { 'name' => 'thing2', 'description' => 'Operations about thing2s' }, { 'name' => 'dummy', 'description' => 'Operations about dummies' } ], 'paths' => { '/v3/other_thing/{elements}' => { 'get' => { 'description' => 'nested route inside namespace', 'produces' => ['application/json'], 'parameters' => [{ 'in' => 'body', 'name' => 'elements', 'description' => 'Set of configuration', 'type' => 'array', 'items' => { 'type' => 'string' }, 'required' => true }], 'responses' => { '200' => { 'description' => 'nested route inside namespace', 'schema' => { '$ref' => '#/definitions/QueryInput' } } }, 'tags' => ['other_thing'], 'operationId' => 'getV3OtherThingElements', 'x-amazon-apigateway-auth' => { 'type' => 'none' }, 'x-amazon-apigateway-integration' => { 'type' => 'aws', 'uri' => 'foo_bar_uri', 'httpMethod' => 'get' } } }, '/thing' => { 'get' => { 'description' => 'This gets Things.', 'produces' => ['application/json'], 'parameters' => [ { 'in' => 'query', 'name' => 'id', 'description' => 'Identity of Something', 'type' => 'integer', 'format' => 'int32', 'required' => false }, { 'in' => 'query', 'name' => 'text', 'description' => 'Content of something.', 'type' => 'string', 'required' => false }, { 'in' => 'formData', 'name' => 'links', 'type' => 'array', 'items' => { 'type' => 'link' }, 'required' => false }, { 'in' => 'query', 'name' => 'others', 'type' => 'text', 'required' => false } ], 'responses' => { '200' => { 'description' => 'This gets Things.' }, '401' => { 'description' => 'Unauthorized', 'schema' => { '$ref' => '#/definitions/ApiError' } } }, 'tags' => ['thing'], 'operationId' => 'getThing' }, 'post' => { 'description' => 'This creates Thing.', 'produces' => ['application/json'], 'consumes' => ['application/json'], 'parameters' => [ { 'in' => 'formData', 'name' => 'text', 'description' => 'Content of something.', 'type' => 'string', 'required' => true }, { 'in' => 'formData', 'name' => 'links', 'type' => 'array', 'items' => { 'type' => 'string' }, 'required' => true } ], 'responses' => { '201' => { 'description' => 'This creates Thing.', 'schema' => { '$ref' => '#/definitions/Something' } }, '422' => { 'description' => 'Unprocessible Entity' } }, 'tags' => ['thing'], 'operationId' => 'postThing' } }, '/thing/{id}' => { 'get' => { 'description' => 'This gets Thing.', 'produces' => ['application/json'], 'parameters' => [{ 'in' => 'path', 'name' => 'id', 'type' => 'integer', 'format' => 'int32', 'required' => true }], 'responses' => { '200' => { 'description' => 'getting a single thing' }, '401' => { 'description' => 'Unauthorized' } }, 'tags' => ['thing'], 'operationId' => 'getThingId' }, 'put' => { 'description' => 'This updates Thing.', 'produces' => ['application/json'], 'consumes' => ['application/json'], 'parameters' => [ { 'in' => 'path', 'name' => 'id', 'type' => 'integer', 'format' => 'int32', 'required' => true }, { 'in' => 'formData', 'name' => 'text', 'description' => 'Content of something.', 'type' => 'string', 'required' => false }, { 'in' => 'formData', 'name' => 'links', 'type' => 'array', 'items' => { 'type' => 'string' }, 'required' => false } ], 'responses' => { '200' => { 'description' => 'This updates Thing.', 'schema' => { '$ref' => '#/definitions/Something' } } }, 'tags' => ['thing'], 'operationId' => 'putThingId' }, 'delete' => { 'description' => 'This deletes Thing.', 'produces' => ['application/json'], 'parameters' => [{ 'in' => 'path', 'name' => 'id', 'type' => 'integer', 'format' => 'int32', 'required' => true }], 'responses' => { '200' => { 'description' => 'This deletes Thing.', 'schema' => { '$ref' => '#/definitions/Something' } } }, 'tags' => ['thing'], 'operationId' => 'deleteThingId' } }, '/thing2' => { 'get' => { 'description' => 'This gets Things.', 'produces' => ['application/json'], 'responses' => { '200' => { 'description' => 'get Horses', 'schema' => { '$ref' => '#/definitions/Something' } }, '401' => { 'description' => 'HorsesOutError', 'schema' => { '$ref' => '#/definitions/ApiError' } } }, 'tags' => ['thing2'], 'operationId' => 'getThing2' } }, '/dummy/{id}' => { 'delete' => { 'description' => 'dummy route.', 'produces' => ['application/json'], 'parameters' => [{ 'in' => 'path', 'name' => 'id', 'type' => 'integer', 'format' => 'int32', 'required' => true }], 'responses' => { '204' => { 'description' => 'dummy route.' }, '401' => { 'description' => 'Unauthorized' } }, 'tags' => ['dummy'], 'operationId' => 'deleteDummyId' } } }, 'definitions' => { 'QueryInput' => { 'type' => 'object', 'properties' => { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } }, 'description' => 'nested route inside namespace' }, 'ApiError' => { 'type' => 'object', 'properties' => { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } }, 'description' => 'This gets Things.' }, 'Something' => { 'type' => 'object', 'properties' => { 'mock_data' => { 'type' => 'string', 'description' => "it's a mock" } }, 'description' => 'This gets Things.' } } } end let(:http_verbs) { %w[get post put delete] } end def mounted_paths %w[/thing /other_thing /dummy] end
35.450151
227
0.453042
abeb302b8c4b03acd845885ff86a0aebfc4bc02f
119
class AddUsersToProjects < ActiveRecord::Migration def change add_column :projects, :user_id, :integer end end
19.833333
50
0.764706
1db5591cb3a0d551c6224d54b8d861317e9a1898
1,812
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.default_url_options = {host: 'localhost:3000'} # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # For Mailcatcher config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = {address: 'localhost', port: 1025} end
38.553191
85
0.773731
1ca1fe15495dfe774f46944728ece602468a4034
748
require 'cloud_controller/structured_error' class HttpResponseError < StructuredError attr_reader :uri, :method, :status, :response def initialize(message, method, response) @method = method.to_s.upcase @response = response @status = response.code.to_i begin source = MultiJson.load(response.body) rescue ArgumentError # Either Oj should raise Oj::ParseError instead of ArgumentError, or MultiJson should also wrap # ArgumentError into MultiJson::Adapters::Oj::ParseError rescue MultiJson::ParseError source = response.body end super(message, source) end def to_h hash = super hash['http'] = { 'method' => method, 'status' => status, } hash end end
23.375
101
0.679144
629c4a57a6a5ac1eb430121579d59c185740d899
1,899
class TwitterService class Error < Exception ; end extend Memoist def enabled? Danbooru.config.twitter_api_key.present? && Danbooru.config.twitter_api_secret.present? end def client raise Error, "Twitter API keys not set" if !enabled? rest_client = ::Twitter::REST::Client.new do |config| config.consumer_key = Danbooru.config.twitter_api_key config.consumer_secret = Danbooru.config.twitter_api_secret if bearer_token = Cache.get("twitter-api-token") config.bearer_token = bearer_token end end Cache.put("twitter-api-token", rest_client.bearer_token) rest_client end memoize :client def status(id, options = {}) Cache.get("twitterapi:#{id}", 60) do client.status(id, options) end end def extract_urls_for_status(tweet) tweet.media.map do |obj| if obj.is_a?(Twitter::Media::Photo) obj.media_url_https.to_s + ":orig" elsif obj.is_a?(Twitter::Media::Video) video = obj.video_info.variants.select do |x| x.content_type == "video/mp4" end.max_by {|y| y.bitrate} if video video.url.to_s end end end.compact.uniq end def extract_og_image_from_page(url) resp = HTTParty.get(url, Danbooru.config.httparty_options) if resp.success? doc = Nokogiri::HTML(resp.body) images = doc.css("meta[property='og:image']") return images.first.attr("content").sub(":large", ":orig") end end def extract_urls_for_card(attrs) urls = attrs.urls.map {|x| x.expanded_url} url = urls.reject {|x| x.host == "twitter.com"}.first if url.nil? url = urls.first end [extract_og_image_from_page(url)].compact end def image_urls(tweet) if tweet.media.any? extract_urls_for_status(tweet) elsif tweet.urls.any? extract_urls_for_card(tweet) end end end
26.013699
91
0.658768
281654cab9a4799a15d9ca5d87782407ed2634ce
149
class User < ActiveRecord::Base has_many :user_events has_secure_password validates :email, uniqueness: true validates :name, presence: true end
21.285714
35
0.798658
f836113f8e51e75a0399d3087ba3ad98708dcae7
357
cask "aerial" do version "2.3.2" sha256 "34fdbd5ec7ca087e3bea72c421947f38e43b0f62992caa532157c29b0f3e9ff1" url "https://github.com/JohnCoates/Aerial/releases/download/v#{version}/Aerial.saver.zip" name "Aerial Screensaver" homepage "https://github.com/JohnCoates/Aerial" screen_saver "Aerial.saver" zap trash: "~/Library/Caches/Aerial" end
27.461538
91
0.770308
7a6c64a94da1ff14cd961dfdfa81de419d23fd12
29,767
# Comprehensively test a formula or pull request. # # Usage: brew test-bot [options...] <pull-request|formula> # # Options: # --keep-logs: Write and keep log files under ./brewbot/ # --cleanup: Clean the Homebrew directory. Very dangerous. Use with care. # --clean-cache: Remove all cached downloads. Use with care. # --skip-setup: Don't check the local system is setup correctly. # --skip-homebrew: Don't check Homebrew's files and tests are all valid. # --junit: Generate a JUnit XML test results file. # --email: Generate an email subject file. # --no-bottle: Run brew install without --build-bottle # --HEAD: Run brew install with --HEAD # --local: Ask Homebrew to write verbose logs under ./logs/ and set HOME to ./home/ # --tap=<tap>: Use the git repository of the given tap # --dry-run: Just print commands, don't run them. # --fail-fast: Immediately exit on a failing step. # # --ci-master: Shortcut for Homebrew master branch CI options. # --ci-pr: Shortcut for Homebrew pull request CI options. # --ci-testing: Shortcut for Homebrew testing CI options. # --ci-upload: Homebrew CI bottle upload. # --ci-reset-and-update: Homebrew CI repository and tap reset and update. require 'formula' require 'utils' require 'date' require 'rexml/document' require 'rexml/xmldecl' require 'rexml/cdata' require 'cmd/tap' module Homebrew EMAIL_SUBJECT_FILE = "brew-test-bot.#{MacOS.cat}.email.txt" BYTES_IN_1_MEGABYTE = 1024*1024 def homebrew_git_repo tap=nil if tap user, repo = tap.split "/" HOMEBREW_LIBRARY/"Taps/#{user}/homebrew-#{repo}" else HOMEBREW_REPOSITORY end end class Step attr_reader :command, :name, :status, :output, :time def initialize test, command, options={} @test = test @category = test.category @command = command @puts_output_on_success = options[:puts_output_on_success] @name = command[1].delete("-") @status = :running @repository = options[:repository] || HOMEBREW_REPOSITORY @time = 0 end def log_file_path file = "#{@category}.#{@name}.txt" root = @test.log_root root ? root + file : file end def status_colour case @status when :passed then "green" when :running then "orange" when :failed then "red" end end def status_upcase @status.to_s.upcase end def command_short (@command - %w[brew --force --retry --verbose --build-bottle --rb]).join(" ") end def passed? @status == :passed end def failed? @status == :failed end def puts_command cmd = @command.join(" ") print "#{Tty.blue}==>#{Tty.white} #{cmd}#{Tty.reset}" tabs = (80 - "PASSED".length + 1 - cmd.length) / 8 tabs.times{ print "\t" } $stdout.flush end def puts_result puts " #{Tty.send status_colour}#{status_upcase}#{Tty.reset}" end def has_output? @output && [email protected]? end def run puts_command if ARGV.include? "--dry-run" puts @status = :passed return end verbose = ARGV.verbose? puts if verbose @output = "" working_dir = Pathname.new(@command.first == "git" ? @repository : Dir.pwd) start_time = Time.now read, write = IO.pipe begin pid = fork do read.close $stdout.reopen(write) $stderr.reopen(write) write.close working_dir.cd { exec(*@command) } end write.close while line = read.gets puts line if verbose @output += line end ensure read.close end Process.wait(pid) @time = Time.now - start_time @status = $?.success? ? :passed : :failed puts_result if has_output? @output = fix_encoding(@output) puts @output if (failed? or @puts_output_on_success) && !verbose File.write(log_file_path, @output) if ARGV.include? "--keep-logs" end exit 1 if ARGV.include?("--fail-fast") && failed? end private if String.method_defined?(:force_encoding) def fix_encoding(str) return str if str.valid_encoding? # Assume we are starting from a "mostly" UTF-8 string str.force_encoding(Encoding::UTF_8) str.encode!(Encoding::UTF_16, :invalid => :replace) str.encode!(Encoding::UTF_8) end elsif require "iconv" def fix_encoding(str) Iconv.conv("UTF-8//IGNORE", "UTF-8", str) end else def fix_encoding(str) str end end end class Test attr_reader :log_root, :category, :name, :steps def initialize argument, tap=nil @hash = nil @url = nil @formulae = [] @added_formulae = [] @modified_formula = [] @steps = [] @tap = tap @repository = Homebrew.homebrew_git_repo @tap url_match = argument.match HOMEBREW_PULL_OR_COMMIT_URL_REGEX begin formula = Formulary.factory(argument) rescue FormulaUnavailableError end git "rev-parse", "--verify", "-q", argument if $?.success? @hash = argument elsif url_match @url = url_match[0] elsif formula @formulae = [argument] else raise ArgumentError.new("#{argument} is not a pull request URL, commit URL or formula name.") end @category = __method__ @brewbot_root = Pathname.pwd + "brewbot" FileUtils.mkdir_p @brewbot_root end def no_args? @hash == 'HEAD' end def git(*args) rd, wr = IO.pipe pid = fork do rd.close STDERR.reopen("/dev/null") STDOUT.reopen(wr) wr.close Dir.chdir @repository exec("git", *args) end wr.close Process.wait(pid) rd.read ensure rd.close end def download def shorten_revision revision git("rev-parse", "--short", revision).strip end def current_sha1 shorten_revision 'HEAD' end def current_branch git("symbolic-ref", "HEAD").gsub("refs/heads/", "").strip end def single_commit? start_revision, end_revision git("rev-list", "--count", "#{start_revision}..#{end_revision}").to_i == 1 end def diff_formulae start_revision, end_revision, path, filter git( "diff-tree", "-r", "--name-only", "--diff-filter=#{filter}", start_revision, end_revision, "--", path ).lines.map do |line| File.basename(line.chomp, ".rb") end end def brew_update return unless current_branch == "master" success = quiet_system "brew", "update" success ||= quiet_system "brew", "update" end @category = __method__ @start_branch = current_branch # Use Jenkins environment variables if present. if no_args? and ENV['GIT_PREVIOUS_COMMIT'] and ENV['GIT_COMMIT'] \ and not ENV['ghprbPullLink'] diff_start_sha1 = shorten_revision ENV['GIT_PREVIOUS_COMMIT'] diff_end_sha1 = shorten_revision ENV['GIT_COMMIT'] brew_update elsif @hash diff_start_sha1 = current_sha1 brew_update diff_end_sha1 = current_sha1 elsif @url brew_update end # Handle Jenkins pull request builder plugin. if ENV['ghprbPullLink'] @url = ENV['ghprbPullLink'] @hash = nil end if no_args? if diff_start_sha1 == diff_end_sha1 or \ single_commit?(diff_start_sha1, diff_end_sha1) @name = diff_end_sha1 else @name = "#{diff_start_sha1}-#{diff_end_sha1}" end elsif @hash test "git", "checkout", @hash diff_start_sha1 = "#{@hash}^" diff_end_sha1 = @hash @name = @hash elsif @url diff_start_sha1 = current_sha1 test "git", "checkout", diff_start_sha1 test "brew", "pull", "--clean", @url diff_end_sha1 = current_sha1 @short_url = @url.gsub('https://github.com/', '') if @short_url.include? '/commit/' # 7 characters should be enough for a commit (not 40). @short_url.gsub!(/(commit\/\w{7}).*/, '\1') @name = @short_url else @name = "#{@short_url}-#{diff_end_sha1}" end else diff_start_sha1 = diff_end_sha1 = current_sha1 @name = "#{@formulae.first}-#{diff_end_sha1}" end @log_root = @brewbot_root + @name FileUtils.mkdir_p @log_root return unless diff_start_sha1 != diff_end_sha1 return if @url and not steps.last.passed? if @tap formula_path = %w[Formula HomebrewFormula].find { |dir| (@repository/dir).directory? } || "" else formula_path = "Library/Formula" end @added_formulae += diff_formulae(diff_start_sha1, diff_end_sha1, formula_path, "A") @modified_formula += diff_formulae(diff_start_sha1, diff_end_sha1, formula_path, "M") @formulae += @added_formulae + @modified_formula end def skip formula_name puts "#{Tty.blue}==>#{Tty.white} SKIPPING: #{formula_name}#{Tty.reset}" end def satisfied_requirements? formula, spec, dependency=nil requirements = formula.send(spec).requirements unsatisfied_requirements = requirements.reject do |requirement| satisfied = false satisfied ||= requirement.satisfied? satisfied ||= requirement.optional? if !satisfied && requirement.default_formula? default = Formula[requirement.class.default_formula] satisfied = satisfied_requirements?(default, :stable, formula.name) end satisfied end if unsatisfied_requirements.empty? true else name = formula.name name += " (#{spec})" unless spec == :stable name += " (#{dependency} dependency)" if dependency skip name puts unsatisfied_requirements.map(&:message) false end end def setup @category = __method__ return if ARGV.include? "--skip-setup" test "brew", "doctor" test "brew", "--env" test "brew", "config" end def formula formula_name @category = "#{__method__}.#{formula_name}" canonical_formula_name = if @tap "#{@tap}/#{formula_name}" else formula_name end test "brew", "uses", canonical_formula_name formula = Formulary.factory(canonical_formula_name) formula.conflicts.map { |c| Formulary.factory(c.name) }. select { |f| f.installed? }.each do |conflict| test "brew", "unlink", conflict.name end installed_gcc = false deps = [] reqs = [] if formula.stable return unless satisfied_requirements?(formula, :stable) deps |= formula.stable.deps.to_a reqs |= formula.stable.requirements.to_a elsif formula.devel return unless satisfied_requirements?(formula, :devel) end if formula.devel && !ARGV.include?('--HEAD') deps |= formula.devel.deps.to_a reqs |= formula.devel.requirements.to_a end begin deps.each do |dep| if dep.is_a?(TapDependency) && dep.tap tap_dir = Homebrew.homebrew_git_repo dep.tap test "brew", "tap", dep.tap unless tap_dir.directory? end CompilerSelector.select_for(dep.to_formula) end CompilerSelector.select_for(formula) rescue CompilerSelectionError => e unless installed_gcc if @formulae.include? "gcc" run_as_not_developer { test "brew", "install", "gcc" } else test "brew", "install", "gcc" end installed_gcc = true OS::Mac.clear_version_cache retry end skip canonical_formula_name puts e.message return end installed = Utils.popen_read("brew", "list").split("\n") dependencies = Utils.popen_read("brew", "deps", "--skip-optional", canonical_formula_name).split("\n") dependencies -= installed unchanged_dependencies = dependencies - @formulae changed_dependences = dependencies - unchanged_dependencies runtime_dependencies = Utils.popen_read("brew", "deps", "--skip-build", "--skip-optional", canonical_formula_name).split("\n") build_dependencies = dependencies - runtime_dependencies unchanged_build_dependencies = build_dependencies - @formulae dependents = Utils.popen_read("brew", "uses", "--skip-build", "--skip-optional", canonical_formula_name).split("\n") dependents -= @formulae dependents = dependents.map {|d| Formulary.factory(d)} testable_dependents = dependents.select { |d| d.test_defined? && d.bottled? } if (deps | reqs).any? { |d| d.name == "mercurial" && d.build? } if @formulae.include? "mercurial" run_as_not_developer { test "brew", "install", "mercurial" } else test "brew", "install", "mercurial" end end test "brew", "fetch", "--retry", *unchanged_dependencies unless unchanged_dependencies.empty? test "brew", "fetch", "--retry", "--build-bottle", *changed_dependences unless changed_dependences.empty? # Install changed dependencies as new bottles so we don't have checksum problems. test "brew", "install", "--build-bottle", *changed_dependences unless changed_dependences.empty? formula_fetch_options = [] formula_fetch_options << "--build-bottle" unless ARGV.include? "--no-bottle" formula_fetch_options << "--force" if ARGV.include? "--cleanup" formula_fetch_options << canonical_formula_name test "brew", "fetch", "--retry", *formula_fetch_options test "brew", "uninstall", "--force", canonical_formula_name if formula.installed? install_args = %w[--verbose] install_args << "--build-bottle" unless ARGV.include? "--no-bottle" install_args << "--HEAD" if ARGV.include? "--HEAD" # Pass --devel or --HEAD to install in the event formulae lack stable. Supports devel-only/head-only. # head-only should not have devel, but devel-only can have head. Stable can have all three. if devel_only_tap? formula install_args << "--devel" elsif head_only_tap? formula install_args << "--HEAD" end install_args << canonical_formula_name # Don't care about e.g. bottle failures for dependencies. run_as_not_developer do test "brew", "install", "--only-dependencies", *install_args unless dependencies.empty? end test "brew", "install", *install_args install_passed = steps.last.passed? audit_args = [canonical_formula_name] audit_args << "--strict" if @added_formulae.include? formula_name test "brew", "audit", *audit_args if install_passed if formula.stable? && !ARGV.include?('--no-bottle') bottle_args = ["--rb", canonical_formula_name] if @tap bottle_args << "--root-url=#{BottleSpecification::DEFAULT_DOMAIN}/#{Bintray.repository(@tap)}" end bottle_args << { :puts_output_on_success => true } test "brew", "bottle", *bottle_args bottle_step = steps.last if bottle_step.passed? and bottle_step.has_output? bottle_filename = bottle_step.output.gsub(/.*(\.\/\S+#{bottle_native_regex}).*/m, '\1') test "brew", "uninstall", "--force", canonical_formula_name if unchanged_build_dependencies.any? test "brew", "uninstall", "--force", *unchanged_build_dependencies unchanged_dependencies -= unchanged_build_dependencies end test "brew", "install", bottle_filename end end test "brew", "test", "--verbose", canonical_formula_name if formula.test_defined? testable_dependents.each do |dependent| unless dependent.installed? test "brew", "fetch", "--retry", dependent.name next if steps.last.failed? conflicts = dependent.conflicts.map { |c| Formulary.factory(c.name) }.select { |f| f.installed? } conflicts.each do |conflict| test "brew", "unlink", conflict.name end test "brew", "install", dependent.name next if steps.last.failed? end if dependent.installed? test "brew", "test", "--verbose", dependent.name end end test "brew", "uninstall", "--force", canonical_formula_name end if formula.devel && formula.stable? && !ARGV.include?('--HEAD') \ && satisfied_requirements?(formula, :devel) test "brew", "fetch", "--retry", "--devel", *formula_fetch_options test "brew", "install", "--devel", "--verbose", canonical_formula_name devel_install_passed = steps.last.passed? test "brew", "audit", "--devel", *audit_args if devel_install_passed test "brew", "test", "--devel", "--verbose", canonical_formula_name if formula.test_defined? test "brew", "uninstall", "--devel", "--force", canonical_formula_name end end test "brew", "uninstall", "--force", *unchanged_dependencies if unchanged_dependencies.any? end def homebrew @category = __method__ return if ARGV.include? "--skip-homebrew" test "brew", "tests" readall_args = [] readall_args << "--syntax" if MacOS.version >= :mavericks test "brew", "readall", *readall_args end def cleanup_before @category = __method__ return unless ARGV.include? '--cleanup' git "stash" git "am", "--abort" git "rebase", "--abort" git "reset", "--hard" git "checkout", "-f", "master" git "clean", "-fdx" git "clean", "-ffdx" unless $?.success? pr_locks = "#{HOMEBREW_REPOSITORY}/.git/refs/remotes/*/pr/*/*.lock" Dir.glob(pr_locks) {|lock| FileUtils.rm_rf lock } end def cleanup_after @category = __method__ checkout_args = [] if ARGV.include? '--cleanup' git "clean", "-fdx" test "git", "clean", "-ffdx" unless $?.success? checkout_args << "-f" end checkout_args << @start_branch if ARGV.include? '--cleanup' or @url or @hash test "git", "checkout", *checkout_args end if ARGV.include? '--cleanup' test "git", "reset", "--hard" git "stash", "pop" test "brew", "cleanup", "--prune=30" end FileUtils.rm_rf @brewbot_root unless ARGV.include? "--keep-logs" end def test(*args) options = Hash === args.last ? args.pop : {} options[:repository] = @repository step = Step.new self, args, options step.run steps << step step end def check_results steps.all? do |step| case step.status when :passed then true when :running then raise when :failed then false end end end def formulae changed_formulae_dependents = {} @formulae.each do |formula| formula_dependencies = Utils.popen_read("brew", "deps", formula).split("\n") unchanged_dependencies = formula_dependencies - @formulae changed_dependences = formula_dependencies - unchanged_dependencies changed_dependences.each do |changed_formula| changed_formulae_dependents[changed_formula] ||= 0 changed_formulae_dependents[changed_formula] += 1 end end changed_formulae = changed_formulae_dependents.sort do |a1,a2| a2[1].to_i <=> a1[1].to_i end changed_formulae.map!(&:first) unchanged_formulae = @formulae - changed_formulae changed_formulae + unchanged_formulae end def head_only_tap? formula formula.head && formula.devel.nil? && formula.stable.nil? && formula.tap == "homebrew/homebrew-head-only" end def devel_only_tap? formula formula.devel && formula.stable.nil? && formula.tap == "homebrew/homebrew-devel-only" end def run cleanup_before download setup homebrew formulae.each do |f| formula(f) end cleanup_after check_results end end def test_bot tap = ARGV.value('tap') if !tap && ENV['UPSTREAM_BOT_PARAMS'] bot_argv = ENV['UPSTREAM_BOT_PARAMS'].split " " bot_argv.extend HomebrewArgvExtension tap ||= bot_argv.value('tap') end tap.gsub!(/homebrew\/homebrew-/i, "Homebrew/") if tap git_url = ENV['UPSTREAM_GIT_URL'] || ENV['GIT_URL'] if !tap && git_url # Also can get tap from Jenkins GIT_URL. url_path = git_url.gsub(%r{^https?://github\.com/}, "").gsub(%r{/$}, "") HOMEBREW_TAP_ARGS_REGEX =~ url_path tap = "#{$1}/#{$3}" if $1 && $3 end if Pathname.pwd == HOMEBREW_PREFIX and ARGV.include? "--cleanup" odie 'cannot use --cleanup from HOMEBREW_PREFIX as it will delete all output.' end if ARGV.include? "--email" File.open EMAIL_SUBJECT_FILE, 'w' do |file| # The file should be written at the end but in case we don't get to that # point ensure that we have something valid. file.write "#{MacOS.version}: internal error." end end ENV['HOMEBREW_DEVELOPER'] = '1' ENV['HOMEBREW_NO_EMOJI'] = '1' if ARGV.include? '--ci-master' or ARGV.include? '--ci-pr' \ or ARGV.include? '--ci-testing' ARGV << "--cleanup" if ENV["JENKINS_HOME"] || ENV["TRAVIS_COMMIT"] ARGV << "--junit" << "--local" end if ARGV.include? '--ci-master' ARGV << '--no-bottle' << '--email' end if ARGV.include? '--local' ENV['HOME'] = "#{Dir.pwd}/home" mkdir_p ENV['HOME'] ENV['HOMEBREW_LOGS'] = "#{Dir.pwd}/logs" end if ARGV.include? "--ci-reset-and-update" Dir.glob("#{HOMEBREW_LIBRARY}/Taps/*/*") do |tap_dir| cd tap_dir do system "git am --abort 2>/dev/null" system "git rebase --abort 2>/dev/null" safe_system "git", "checkout", "-f", "master" safe_system "git", "reset", "--hard", "origin/master" end end safe_system "brew", "update" return end repository = Homebrew.homebrew_git_repo tap # Tap repository if required, this is done before everything else # because Formula parsing and/or git commit hash lookup depends on it. if tap if !repository.directory? safe_system "brew", "tap", tap else quiet_system "brew", "tap", "--repair" end end if ARGV.include? '--ci-upload' jenkins = ENV['JENKINS_HOME'] job = ENV['UPSTREAM_JOB_NAME'] id = ENV['UPSTREAM_BUILD_ID'] raise "Missing Jenkins variables!" if !jenkins || !job || !id bintray_user = ENV["BINTRAY_USER"] bintray_key = ENV["BINTRAY_KEY"] if !bintray_user || !bintray_key raise "Missing BINTRAY_USER or BINTRAY_KEY variables!" end ARGV << '--verbose' bottles = Dir["#{jenkins}/jobs/#{job}/configurations/axis-version/*/builds/#{id}/archive/*.bottle*.*"] return if bottles.empty? FileUtils.cp bottles, Dir.pwd, :verbose => true ENV["GIT_COMMITTER_NAME"] = "BrewTestBot" ENV["GIT_COMMITTER_EMAIL"] = "[email protected]" ENV["GIT_WORK_TREE"] = repository ENV["GIT_DIR"] = "#{ENV["GIT_WORK_TREE"]}/.git" pr = ENV['UPSTREAM_PULL_REQUEST'] number = ENV['UPSTREAM_BUILD_NUMBER'] system "git am --abort 2>/dev/null" system "git rebase --abort 2>/dev/null" safe_system "git", "checkout", "-f", "master" safe_system "git", "reset", "--hard", "origin/master" safe_system "brew", "update" if pr pull_pr = if tap user, repo = tap.split "/" "https://github.com/#{user}/homebrew-#{repo}/pull/#{pr}" else pr end safe_system "brew", "pull", "--clean", pull_pr end # Check for existing bottles as we don't want them to be autopublished # on Bintray until manually `brew pull`ed. existing_bottles = {} Dir.glob("*.bottle*.tar.gz") do |filename| formula_name = bottle_filename_formula_name filename canonical_formula_name = if tap "#{tap}/#{formula_name}" else formula_name end formula = Formulary.factory canonical_formula_name existing_bottles[formula_name] = !!formula.bottle end ENV["GIT_AUTHOR_NAME"] = ENV["GIT_COMMITTER_NAME"] ENV["GIT_AUTHOR_EMAIL"] = ENV["GIT_COMMITTER_EMAIL"] bottle_args = ["--merge", "--write", *Dir["*.bottle.rb"]] bottle_args << "--tap=#{tap}" if tap safe_system "brew", "bottle", *bottle_args remote_repo = tap ? tap.gsub("/", "-") : "homebrew" remote = "[email protected]:BrewTestBot/#{remote_repo}.git" tag = pr ? "pr-#{pr}" : "testing-#{number}" safe_system "git", "push", "--force", remote, "master:master", ":refs/tags/#{tag}" bintray_repo = Bintray.repository(tap) bintray_repo_url = "https://api.bintray.com/packages/homebrew/#{bintray_repo}" formula_packaged = {} Dir.glob("*.bottle*.tar.gz") do |filename| formula_name = bottle_filename_formula_name filename canonical_formula_name = if tap "#{tap}/#{formula_name}" else formula_name end formula = Formulary.factory canonical_formula_name version = formula.pkg_version bintray_package = Bintray.package formula_name existing_bottle = existing_bottles[formula_name] unless formula_packaged[formula_name] package_url = "#{bintray_repo_url}/#{bintray_package}" unless system "curl", "--silent", "--fail", "--output", "/dev/null", package_url curl "--silent", "--fail", "-u#{bintray_user}:#{bintray_key}", "-H", "Content-Type: application/json", "-d", "{\"name\":\"#{bintray_package}\"}", bintray_repo_url puts end formula_packaged[formula_name] = true end content_url = "https://api.bintray.com/content/homebrew" content_url += "/#{bintray_repo}/#{bintray_package}/#{version}/#{filename}" content_url += "?override=1" content_url += "&publish=1" if existing_bottle curl "--silent", "--fail", "-u#{bintray_user}:#{bintray_key}", "-T", filename, content_url puts end safe_system "git", "tag", "--force", tag safe_system "git", "push", "--force", remote, "refs/tags/#{tag}" return end tests = [] any_errors = false if ARGV.named.empty? # With no arguments just build the most recent commit. head_test = Test.new('HEAD', tap) any_errors = !head_test.run tests << head_test else ARGV.named.each do |argument| test_error = false begin test = Test.new(argument, tap) rescue ArgumentError => e test_error = true ofail e.message else test_error = !test.run tests << test end any_errors ||= test_error end end if ARGV.include? "--junit" xml_document = REXML::Document.new xml_document << REXML::XMLDecl.new testsuites = xml_document.add_element "testsuites" tests.each do |test| testsuite = testsuites.add_element "testsuite" testsuite.add_attribute "name", "brew-test-bot.#{MacOS.cat}" testsuite.add_attribute "tests", test.steps.count test.steps.each do |step| testcase = testsuite.add_element "testcase" testcase.add_attribute "name", step.command_short testcase.add_attribute "status", step.status testcase.add_attribute "time", step.time if step.has_output? # Remove invalid XML CData characters from step output. output = step.output.delete("\000\a\b\e\f\x2\x1f") if output.bytesize > BYTES_IN_1_MEGABYTE output = "truncated output to 1MB:\n" \ + output.slice(-BYTES_IN_1_MEGABYTE, BYTES_IN_1_MEGABYTE) end cdata = REXML::CData.new output if step.passed? elem = testcase.add_element "system-out" else elem = testcase.add_element "failure" elem.add_attribute "message", "#{step.status}: #{step.command.join(" ")}" end elem << cdata end end end open("brew-test-bot.xml", "w") do |xml_file| pretty_print_indent = 2 xml_document.write(xml_file, pretty_print_indent) end end if ARGV.include? "--email" failed_steps = [] tests.each do |test| test.steps.each do |step| next if step.passed? failed_steps << step.command_short end end if failed_steps.empty? email_subject = '' else email_subject = "#{MacOS.version}: #{failed_steps.join ', '}." end File.open EMAIL_SUBJECT_FILE, 'w' do |file| file.write email_subject end end safe_system "rm -rf #{HOMEBREW_CACHE}/*" if ARGV.include? "--clean-cache" Homebrew.failed = any_errors end end
31.973147
122
0.598683
3831867cd53f8e362b336857bb23f1fa596dcc69
7,500
# coding: utf-8 Pod::Spec.new do |s| s.name = "WeexSDK" s.version = "0.28.0" s.summary = "WeexSDK Source." s.description = <<-DESC A framework for building Mobile cross-platform UI DESC s.homepage = "https://github.com/alibaba/weex" s.license = { :type => 'Copyright', :text => <<-LICENSE Alibaba-INC copyright LICENSE } s.authors = { "cxfeng1" => "[email protected]", "boboning" => "[email protected]", "yangshengtao" => "[email protected]", "kfeagle" => "[email protected]", "acton393" => "[email protected]", "wqyfavor" => "[email protected]", "doumafang " => "[email protected]" } s.platform = :ios s.ios.deployment_target = '9.0' # use for public # s.source = { # :git => 'https://github.com/apache/incubator-weex.git', # :tag => #{s.version} # } # use for playground s.source = { :path => '.' } s.source_files = 'ios/sdk/WeexSDK/Sources/**/*.{h,m,mm,c,cpp,cc}', 'ios/Custom/*.{h,m,mm,c,cpp,cc}', 'weex_core/Source/base/**/*.{h,hpp,m,mm,c,cpp,cc}', 'weex_core/Source/core/**/*.{h,hpp,m,mm,c,cpp,cc}', 'weex_core/Source/wson/**/*.{h,hpp,m,mm,c,cpp,cc}', 'weex_core/Source/third_party/**/*.{h,hpp,m,mm,c,cpp,cc}', 'weex_core/Source/include/**/*.{h,hpp,m,mm,c,cpp,cc}' s.exclude_files = 'weex_core/Source/**/*android.{h,hpp,m,mm,c,cpp,cc}', 'weex_core/Source/base/android', 'weex_core/Source/base/base64', 'weex_core/Source/base/crash', 'weex_core/Source/base/utils/Compatible.cpp', 'weex_core/Source/base/utils/ThreadLocker.cpp', 'weex_core/Source/core/parser/action_args_check.*', 'weex_core/Source/third_party/IPC', 'weex_core/Source/core/network/android/', 'weex_core/Source/include/JavaScriptCore/', 'weex_core/Source/include/wtf' s.private_header_files = 'ios/sdk/WeexSDK/Sources/Component/RecycleList/WXJSASTParser.h' s.public_header_files = 'ios/sdk/WeexSDK/Sources/WeexSDK.h', 'ios/sdk/WeexSDK/Sources/Layout/WXComponent+Layout.h', 'ios/sdk/WeexSDK/Sources/Debug/WXDebugTool.h', 'ios/sdk/WeexSDK/Sources/Loader/WXResourceLoader.h', 'ios/sdk/WeexSDK/Sources/WebSocket/WXWebSocketHandler.h', 'ios/sdk/WeexSDK/Sources/Module/WXVoiceOverModule.h', 'ios/sdk/WeexSDK/Sources/Module/WXPrerenderManager.h', 'ios/sdk/WeexSDK/Sources/Module/WXModalUIModule.h', 'ios/sdk/WeexSDK/Sources/Module/WXStreamModule.h', 'ios/sdk/WeexSDK/Sources/Component/WXListComponent.h', 'ios/sdk/WeexSDK/Sources/Component/WXScrollerComponent.h', 'ios/sdk/WeexSDK/Sources/Component/WXRichText.h', 'ios/sdk/WeexSDK/Sources/Component/WXIndicatorComponent.h', 'ios/sdk/WeexSDK/Sources/Component/WXAComponent.h', 'ios/sdk/WeexSDK/Sources/Component/WXRefreshComponent.h', 'ios/sdk/WeexSDK/Sources/Component/Recycler/WXRecyclerComponent.h', 'ios/sdk/WeexSDK/Sources/Controller/WXBaseViewController.h', 'ios/sdk/WeexSDK/Sources/Controller/WXRootViewController.h', 'ios/sdk/WeexSDK/Sources/Handler/WXNavigationDefaultImpl.h', 'ios/sdk/WeexSDK/Sources/View/WXView.h', 'ios/sdk/WeexSDK/Sources/View/WXErrorView.h', 'ios/sdk/WeexSDK/Sources/Protocol/*.h', 'ios/sdk/WeexSDK/Sources/Network/WXResourceRequestHandler.h', 'ios/sdk/WeexSDK/Sources/Network/WXResourceRequest.h', 'ios/sdk/WeexSDK/Sources/Network/WXResourceResponse.h', 'ios/sdk/WeexSDK/Sources/Model/WXSDKInstance.h', 'ios/sdk/WeexSDK/Sources/Model/WXJSExceptionInfo.h', 'ios/sdk/WeexSDK/Sources/Model/WXComponent.h', 'ios/sdk/WeexSDK/Sources/Monitor/WXMonitor.h', 'ios/sdk/WeexSDK/Sources/Monitor/WXExceptionUtils.h', 'ios/sdk/WeexSDK/Sources/Monitor/WXAnalyzerCenter.h', 'ios/sdk/WeexSDK/Sources/Manager/WXSDKManager.h', 'ios/sdk/WeexSDK/Sources/Manager/WXBridgeManager.h', 'ios/sdk/WeexSDK/Sources/Manager/WXComponentManager.h', 'ios/sdk/WeexSDK/Sources/Manager/WXHandlerFactory.h', 'ios/sdk/WeexSDK/Sources/Manager/WXComponentFactory.h', 'ios/sdk/WeexSDK/Sources/Manager/WXInvocationConfig.h', 'ios/sdk/WeexSDK/Sources/Engine/WXSDKEngine.h', 'ios/sdk/WeexSDK/Sources/Engine/WXSDKError.h', 'ios/sdk/WeexSDK/Sources/Eagle/WXDataRenderHandler.h', 'ios/sdk/WeexSDK/Sources/Utility/WXConvert.h', 'ios/sdk/WeexSDK/Sources/Utility/WXUtility.h', 'ios/sdk/WeexSDK/Sources/Utility/WXConvertUtility.h', 'ios/sdk/WeexSDK/Sources/Utility/WXLog.h', 'ios/sdk/WeexSDK/Sources/Utility/WXDefine.h', 'ios/sdk/WeexSDK/Sources/Utility/WXType.h', 'ios/sdk/WeexSDK/Sources/Utility/NSObject+WXSwizzle.h', 'ios/sdk/WeexSDK/Sources/Utility/WXAppConfiguration.h', 'ios/sdk/WeexSDK/Sources/Performance/WXApmForInstance.h', 'ios/sdk/WeexSDK/Sources/Bridge/JSContext+Weex.h', 'ios/sdk/WeexSDK/Sources/Bridge/WXBridgeMethod.h', 'weex_core/Source/core/layout/flex_enum.h', 'weex_core/Source/core/layout/layout.h', 'weex_core/Source/core/layout/style.h', 'weex_core/Source/core/bridge/eagle_bridge.h' s.module_map = 'WeexSDK.modulemap' # 0.21.0 版本开始不再需要 native-bundle-main.js s.resources = 'pre-build/*.js','ios/sdk/WeexSDK/Resources/[email protected]' s.user_target_xcconfig = { 'FRAMEWORK_SEARCH_PATHS' => "'$(PODS_ROOT)/WeexSDK'" } s.requires_arc = true s.prefix_header_file = 'ios/sdk/WeexSDK/Sources/Supporting Files/WeexSDK-Prefix.pch' s.xcconfig = { "OTHER_LINK_FLAG" => '$(inherited) -ObjC' } s.pod_target_xcconfig = { 'USER_HEADER_SEARCH_PATHS' => '${PODS_TARGET_SRCROOT}/WeexSDK/weex_core/Source/ ${PROJECT_DIR}/../../../../plugins/eeui/WeexSDK/ios/weex_core/Source', 'GCC_PREPROCESSOR_DEFINITIONS' => 'OS_IOS=1' } s.frameworks = 'CoreMedia','MediaPlayer','AVFoundation','AVKit','JavaScriptCore','GLKit','OpenGLES','CoreText','QuartzCore','CoreGraphics' s.libraries = 'c++' end
55.147059
178
0.549867
1127ddbef66f020186f2b8abcc143a41f8dd0857
6,071
=begin #OpenAPI Petstore #This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.1.2-SNAPSHOT =end require 'date' module Petstore class ReadOnlyFirst attr_accessor :bar attr_accessor :baz # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'bar' => :'bar', :'baz' => :'baz' } end # Attribute type mapping. def self.openapi_types { :'bar' => :'String', :'baz' => :'String' } 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 `Petstore::ReadOnlyFirst` 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 `Petstore::ReadOnlyFirst`. 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?(:'bar') self.bar = attributes[:'bar'] end if attributes.key?(:'baz') self.baz = attributes[:'baz'] 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 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? 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 && bar == o.bar && baz == o.baz 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 [bar, baz].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 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 # 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 Petstore.const_get(type).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
29.470874
201
0.617691
bf7c30d8a18e96747c33498c63470b2b827609be
2,161
require 'spec_helper' describe Spree::ReturnItem::EligibilityValidator::NoReimbursements do let(:validator) { Spree::ReturnItem::EligibilityValidator::NoReimbursements.new(return_item) } describe "#eligible_for_return?" do subject { validator.eligible_for_return? } context "inventory unit has already been reimbursed" do let(:reimbursement) { create(:reimbursement) } let(:return_item) { reimbursement.return_items.last } it "returns false" do expect(subject).to eq false end it "sets an error" do subject expect(validator.errors[:inventory_unit_reimbursed]).to eq Spree.t('return_item_inventory_unit_reimbursed') end context "but the return item has been expired" do before { return_item.expired } it "returns true" do expect(subject).to eq true end end context "but the return item has been canceled" do before { return_item.cancel } it "returns true" do expect(subject).to eq true end end context "but the return item has been unexchanged" do before { return_item.unexchange } it "returns true" do expect(subject).to eq true end end end context "inventory unit has not been reimbursed" do let(:return_item) { create(:return_item) } it "returns true" do expect(subject).to eq true end end end describe "#requires_manual_intervention?" do subject { validator.requires_manual_intervention? } context "not eligible for return" do let(:reimbursement) { create(:reimbursement) } let(:return_item) { reimbursement.return_items.last } before do validator.eligible_for_return? end it 'returns true if errors were added' do expect(subject).to eq true end end context "eligible for return" do let(:return_item) { create(:return_item) } before do validator.eligible_for_return? end it 'returns false if no errors were added' do expect(subject).to eq false end end end end
25.127907
115
0.646923
e27a4a80e20988538c75279e3c382d01562d2f6a
659
module Edmunds class Style < API def find_by_id(style_id) @url = "/stylerepository/findbyid?id=#{style_id}&" call_style_api end def find_styles_by_make_model_year(make, model, year) @url = "/stylerepository/findstylesbymakemodelyear?make=#{make}&model=#{model}&year=#{year}&" call_style_api end def find_styles_by_model_year_id(model_year_id) @url = "/stylerepository/findstylesbymodelyearid?modelyearid=#{model_year_id}&" call_style_api end private def call_style_api @base = "http://api.edmunds.com/v1/api/vehicle" call_api @json["styleHolder"] end end end
22.724138
99
0.6783
bf13834889ca778177ba0dd0d6008b3f47da21d8
1,149
# bandwidth # # This file was automatically generated by APIMATIC v2.0 # ( https://apimatic.io ). module Bandwidth # TwoFactorVoiceResponse Model. class TwoFactorVoiceResponse < BaseModel SKIP = Object.new private_constant :SKIP # TODO: Write general description for this method # @return [String] attr_accessor :call_id # A mapping from model property names to API property names. def self.names @_hash = {} if @_hash.nil? @_hash['call_id'] = 'callId' @_hash end # An array for optional fields def optionals %w[ call_id ] end # An array for nullable fields def nullables [] end def initialize(call_id = nil) @call_id = call_id unless call_id == SKIP end # Creates an instance of the object from a hash. def self.from_hash(hash) return nil unless hash # Extract variables from the hash. call_id = hash.key?('callId') ? hash['callId'] : SKIP # Create object from extracted values. TwoFactorVoiceResponse.new(call_id) end end end
22.529412
65
0.614447
1a0f9feb2380464a9138e282559f601d49f8cdae
4,447
require 'spec_helper' require File.expand_path('../shared_examples', __FILE__) describe GlobalSession::Session::V4 do subject { GlobalSession::Session::V4 } include SpecHelper context 'given an EC key' do let(:key_generation_parameter) { 'prime256v1' } let(:signature_method) { :dsa_sign_asn1 } let(:approximate_token_size) { 210 } it_should_behave_like 'all subclasses of Session::Abstract' let(:algorithm_identifier) { 'ES256' } it_should_behave_like 'JWT compatible subclasses of Session::Abstract' end context 'given an RSA key' do let(:key_generation_parameter) { 1024 } let(:signature_method) { :dsa_sign_asn1 } let(:approximate_token_size) { 280 } it_should_behave_like 'all subclasses of Session::Abstract' let(:algorithm_identifier) { 'RS256' } it_should_behave_like 'JWT compatible subclasses of Session::Abstract' end # tests related to accepting flexeraIAM-generated tokens context 'decode_cookie' do let(:token_subject) { "my_okta_user" } let(:now) { Time.now } let(:expire_at) { now + 60 } let(:trusted_issuer) { "my-RS256" } let(:key_generation_parameter) { 1024 } let(:configuration) do { 'attributes' => { 'signed' => ['sub'] }, 'keystore' => { 'public' => key_factory.dir, 'private' => File.join(key_factory.dir, "#{trusted_issuer}.key"), }, 'timeout' => 60, } end let(:directory) { GlobalSession::Directory.new(configuration) } let(:key_factory) { KeyFactory.new } before do key_factory.create(trusted_issuer, true, parameter: key_generation_parameter) key_factory.create('untrusted', true, parameter: key_generation_parameter) FileUtils.rm(File.join(key_factory.dir, 'untrusted.pub')) end after do key_factory.destroy end context 'when the typ=JWT header is ommitted' do let(:valid_jwt) do algorithm = 'RS256' header = { 'alg' => algorithm } encoded_header = JWT.base64url_encode(JWT.encode_json(header)) payload = { 'iat' => now.to_i, 'exp' => expire_at.to_i, 'iss' => trusted_issuer, 'sub' => token_subject } segments = [] segments << encoded_header segments << JWT.encoded_payload(payload) segments << JWT.encoded_signature(segments.join('.'), directory.private_key, algorithm) segments.join('.') end it 'should parse properly' do session = subject.new(directory, valid_jwt) expect(session['sub']).to eq(token_subject) end end context 'when the issuer is a flexeraiam-us endpoint, and the issuer is present in the kid header' do let(:valid_jwt) do algorithm = 'RS256' header = { 'kid' => trusted_issuer, 'alg' => algorithm } encoded_header = JWT.base64url_encode(JWT.encode_json(header)) payload = { 'iat' => now.to_i, 'exp' => expire_at.to_i, 'iss' => "https://secure.flexeratest.com/oauth/something", 'sub' => token_subject } segments = [] segments << encoded_header segments << JWT.encoded_payload(payload) segments << JWT.encoded_signature(segments.join('.'), directory.private_key, algorithm) segments.join('.') end it 'should parse properly' do session = subject.new(directory, valid_jwt) expect(session['sub']).to eq(token_subject) end end context 'when the issuer is a flexeraiam-eu endpoint, and the issuer is present in the kid header' do let(:valid_jwt) do algorithm = 'RS256' header = { 'kid' => trusted_issuer, 'alg' => algorithm } encoded_header = JWT.base64url_encode(JWT.encode_json(header)) payload = { 'iat' => now.to_i, 'exp' => expire_at.to_i, 'iss' => "https://secure.flexera.eu/oauth/something", 'sub' => token_subject } segments = [] segments << encoded_header segments << JWT.encoded_payload(payload) segments << JWT.encoded_signature(segments.join('.'), directory.private_key, algorithm) segments.join('.') end it 'should parse properly' do session = subject.new(directory, valid_jwt) expect(session['sub']).to eq(token_subject) end end end end
31.992806
105
0.621992
1da8a49699b0be040f9a5a8eb43d5c7f46272723
2,668
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'User activates Jira', :js do include_context 'project service activation' let(:url) { 'http://jira.example.com' } let(:test_url) { 'http://jira.example.com/rest/api/2/serverInfo' } def fill_form(disable: false) click_active_toggle if disable fill_in 'service_url', with: url fill_in 'service_username', with: 'username' fill_in 'service_password', with: 'password' fill_in 'service_jira_issue_transition_id', with: '25' end describe 'user sets and activates Jira Service' do context 'when Jira connection test succeeds' do before do server_info = { key: 'value' }.to_json stub_request(:get, test_url).with(basic_auth: %w(username password)).to_return(body: server_info) visit_project_integration('Jira') fill_form click_test_integration end it 'activates the Jira service' do expect(page).to have_content('Jira activated.') expect(current_path).to eq(project_settings_integrations_path(project)) end it 'shows the Jira link in the menu' do page.within('.nav-sidebar') do expect(page).to have_link('Jira', href: url) end end end context 'when Jira connection test fails' do it 'shows errors when some required fields are not filled in' do visit_project_integration('Jira') fill_in 'service_password', with: 'password' click_test_integration page.within('.service-settings') do expect(page).to have_content('This field is required.') end end it 'activates the Jira service' do stub_request(:get, test_url).with(basic_auth: %w(username password)) .to_raise(JIRA::HTTPError.new(double(message: 'message'))) visit_project_integration('Jira') fill_form click_test_then_save_integration expect(page).to have_content('Jira activated.') expect(current_path).to eq(project_settings_integrations_path(project)) end end end describe 'user disables the Jira Service' do before do visit_project_integration('Jira') fill_form(disable: true) click_button('Save changes') end it 'saves but does not activate the Jira service' do expect(page).to have_content('Jira settings saved, but not activated.') expect(current_path).to eq(project_settings_integrations_path(project)) end it 'does not show the Jira link in the menu' do page.within('.nav-sidebar') do expect(page).not_to have_link('Jira', href: url) end end end end
30.318182
105
0.674288
e88bed96b3b1807341fc3614dc19eeb93cac568a
4,311
require 'cxxstdlib' require 'ostruct' require 'options' require 'utils/json' # Inherit from OpenStruct to gain a generic initialization method that takes a # hash and creates an attribute for each key and value. `Tab.new` probably # should not be called directly, instead use one of the class methods like # `Tab.create`. class Tab < OpenStruct FILENAME = 'INSTALL_RECEIPT.json' def self.create(formula, compiler, stdlib, build) attributes = { :used_options => build.used_options.as_flags, :unused_options => build.unused_options.as_flags, :tabfile => formula.prefix.join(FILENAME), :built_as_bottle => !!ARGV.build_bottle?, :poured_from_bottle => false, :tapped_from => formula.tap, :time => Time.now.to_i, :HEAD => Homebrew.git_head, :compiler => compiler, :stdlib => stdlib, :source => { :path => formula.path.to_s, }, } new(attributes) end def self.from_file path attributes = Utils::JSON.load(File.read(path)) attributes[:tabfile] = path new(attributes) end def self.for_keg keg path = keg.join(FILENAME) if path.exist? from_file(path) else dummy_tab end end def self.for_name name for_formula(Formulary.factory(name)) end def self.remap_deprecated_options deprecated_options, options deprecated_options.each do |deprecated_option| option = options.find { |o| o.name == deprecated_option.old } next unless option options -= [option] options << Option.new(deprecated_option.current, option.description) end options end def self.for_formula f paths = [] if f.opt_prefix.symlink? && f.opt_prefix.directory? paths << f.opt_prefix.resolved_path end if f.linked_keg.symlink? && f.linked_keg.directory? paths << f.linked_keg.resolved_path end if f.rack.directory? && (dirs = f.rack.subdirs).length == 1 paths << dirs.first end paths << f.prefix path = paths.map { |pn| pn.join(FILENAME) }.find(&:file?) if path tab = from_file(path) used_options = remap_deprecated_options(f.deprecated_options, tab.used_options) tab.used_options = used_options.as_flags tab else dummy_tab(f) end end def self.dummy_tab f=nil attributes = { :used_options => [], :unused_options => f ? f.options.as_flags : [], :built_as_bottle => false, :poured_from_bottle => false, :tapped_from => "", :time => nil, :HEAD => nil, :stdlib => nil, :compiler => :clang, :source => { :path => nil, }, } new(attributes) end def with? val name = val.respond_to?(:option_name) ? val.option_name : val include?("with-#{name}") || unused_options.include?("without-#{name}") end def without? name not with? name end def include? opt used_options.include? opt end def universal? include?("universal") end def cxx11? include?("c++11") end def build_32_bit? include?("32-bit") end def used_options Options.create(super) end def unused_options Options.create(super) end def cxxstdlib # Older tabs won't have these values, so provide sensible defaults lib = stdlib.to_sym if stdlib cc = compiler || MacOS.default_compiler CxxStdlib.create(lib, cc.to_sym) end def build_bottle? built_as_bottle && !poured_from_bottle end def to_json attributes = { :used_options => used_options.as_flags, :unused_options => unused_options.as_flags, :built_as_bottle => built_as_bottle, :poured_from_bottle => poured_from_bottle, :tapped_from => tapped_from, :time => time, :HEAD => self.HEAD, :stdlib => (stdlib.to_s if stdlib), :compiler => (compiler.to_s if compiler), :source => source || {}, } Utils::JSON.dump(attributes) end def write tabfile.atomic_write(to_json) end def to_s s = [] case poured_from_bottle when true then s << "Poured from bottle" when false then s << "Built from source" end unless used_options.empty? s << "Installed" if s.empty? s << "with:" s << used_options.to_a.join(", ") end s.join(" ") end end
22.689474
85
0.63396
8728fce7c44eb60230fba091ed1c6f18aa66040f
199
class AddEmployeeRepresentativeNotifiedAtToSupervisorReports < ActiveRecord::Migration[5.2] def change add_column :supervisor_reports, :employee_representative_notified_at, :datetime end end
33.166667
91
0.844221
acb1f75734bc2c1574d0efbd0620fa450ab287c9
642
cask "xbar" do version "2.1.7-beta" sha256 "0a7ea7c40e4d4e2ecce0dae3c9c3773d459ddf5af86744f70c44b9f9901bc73f" url "https://github.com/matryer/xbar/releases/download/v#{version}/xbar.v#{version}.dmg", verified: "github.com/matryer/xbar/" name "xbar" desc "View output from scripts in the menu bar" homepage "https://xbarapp.com/" livecheck do url "https://xbarapp.com/dl" strategy :header_match end depends_on macos: ">= :high_sierra" app "xbar.app" uninstall quit: "xbar.v#{version}" zap trash: [ "~/Library/Preferences/xbar.v#{version}.plist", "~/Library/WebKit/xbar.v#{version}", ] end
23.777778
91
0.690031
08c6d8cef6405242e065e9433624571384a156e8
1,022
class Object def blank? respond_to?(:empty?) ? empty? : !self end def present? !blank? end def boolean? [true, false].include? self end end class String def to_bool return true if self == true || self =~ (/(true|t|yes|y|x|1)$/i) return false if self == false || self.blank? || self =~ (/(false|f|no|n|0)$/i) raise ArgumentError.new("invalid value for Boolean: \"#{self}\"") end def string_between(marker1, marker2) self[/#{Regexp.escape(marker1)}(.*?)#{Regexp.escape(marker2)}/m, 1] end def format_date_time(date_time_format) return if self.blank? new_date = DateTime.parse(self) if ENV['LOCALE'] && date_time_format.is_a?(Symbol) I18n.l(new_date, format: date_time_format) else new_date.strftime(date_time_format) end end def titlecase "#{self.split.each{ |text| text.capitalize! }.join(' ')}" end def is_int? Integer(self) && true rescue false end def is_float? Float(self) && true rescue false end end
20.857143
82
0.636986
edee0d1957b1d3badff324907bb68798353c4769
1,125
class Thing < ActiveRecord::Base include Geokit::Geocoders require 'libxml' validates_presence_of :lat, :lng belongs_to :user has_many :reminders def self.find_closest(lat, lng, limit=10) query = <<-SQL SELECT *, (3959 * ACOS(COS(RADIANS(?)) * COS(RADIANS(lat)) * COS(RADIANS(lng) - RADIANS(?)) + SIN(RADIANS(?)) * SIN(RADIANS(lat)))) AS distance FROM things ORDER BY distance LIMIT ? SQL find_by_sql([query, lat.to_f, lng.to_f, lat.to_f, limit.to_i]) end def reverse_geocode @reverse_geocode ||= MultiGeocoder.reverse_geocode([lat, lng]) end def street_number reverse_geocode.street_number end def street_name reverse_geocode.street_name end def street_address reverse_geocode.street_address end def city reverse_geocode.city end def state reverse_geocode.state end def zip reverse_geocode.zip end def country_code reverse_geocode.country_code end def country reverse_geocode.country end def full_address reverse_geocode.full_address end def adopted? !user_id.nil? end end
18.442623
149
0.691556
6ac414384907a7f29e09b21569f53b6d986f1233
806
require "bundler/setup" require "active_storage/engine" Bundler.require :default, :development require "support/blob_helper" Combustion.initialize! :active_record, :active_job do if ActiveRecord::VERSION::MAJOR < 6 && config.active_record.sqlite3.respond_to?(:represent_boolean_as_integer) config.active_record.sqlite3.represent_boolean_as_integer = true end config.active_job.queue_adapter = :inline config.active_storage.service = :test end RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end config.include BlobHelper end
29.851852
112
0.784119
01b3fd5aa0afd7f7d5d690f5f39e5aea31ee963e
51,140
# 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 '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 GkehubV1 # GKE Hub # # # # @example # require 'google/apis/gkehub_v1' # # Gkehub = Google::Apis::GkehubV1 # Alias the module # service = Gkehub::GKEHubService.new # # @see https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster class GKEHubService < Google::Apis::Core::BaseService # @return [String] # API key. Your API key identifies your project and provides you with API access, # quota, and reports. Required unless you provide an OAuth 2.0 token. attr_accessor :key # @return [String] # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. attr_accessor :quota_user def initialize super('https://gkehub.googleapis.com/', '', client_name: 'google-apis-gkehub_v1', client_version: Google::Apis::GkehubV1::GEM_VERSION) @batch_path = 'batch' end # Gets information about a location. # @param [String] name # Resource name for the location. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::Location] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::Location] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_project_location(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1/{+name}', options) command.response_representation = Google::Apis::GkehubV1::Location::Representation command.response_class = Google::Apis::GkehubV1::Location command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists information about the supported locations for this service. # @param [String] name # The resource that owns the locations collection, if applicable. # @param [String] filter # A filter to narrow down results to a preferred subset. The filtering language # accepts strings like "displayName=tokyo", and is documented in more detail in [ # AIP-160](https://google.aip.dev/160). # @param [Fixnum] page_size # The maximum number of results to return. If not set, the service selects a # default. # @param [String] page_token # A page token received from the `next_page_token` field in the response. Send # that page token to receive the subsequent page. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::ListLocationsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::ListLocationsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_project_locations(name, filter: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1/{+name}/locations', options) command.response_representation = Google::Apis::GkehubV1::ListLocationsResponse::Representation command.response_class = Google::Apis::GkehubV1::ListLocationsResponse command.params['name'] = name unless name.nil? command.query['filter'] = filter unless filter.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Gets the access control policy for a resource. Returns an empty policy if the # resource exists and does not have a policy set. # @param [String] resource # REQUIRED: The resource for which the policy is being requested. See the # operation documentation for the appropriate value for this field. # @param [Fixnum] options_requested_policy_version # Optional. The policy format version to be returned. Valid values are 0, 1, and # 3. Requests specifying an invalid value will be rejected. Requests for # policies with any conditional bindings must specify version 3. Policies # without any conditional bindings may specify any valid value or leave the # field unset. To learn which resources support conditions in their IAM policies, # see the [IAM documentation](https://cloud.google.com/iam/help/conditions/ # resource-policies). # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::Policy] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::Policy] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_project_location_feature_iam_policy(resource, options_requested_policy_version: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1/{+resource}:getIamPolicy', options) command.response_representation = Google::Apis::GkehubV1::Policy::Representation command.response_class = Google::Apis::GkehubV1::Policy command.params['resource'] = resource unless resource.nil? command.query['options.requestedPolicyVersion'] = options_requested_policy_version unless options_requested_policy_version.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Sets the access control policy on the specified resource. Replaces any # existing policy. Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and ` # PERMISSION_DENIED` errors. # @param [String] resource # REQUIRED: The resource for which the policy is being specified. See the # operation documentation for the appropriate value for this field. # @param [Google::Apis::GkehubV1::SetIamPolicyRequest] set_iam_policy_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::Policy] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::Policy] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def set_feature_iam_policy(resource, set_iam_policy_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1/{+resource}:setIamPolicy', options) command.request_representation = Google::Apis::GkehubV1::SetIamPolicyRequest::Representation command.request_object = set_iam_policy_request_object command.response_representation = Google::Apis::GkehubV1::Policy::Representation command.response_class = Google::Apis::GkehubV1::Policy command.params['resource'] = resource unless resource.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Returns permissions that a caller has on the specified resource. If the # resource does not exist, this will return an empty set of permissions, not a ` # NOT_FOUND` error. Note: This operation is designed to be used for building # permission-aware UIs and command-line tools, not for authorization checking. # This operation may "fail open" without warning. # @param [String] resource # REQUIRED: The resource for which the policy detail is being requested. See the # operation documentation for the appropriate value for this field. # @param [Google::Apis::GkehubV1::TestIamPermissionsRequest] test_iam_permissions_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::TestIamPermissionsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::TestIamPermissionsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def test_feature_iam_permissions(resource, test_iam_permissions_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1/{+resource}:testIamPermissions', options) command.request_representation = Google::Apis::GkehubV1::TestIamPermissionsRequest::Representation command.request_object = test_iam_permissions_request_object command.response_representation = Google::Apis::GkehubV1::TestIamPermissionsResponse::Representation command.response_class = Google::Apis::GkehubV1::TestIamPermissionsResponse command.params['resource'] = resource unless resource.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Creates a new Membership. **This is currently only supported for GKE clusters # on Google Cloud**. To register other clusters, follow the instructions at # https://cloud.google.com/anthos/multicluster-management/connect/registering-a- # cluster. # @param [String] parent # Required. The parent (project and location) where the Memberships will be # created. Specified in the format `projects/*/locations/*`. # @param [Google::Apis::GkehubV1::Membership] membership_object # @param [String] membership_id # Required. Client chosen ID for the membership. `membership_id` must be a valid # RFC 1123 compliant DNS label: 1. At most 63 characters in length 2. It must # consist of lower case alphanumeric characters or `-` 3. It must start and end # with an alphanumeric character Which can be expressed as the regex: `[a-z0-9]([ # -a-z0-9]*[a-z0-9])?`, with a maximum length of 63 characters. # @param [String] request_id # Optional. A request ID to identify requests. Specify a unique request ID so # that if you must retry your request, the server will know to ignore the # request if it has already been completed. The server will guarantee that for # at least 60 minutes after the first request. For example, consider a situation # where you make an initial request and the request times out. If you make the # request again with the same request ID, the server can check if original # operation with the same request ID was received, and if so, will ignore the # second request. This prevents clients from accidentally creating duplicate # commitments. The request ID must be a valid UUID with the exception that zero # UUID is not supported (00000000-0000-0000-0000-000000000000). # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::Operation] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::Operation] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def create_project_location_membership(parent, membership_object = nil, membership_id: nil, request_id: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1/{+parent}/memberships', options) command.request_representation = Google::Apis::GkehubV1::Membership::Representation command.request_object = membership_object command.response_representation = Google::Apis::GkehubV1::Operation::Representation command.response_class = Google::Apis::GkehubV1::Operation command.params['parent'] = parent unless parent.nil? command.query['membershipId'] = membership_id unless membership_id.nil? command.query['requestId'] = request_id unless request_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Removes a Membership. **This is currently only supported for GKE clusters on # Google Cloud**. To unregister other clusters, follow the instructions at https: # //cloud.google.com/anthos/multicluster-management/connect/unregistering-a- # cluster. # @param [String] name # Required. The Membership resource name in the format `projects/*/locations/*/ # memberships/*`. # @param [String] request_id # Optional. A request ID to identify requests. Specify a unique request ID so # that if you must retry your request, the server will know to ignore the # request if it has already been completed. The server will guarantee that for # at least 60 minutes after the first request. For example, consider a situation # where you make an initial request and the request times out. If you make the # request again with the same request ID, the server can check if original # operation with the same request ID was received, and if so, will ignore the # second request. This prevents clients from accidentally creating duplicate # commitments. The request ID must be a valid UUID with the exception that zero # UUID is not supported (00000000-0000-0000-0000-000000000000). # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::Operation] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::Operation] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def delete_project_location_membership(name, request_id: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:delete, 'v1/{+name}', options) command.response_representation = Google::Apis::GkehubV1::Operation::Representation command.response_class = Google::Apis::GkehubV1::Operation command.params['name'] = name unless name.nil? command.query['requestId'] = request_id unless request_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Generates the manifest for deployment of the GKE connect agent. **This method # is used internally by Google-provided libraries.** Most clients should not # need to call this method directly. # @param [String] name # Required. The Membership resource name the Agent will associate with, in the # format `projects/*/locations/*/memberships/*`. # @param [String] image_pull_secret_content # Optional. The image pull secret content for the registry, if not public. # @param [Boolean] is_upgrade # Optional. If true, generate the resources for upgrade only. Some resources # generated only for installation (e.g. secrets) will be excluded. # @param [String] namespace # Optional. Namespace for GKE Connect agent resources. Defaults to `gke-connect`. # The Connect Agent is authorized automatically when run in the default # namespace. Otherwise, explicit authorization must be granted with an # additional IAM binding. # @param [String] proxy # Optional. URI of a proxy if connectivity from the agent to gkeconnect. # googleapis.com requires the use of a proxy. Format must be in the form `http(s) # ://`proxy_address``, depending on the HTTP/HTTPS protocol supported by the # proxy. This will direct the connect agent's outbound traffic through a HTTP(S) # proxy. # @param [String] registry # Optional. The registry to fetch the connect agent image from. Defaults to gcr. # io/gkeconnect. # @param [String] version # Optional. The Connect agent version to use. Defaults to the most current # version. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::GenerateConnectManifestResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::GenerateConnectManifestResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def generate_project_location_membership_connect_manifest(name, image_pull_secret_content: nil, is_upgrade: nil, namespace: nil, proxy: nil, registry: nil, version: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1/{+name}:generateConnectManifest', options) command.response_representation = Google::Apis::GkehubV1::GenerateConnectManifestResponse::Representation command.response_class = Google::Apis::GkehubV1::GenerateConnectManifestResponse command.params['name'] = name unless name.nil? command.query['imagePullSecretContent'] = image_pull_secret_content unless image_pull_secret_content.nil? command.query['isUpgrade'] = is_upgrade unless is_upgrade.nil? command.query['namespace'] = namespace unless namespace.nil? command.query['proxy'] = proxy unless proxy.nil? command.query['registry'] = registry unless registry.nil? command.query['version'] = version unless version.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Gets the details of a Membership. # @param [String] name # Required. The Membership resource name in the format `projects/*/locations/*/ # memberships/*`. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::Membership] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::Membership] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_project_location_membership(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1/{+name}', options) command.response_representation = Google::Apis::GkehubV1::Membership::Representation command.response_class = Google::Apis::GkehubV1::Membership command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Gets the access control policy for a resource. Returns an empty policy if the # resource exists and does not have a policy set. # @param [String] resource # REQUIRED: The resource for which the policy is being requested. See the # operation documentation for the appropriate value for this field. # @param [Fixnum] options_requested_policy_version # Optional. The policy format version to be returned. Valid values are 0, 1, and # 3. Requests specifying an invalid value will be rejected. Requests for # policies with any conditional bindings must specify version 3. Policies # without any conditional bindings may specify any valid value or leave the # field unset. To learn which resources support conditions in their IAM policies, # see the [IAM documentation](https://cloud.google.com/iam/help/conditions/ # resource-policies). # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::Policy] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::Policy] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_project_location_membership_iam_policy(resource, options_requested_policy_version: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1/{+resource}:getIamPolicy', options) command.response_representation = Google::Apis::GkehubV1::Policy::Representation command.response_class = Google::Apis::GkehubV1::Policy command.params['resource'] = resource unless resource.nil? command.query['options.requestedPolicyVersion'] = options_requested_policy_version unless options_requested_policy_version.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists Memberships in a given project and location. # @param [String] parent # Required. The parent (project and location) where the Memberships will be # listed. Specified in the format `projects/*/locations/*`. # @param [String] filter # Optional. Lists Memberships that match the filter expression, following the # syntax outlined in https://google.aip.dev/160. Examples: - Name is `bar` in # project `foo-proj` and location `global`: name = "projects/foo-proj/locations/ # global/membership/bar" - Memberships that have a label called `foo`: labels. # foo:* - Memberships that have a label called `foo` whose value is `bar`: # labels.foo = bar - Memberships in the CREATING state: state = CREATING # @param [String] order_by # Optional. One or more fields to compare and use to sort the output. See https:/ # /google.aip.dev/132#ordering. # @param [Fixnum] page_size # Optional. When requesting a 'page' of resources, `page_size` specifies number # of resources to return. If unspecified or set to 0, all resources will be # returned. # @param [String] page_token # Optional. Token returned by previous call to `ListMemberships` which specifies # the position in the list from where to continue listing the resources. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::ListMembershipsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::ListMembershipsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_project_location_memberships(parent, filter: nil, order_by: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1/{+parent}/memberships', options) command.response_representation = Google::Apis::GkehubV1::ListMembershipsResponse::Representation command.response_class = Google::Apis::GkehubV1::ListMembershipsResponse command.params['parent'] = parent unless parent.nil? command.query['filter'] = filter unless filter.nil? command.query['orderBy'] = order_by unless order_by.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Updates an existing Membership. # @param [String] name # Required. The Membership resource name in the format `projects/*/locations/*/ # memberships/*`. # @param [Google::Apis::GkehubV1::Membership] membership_object # @param [String] request_id # Optional. A request ID to identify requests. Specify a unique request ID so # that if you must retry your request, the server will know to ignore the # request if it has already been completed. The server will guarantee that for # at least 60 minutes after the first request. For example, consider a situation # where you make an initial request and the request times out. If you make the # request again with the same request ID, the server can check if original # operation with the same request ID was received, and if so, will ignore the # second request. This prevents clients from accidentally creating duplicate # commitments. The request ID must be a valid UUID with the exception that zero # UUID is not supported (00000000-0000-0000-0000-000000000000). # @param [String] update_mask # Required. Mask of fields to update. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::Operation] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::Operation] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def patch_project_location_membership(name, membership_object = nil, request_id: nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:patch, 'v1/{+name}', options) command.request_representation = Google::Apis::GkehubV1::Membership::Representation command.request_object = membership_object command.response_representation = Google::Apis::GkehubV1::Operation::Representation command.response_class = Google::Apis::GkehubV1::Operation command.params['name'] = name unless name.nil? command.query['requestId'] = request_id unless request_id.nil? command.query['updateMask'] = update_mask unless update_mask.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Sets the access control policy on the specified resource. Replaces any # existing policy. Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and ` # PERMISSION_DENIED` errors. # @param [String] resource # REQUIRED: The resource for which the policy is being specified. See the # operation documentation for the appropriate value for this field. # @param [Google::Apis::GkehubV1::SetIamPolicyRequest] set_iam_policy_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::Policy] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::Policy] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def set_membership_iam_policy(resource, set_iam_policy_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1/{+resource}:setIamPolicy', options) command.request_representation = Google::Apis::GkehubV1::SetIamPolicyRequest::Representation command.request_object = set_iam_policy_request_object command.response_representation = Google::Apis::GkehubV1::Policy::Representation command.response_class = Google::Apis::GkehubV1::Policy command.params['resource'] = resource unless resource.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Returns permissions that a caller has on the specified resource. If the # resource does not exist, this will return an empty set of permissions, not a ` # NOT_FOUND` error. Note: This operation is designed to be used for building # permission-aware UIs and command-line tools, not for authorization checking. # This operation may "fail open" without warning. # @param [String] resource # REQUIRED: The resource for which the policy detail is being requested. See the # operation documentation for the appropriate value for this field. # @param [Google::Apis::GkehubV1::TestIamPermissionsRequest] test_iam_permissions_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::TestIamPermissionsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::TestIamPermissionsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def test_membership_iam_permissions(resource, test_iam_permissions_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1/{+resource}:testIamPermissions', options) command.request_representation = Google::Apis::GkehubV1::TestIamPermissionsRequest::Representation command.request_object = test_iam_permissions_request_object command.response_representation = Google::Apis::GkehubV1::TestIamPermissionsResponse::Representation command.response_class = Google::Apis::GkehubV1::TestIamPermissionsResponse command.params['resource'] = resource unless resource.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Starts asynchronous cancellation on a long-running operation. The server makes # a best effort to cancel the operation, but success is not guaranteed. If the # server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. # Clients can use Operations.GetOperation or other methods to check whether the # cancellation succeeded or whether the operation completed despite cancellation. # On successful cancellation, the operation is not deleted; instead, it becomes # an operation with an Operation.error value with a google.rpc.Status.code of 1, # corresponding to `Code.CANCELLED`. # @param [String] name # The name of the operation resource to be cancelled. # @param [Google::Apis::GkehubV1::CancelOperationRequest] cancel_operation_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::Empty] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::Empty] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def cancel_operation(name, cancel_operation_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1/{+name}:cancel', options) command.request_representation = Google::Apis::GkehubV1::CancelOperationRequest::Representation command.request_object = cancel_operation_request_object command.response_representation = Google::Apis::GkehubV1::Empty::Representation command.response_class = Google::Apis::GkehubV1::Empty command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Deletes a long-running operation. This method indicates that the client is no # longer interested in the operation result. It does not cancel the operation. # If the server doesn't support this method, it returns `google.rpc.Code. # UNIMPLEMENTED`. # @param [String] name # The name of the operation resource to be deleted. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::Empty] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::Empty] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def delete_project_location_operation(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:delete, 'v1/{+name}', options) command.response_representation = Google::Apis::GkehubV1::Empty::Representation command.response_class = Google::Apis::GkehubV1::Empty command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Gets the latest state of a long-running operation. Clients can use this method # to poll the operation result at intervals as recommended by the API service. # @param [String] name # The name of the operation resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::Operation] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::Operation] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_project_location_operation(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1/{+name}', options) command.response_representation = Google::Apis::GkehubV1::Operation::Representation command.response_class = Google::Apis::GkehubV1::Operation command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists operations that match the specified filter in the request. If the server # doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` # binding allows API services to override the binding to use different resource # name schemes, such as `users/*/operations`. To override the binding, API # services can add a binding such as `"/v1/`name=users/*`/operations"` to their # service configuration. For backwards compatibility, the default name includes # the operations collection id, however overriding users must ensure the name # binding is the parent resource, without the operations collection id. # @param [String] name # The name of the operation's parent resource. # @param [String] filter # The standard list filter. # @param [Fixnum] page_size # The standard list page size. # @param [String] page_token # The standard list page token. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::GkehubV1::ListOperationsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::GkehubV1::ListOperationsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_project_location_operations(name, filter: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1/{+name}/operations', options) command.response_representation = Google::Apis::GkehubV1::ListOperationsResponse::Representation command.response_class = Google::Apis::GkehubV1::ListOperationsResponse command.params['name'] = name unless name.nil? command.query['filter'] = filter unless filter.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end protected def apply_command_defaults(command) command.query['key'] = key unless key.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? end end end end end
63.135802
229
0.676339
ff8e12f281449b729117bd45bd52436ad605bffb
1,143
$:.push File.expand_path('../lib', __FILE__) require 'backport_yield_self/version' Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'backport_yield_self' s.summary = 'backport_yield_self is the backport of Kernel#yield_self in Ruby 2.5 to older Ruby versions.' s.version = BackportYieldSelf::VERSION s.licenses = 'MIT' s.authors = ['Koichi ITO'] s.email = '[email protected]' s.homepage = 'https://github.com/koic/backport_yield_self' s.require_paths = ['lib'] s.extensions = ['ext/backport_yield_self/extconf.rb'] s.files = [ 'Manifest.txt', 'README.md', 'Rakefile', 'ext/backport_yield_self/extconf.rb', 'ext/backport_yield_self/backport_yield_self.c', 'lib/backport_yield_self.rb' ] s.required_ruby_version = ['>= 2.2.0', '< 2.5.0'] s.post_install_message = <<-EOS backport_yield_self is the backport of Kernel#yield_self in Ruby 2.5 to older Ruby versions. The best way is to use Ruby 2.5 or later. Thanks. EOS s.add_development_dependency('hoe') s.add_development_dependency('rake-compiler') s.add_development_dependency('rspec', '>= 3.0.0') end
28.575
108
0.708661
62a933b2239e87b75d4db56c141acd7d2844f85f
479
class TravelLeisure::Scraper def self.get_page Nokogiri::HTML(open("https://www.travelandleisure.com/travel-guide")) end def self.scrape_destinations destinations = get_page.css("ul.grid li") destinations.collect do |destination| destination_hash = { city: destination.css("span.grid__item__title").text, country: destination.css("span.grid__item__cat").text, url: destination.css("a").attribute("href") } end end end
28.176471
73
0.686848
e8b21684b24a4311e54b460a04764186adc90f65
1,591
class Libsodium < Formula desc "NaCl networking and cryptography library" homepage "https://libsodium.org/" url "https://download.libsodium.org/libsodium/releases/libsodium-1.0.18.tar.gz" sha256 "6f504490b342a4f8a4c4a02fc9b866cbef8622d5df4e5452b46be121e46636c1" license "ISC" revision 1 livecheck do url "https://download.libsodium.org/libsodium/releases/" regex(/href=.*?libsodium[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do cellar :any sha256 "db372521cd0b1861a5b578bee22426f3a1f4f7cb3c382be1f842da4715dc65bd" => :catalina sha256 "55245bfcf6654b0914d3f7459b99a08c54ef2560587bf583a1c1aff4cfc81f28" => :mojave sha256 "fc972755eb60f4221d7b32e58fc0f94e99b913fefefc84c4c76dc4bca1c5c445" => :high_sierra sha256 "f7a0d2d788866c83dfe70624ea4e990a1c9a055f89d07ab3556dafb14e1d5931" => :x86_64_linux end head do url "https://github.com/jedisct1/libsodium.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end def install system "./autogen.sh" if build.head? system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "check" system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <assert.h> #include <sodium.h> int main() { assert(sodium_init() != -1); return 0; } EOS system ENV.cc, "test.c", "-I#{include}", "-L#{lib}", "-lsodium", "-o", "test" system "./test" end end
29.462963
94
0.661848
913865c5f285842a875683feae0cbe004287db77
21
require 'esnek/base'
10.5
20
0.761905
879f86a3979508704ab42b14b576f56d51336ebe
236
# frozen_string_literal: true module Unused module Integration module CsvOutput class Child < Parent # override parent method def base_method; end def unused_method; end end end end end
15.733333
32
0.648305
1c2c4f836c1307c34d8bf86bc256a276f1879f3c
3,612
require 'thor' require "dokku_cli/version" require "dokku_cli/config" require "dokku_cli/domains" require "dokku_cli/nginx" require "dokku_cli/ps" require "dokku_cli/events" require "dokku_cli/certs" require "dokku_cli/keys" module DokkuCli class Cli < Thor class_option :remote desc "logs [-n num] [-p ps] [-q quiet [-t tail]", "Display logs for the app" method_option :n, type: :numeric, aliases: %w{-num --num}, desc: "Limit to <n> number of lines" method_option :p, type: :string, aliases: %w{-ps --ps}, desc: "Filter by <p> process" method_option :q, type: :boolean, aliases: %w{-quiet --quiet}, desc: "Remove docker prefixes from output" method_option :t, type: :boolean, aliases: %w{-tail --tail}, desc: "Follow output" def logs args = options.map{|k, v| "-#{k} #{v}"}.join(" ") if args.empty? run_command "logs #{app_name}" else # remove unnecessary mapped remote option args = args.gsub(/-remote [\S]*/, '') command = "ssh -t -p #{port} dokku@#{domain} logs #{app_name} #{args}" puts "Running #{command}..." exec(command) end end desc "open", "Open the app in your default browser" def open url = %x[dokku urls --remote #{app_name}].split("\r").first exec("open #{url}") end desc "run <cmd>", "Run a one-off command in the environment of the app" def walk(*args) command = "#{args.join(' ')}" case command.gsub(" ", "") when "rakedb:drop" puts "You cannot use `rake db:drop`. Use Dokku directly to delete the database." when "rakedb:create" puts "You cannot use `rake db:create`. Use Dokku directly to create the database." else run_command "run #{app_name} #{command}" end end map "run" => "walk" desc "ssh", "Start an SSH session as root user" def ssh command = "ssh -p #{port} root@#{domain}" puts "Running #{command}..." exec(command) end desc "url", "Show the first URL for the app" def url run_command "url #{app_name}" end desc "urls", "Show all URLs for the app" def urls run_command "urls #{app_name}" end def help(method = nil) method = "walk" if method == "run" super end private def app_name @app_name ||= git_config["app_name"] end def domain @domain ||= git_config["domain"] end def port @port ||= git_config["port"] end def git_config remote = "dokku" remote = options[:remote] if options[:remote] @git_config ||= begin config_path = File.join(Dir.pwd, ".git", "config") exit unless File.exist?(config_path) config_file = File.read(config_path) # Default dokku config: [email protected]:app default_style_regex = /\[remote "#{remote}"\]\s+url \= dokku@(?<domain>.*):(?<app_name>.*)$/ match ||= config_file.match(default_style_regex) # SSH dokku config: ssh://[email protected]:1337/app ssh_style_regex = /\[remote "#{remote}"\]\s+url \= ssh:\/\/dokku@(?<domain>.*):(?<port>.*)\/(?<app_name>.*)$/ match ||= config_file.match(ssh_style_regex) exit unless match match = Hash[match.names.zip(match.captures)] match["port"] ||= 22 match end end def run_command(command) command = command.gsub(/ --remote=[\S]*/, '') dokku_command = "ssh -t -p #{port} dokku@#{domain} #{command}" puts "Running #{dokku_command}..." exec(dokku_command) end end end
28.21875
117
0.587209
e847654f6ccd588a67d8748cbee32a9d2fb076f8
2,866
# encoding: UTF-8 # # 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. # # kubernetes master default['kube']['api']['host'] = '' default['kube']['api']['bind-address'] = '0.0.0.0' default['kube']['api']['bind-port'] = node.kubernetes.api_port default['kube']['api']['bind-port-secure'] = node.kubernetes.api_port_secure default['kube']['service']['addresses'] = node.kubernetes.service_addresses default['kube']['scheduler']['args'] = '' controller_manager_args_value = '' if node.kubernetes.has_key?("controller_manager_args") args = JSON.parse(node.kubernetes.controller_manager_args) args.each_pair do |k,v| Chef::Log.info("setting controller_manager arg: --#{k}=#{v}") controller_manager_args_value += " --#{k}=#{v}" end end node.set['kube']['controller-manager']['args'] = controller_manager_args_value.strip scheduler_args_value = '' if node.kubernetes.has_key?("scheduler_args") args = JSON.parse(node.kubernetes.scheduler_args) args.each_pair do |k,v| Chef::Log.info("setting scheduler arg: --#{k}=#{v}") scheduler_args_value += " --#{k}=#{v}" end end node.set['kube']['scheduler']['args'] = scheduler_args_value.strip api_args_value = '' if node.kubernetes.has_key?("api_args") args = JSON.parse(node.kubernetes.api_args) args.each_pair do |k,v| Chef::Log.info("setting api arg: --#{k}=#{v}") api_args_value += " --#{k}=#{v}" end end node.set['kube']['api']['args'] = api_args_value.strip # kubernetes nodes default['kube']['kubelet']['machines'] = [] default['kube']['kubelet']['bind-address'] = '0.0.0.0' default['kube']['kubelet']['bind-port'] = '10250' kubelet_args_value = '' if node.kubernetes.has_key?("kubelet_args") kubelet_args = JSON.parse(node.kubernetes.kubelet_args) kubelet_args.each_pair do |k,v| Chef::Log.info("setting kubelet arg: --#{k}=#{v}") kubelet_args_value += " --#{k}=#{v}" end end node.set['kube']['kubelet']['args'] = kubelet_args_value.strip proxy_args_value = '' if node.kubernetes.has_key?("proxy_args") proxy_args = JSON.parse(node.kubernetes.proxy_args) proxy_args.each_pair do |k,v| Chef::Log.info("setting proxy arg: --#{k}=#{v}") proxy_args_value += " --#{k}=#{v}" end end node.set['kube']['proxy']['args'] = proxy_args_value.strip default['kube']['interface'] = 'eth0' # related packages default['kube']['go']['package'] = 'golang'
32.942529
84
0.687369
1daad6d270319f4880af223b6d0eeda87cebfa5f
169
require 'html/sanitizer' module SanitizeHelper def strip_tags(html) (@full_sanitizer ||= HTML::FullSanitizer.new).sanitize(html) end end World(SanitizeHelper)
16.9
64
0.757396
ed47f96072c567359f2bc83add77774bc999a8e4
406
module Beacon module States # Wait 5 intervals. class Five def call blink wait next_state end private def blink Leds.blink! 5 end def wait Log.debug { "Waiting because I'll retry in 5 intervals" } Sleep.call Beacon.config.delay end def next_state States::Four end end end end
14.5
65
0.534483
e28486239eebfc9e05fdd4e3e97e3ed6eb4bd91e
362
class CreateSamuraiContactsContacts < ActiveRecord::Migration[5.1] def change create_table :samurai_contacts_contacts do |t| t.string :first_name t.string :last_name t.string :company t.string :email t.string :phone t.references :user, foreign_key: {to_table: :samurai_users} t.timestamps end end end
24.133333
66
0.674033
26ff3ef9f765f009caea050b877ec549d609e3e6
512
require 'reach/extensions/git' module Reach module Extension module Yarn def yarn_install(force = false) requires_setting :deploy_to if force || files_have_changes?(%w[package.json yarn.lock]) within fetch(:deploy_to) do execute :yarn, 'install', '--production' end true else false end end def yarn_install! yarn_install(force = true) end end end helpers Extension::Yarn end
17.066667
67
0.578125
015aca8161942bab4623cf7cbafe7c1a4d957d89
1,211
require './lib/second_curtain/path_utils.rb' describe PathUtils do before(:each) do end describe "composing a path" do it "yields a concatenation of these components without leading and trailing slashes" do expect(PathUtils.pathWithComponents(["component1", "component2"])).to eq("component1/component2") end it "yields a concatenation of these components without leading and trailing slashes" do expect(PathUtils.pathWithComponents(["/component1/component1b/", "/component2/"])).to eq("component1/component1b/component2") end it "yields an empty string when called without components" do expect(PathUtils.pathWithComponents([])).to eq("") end it "yields a string without leading slash when called with an empty first component" do expect(PathUtils.pathWithComponents(["", "/component2"])).to eq("component2") end it "yields a string without trailing slash when called with an empty last component" do expect(PathUtils.pathWithComponents(["component1", ""])).to eq("component1") end it "yields an empty string when called with a single slash" do expect(PathUtils.pathWithComponents(["/"])).to eq("") end end end
36.69697
131
0.717589