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
bf0d3df4edb87bbaa4be02237b654afc34b78a3b
278
{ 'info' => { 'api_server' => 'https://test.kineticdata.com/kinetic', 'api_username' => 'admin', 'api_password' => '', 'enable_debug_logging'=>'yes' }, 'parameters' => { 'error_handling' => 'Error Message', 'space_slug' => 'test' } }
21.384615
60
0.52518
bba9246c1127957fb0f3518180085b3329e7d50d
1,255
class Sentencepiece < Formula desc "Unsupervised text tokenizer and detokenizer" homepage "https://github.com/google/sentencepiece" url "https://github.com/google/sentencepiece/archive/v0.1.94.tar.gz" sha256 "a23133caa67c38c3bf7f978fcea07947072783b32554a034cbbe99a8cf776192" license "Apache-2.0" head "https://github.com/google/sentencepiece.git" livecheck do url "https://github.com/google/sentencepiece/releases/latest" regex(%r{href=.*?/tag/v?(\d+(?:\.\d+)+)["' >]}i) end bottle do sha256 "34eaf54eed2f033c154575c04b517742dea72d9fdba2d80515348acb9afb8793" => :catalina sha256 "367c727302ab46993a8604b21f4276d051bb06e17dd91b27252639abee05d84b" => :mojave sha256 "81a320ad4d6d5c92493f471735bc50fc38ca580d97dd4c710928e743f48d3841" => :high_sierra sha256 "ed294aeb6f0eda9ede6ee61c8ffd8d66641819581c30d75585c009d2e9ef7992" => :x86_64_linux end depends_on "cmake" => :build def install mkdir "build" do system "cmake", "..", *std_cmake_args system "make" system "make", "install" end pkgshare.install "data" end test do cp (pkgshare/"data/botchan.txt"), testpath system "#{bin}/spm_train", "--input=botchan.txt", "--model_prefix=m", "--vocab_size=1000" end end
33.918919
94
0.732271
391b60150f4ba52f2dd34154646365cfa18df9f0
1,085
require_relative 'module' require 'spaceship' module Deliver # Set the app's pricing class UploadPriceTier def upload(options) return unless options[:price_tier] price_tier = options[:price_tier].to_s legacy_app = options[:app] app_id = legacy_app.apple_id app = Spaceship::ConnectAPI::App.get(app_id: app_id) attributes = {} territory_ids = [] app_prices = app.fetch_app_prices if app_prices.first old_price = app_prices.first.price_tier.id else UI.message("App has no prices yet... Enabling all countries in App Store Connect") territory_ids = Spaceship::ConnectAPI::Territory.all.map(&:id) attributes[:availableInNewTerritories] = true end if price_tier == old_price UI.success("Price Tier unchanged (tier #{old_price})") return end app.update(attributes: attributes, app_price_tier_id: price_tier, territory_ids: territory_ids) UI.success("Successfully updated the pricing from #{old_price} to #{price_tier}") end end end
28.552632
101
0.677419
d597b3d8174651f614a84cfc88d8e13fcee540ca
1,200
class OrganisationDefaultStringValues < ActiveRecord::Migration[4.2] ATTRS = %i[ name address postcode email description website telephone donation_info ] def up ATTRS.each do |attr| Organisation.table_name = "organisations" Organisation.with_deleted.where(attr => nil).update_all(attr => "") ProposedOrganisationEdit.with_deleted.where(attr => nil).update_all(attr => "") change_column_default(:organisations, attr, "") change_column_null(:organisations, attr, false) change_column_default(:proposed_organisation_edits, attr, "") change_column_null(:proposed_organisation_edits, attr, false) end end def down ATTRS.each do |attr| change_column_default(:organisations, attr, nil) change_column_null(:organisations, attr, true) change_column_default(:proposed_organisation_edits, attr, nil) change_column_null(:proposed_organisation_edits, attr, true) Organisation.table_name = "organisations" Organisation.with_deleted.where(attr => "").update_all(attr => nil) ProposedOrganisationEdit.with_deleted.where(attr => "").update_all(attr => nil) end end end
31.578947
85
0.71
1cace66f35eb454d1852fbe030755fcfe8ac913b
1,395
require 'oauth/request_proxy/base' require 'curb' require 'uri' require 'cgi' module OAuth::RequestProxy::Curl class Easy < OAuth::RequestProxy::Base # Proxy for signing Curl::Easy requests # Usage example: # oauth_params = {:consumer => oauth_consumer, :token => access_token} # req = Curl::Easy.new(uri) # oauth_helper = OAuth::Client::Helper.new(req, oauth_params.merge(:request_uri => uri)) # req.headers.merge!({"Authorization" => oauth_helper.header}) # req.http_get # response = req.body_str proxies ::Curl::Easy def method nil end def uri options[:uri].to_s end def parameters if options[:clobber_request] options[:parameters] else post_parameters.merge(query_parameters).merge(options[:parameters] || {}) end end private def query_parameters query = URI.parse(request.url).query return(query ? CGI.parse(query) : {}) end def post_parameters post_body = {} # Post params are only used if posting form data if (request.headers['Content-Type'] && request.headers['Content-Type'].to_s.downcase.start_with?("application/x-www-form-urlencoded")) request.post_body.split("&").each do |str| param = str.split("=") post_body[param[0]] = param[1] end end post_body end end end
24.910714
140
0.632258
088ac3ac190b14845376bef04d11b72f4c2ce2d0
846
require 'spec_helper' describe "project_products/new" do before(:each) do assign(:project_product, stub_model(ProjectProduct, :project => nil, :product => nil, :quantity => 1, :subtotal => 1 ).as_new_record) end it "renders new project_product form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form[action=?][method=?]", project_products_path, "post" do assert_select "input#project_product_project[name=?]", "project_product[project]" assert_select "input#project_product_product[name=?]", "project_product[product]" assert_select "input#project_product_quantity[name=?]", "project_product[quantity]" assert_select "input#project_product_subtotal[name=?]", "project_product[subtotal]" end end end
33.84
89
0.708038
394568ad3fb0fb0a88e7985868c032a8dd52e6cd
21
class PlayerHand end
7
16
0.857143
aca18c903b104fcc38d87fb398d5e6c39ecad911
3,070
require './vtparse_tables.rb' class String def pad(len) self << (" " * (len - self.length)) end end File.open("vtparse_table.h", "w") { |f| f.puts "typedef enum {" $states_in_order.each_with_index { |state, i| f.puts " VTPARSE_STATE_#{state.to_s.upcase} = #{i+1}," } f.puts "} vtparse_state_t;" f.puts f.puts "typedef enum {" $actions_in_order.each_with_index { |action, i| f.puts " VTPARSE_ACTION_#{action.to_s.upcase} = #{i+1}," } f.puts "} vtparse_action_t;" f.puts f.puts "typedef unsigned char state_change_t;" f.puts "extern state_change_t STATE_TABLE[#{$states_in_order.length}][256];" f.puts "extern vtparse_action_t ENTRY_ACTIONS[#{$states_in_order.length}];" f.puts "extern vtparse_action_t EXIT_ACTIONS[#{$states_in_order.length}];" f.puts "extern char *ACTION_NAMES[#{$actions_in_order.length+1}];" f.puts "extern char *STATE_NAMES[#{$states_in_order.length+1}];" f.puts } puts "Wrote vtparse_table.h" File.open("vtparse_table.c", "w") { |f| f.puts f.puts '#include "vtparse_table.h"' f.puts f.puts "char *ACTION_NAMES[] = {" f.puts " \"<no action>\"," $actions_in_order.each { |action| f.puts " \"#{action.to_s.upcase}\"," } f.puts "};" f.puts f.puts "char *STATE_NAMES[] = {" f.puts " \"<no state>\"," $states_in_order.each { |state| f.puts " \"#{state.to_s}\"," } f.puts "};" f.puts f.puts "state_change_t STATE_TABLE[#{$states_in_order.length}][256] = {" $states_in_order.each_with_index { |state, i| f.puts " { /* VTPARSE_STATE_#{state.to_s.upcase} = #{i} */" $state_tables[state].each_with_index { |state_change, i| if not state_change f.puts " 0," else (action,) = state_change.find_all { |s| s.kind_of?(Symbol) } (state,) = state_change.find_all { |s| s.kind_of?(StateTransition) } action_str = action ? "VTPARSE_ACTION_#{action.to_s.upcase}" : "0" state_str = state ? "VTPARSE_STATE_#{state.to_state.to_s}" : "0" f.puts "/*#{i.to_s.pad(3)}*/ #{action_str.pad(33)} | (#{state_str.pad(33)} << 4)," end } f.puts " }," } f.puts "};" f.puts f.puts "vtparse_action_t ENTRY_ACTIONS[] = {" $states_in_order.each { |state| actions = $states[state] if actions[:on_entry] f.puts " VTPARSE_ACTION_#{actions[:on_entry].to_s.upcase}, /* #{state} */" else f.puts " 0 /* none for #{state} */," end } f.puts "};" f.puts f.puts "vtparse_action_t EXIT_ACTIONS[] = {" $states_in_order.each { |state| actions = $states[state] if actions[:on_exit] f.puts " VTPARSE_ACTION_#{actions[:on_exit].to_s.upcase}, /* #{state} */" else f.puts " 0 /* none for #{state} */," end } f.puts "};" f.puts } puts "Wrote vtparse_table.c"
31.649485
99
0.558958
61e6426c57d82b73b9f29118608c9b8ae623858b
588
require "europa_rates/version" require "europa_rates/configuration" require "europa_rates/exchange_rate" require "europa_rates/store" require "europa_rates/stores/file_store" require "europa_rates/stores/redis_store" require "europa_rates/errors/invalid_store_error" require "europa_rates/errors/no_data_available_error" module EuropaRates class << self attr_writer :configuration end def self.configuration @configuration ||= Configuration.new end def self.reset @configuration = Configuration.new end def self.configure yield(configuration) end end
21
53
0.792517
08e23015dcff608f9b7ac5b27241f9eb82c9917b
25,739
require 'test/unit' require 'date' class TestSH < Test::Unit::TestCase def test_new [Date.new, Date.civil, DateTime.new, DateTime.civil ].each do |d| assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) end [Date.new(2001), Date.civil(2001), DateTime.new(2001), DateTime.civil(2001) ].each do |d| assert_equal([2001, 1, 1], [d.year, d.mon, d.mday]) end d = Date.new(2001, 2, 3) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) d = Date.new(2001, 2, Rational('3.5')) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) d = Date.new(2001,2, 3, Date::JULIAN) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) d = Date.new(2001,2, 3, Date::GREGORIAN) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) d = Date.new(2001,-12, -31) assert_equal([2001, 1, 1], [d.year, d.mon, d.mday]) d = Date.new(2001,-12, -31, Date::JULIAN) assert_equal([2001, 1, 1], [d.year, d.mon, d.mday]) d = Date.new(2001,-12, -31, Date::GREGORIAN) assert_equal([2001, 1, 1], [d.year, d.mon, d.mday]) d = DateTime.new(2001, 2, 3, 4, 5, 6) assert_equal([2001, 2, 3, 4, 5, 6, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.new(2001, 2, 3, 4, 5, 6, 0) assert_equal([2001, 2, 3, 4, 5, 6, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.new(2001, 2, 3, 4, 5, 6, Rational(9,24)) assert_equal([2001, 2, 3, 4, 5, 6, Rational(9,24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.new(2001, 2, 3, 4, 5, 6, 0.375) assert_equal([2001, 2, 3, 4, 5, 6, Rational(9,24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.new(2001, 2, 3, 4, 5, 6, '+09:00') assert_equal([2001, 2, 3, 4, 5, 6, Rational(9,24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.new(2001, 2, 3, 4, 5, 6, '-09:00') assert_equal([2001, 2, 3, 4, 5, 6, Rational(-9,24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.new(2001, -12, -31, -4, -5, -6, '-09:00') assert_equal([2001, 1, 1, 20, 55, 54, Rational(-9,24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.new(2001, -12, -31, -4, -5, -6, '-09:00', Date::JULIAN) assert_equal([2001, 1, 1, 20, 55, 54, Rational(-9,24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.new(2001, -12, -31, -4, -5, -6, '-09:00', Date::GREGORIAN) assert_equal([2001, 1, 1, 20, 55, 54, Rational(-9,24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) end def test_jd d = Date.jd assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) d = Date.jd(0) assert_equal([-4712, 1, 1], [d.year, d.mon, d.mday]) d = Date.jd(2451944) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) d = DateTime.jd assert_equal([-4712, 1, 1, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.jd(0) assert_equal([-4712, 1, 1, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.jd(2451944) assert_equal([2001, 2, 3, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.jd(2451944, 4, 5, 6) assert_equal([2001, 2, 3, 4, 5, 6, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.jd(2451944, 4, 5, 6, 0) assert_equal([2001, 2, 3, 4, 5, 6, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.jd(2451944, 4, 5, 6, '+9:00') assert_equal([2001, 2, 3, 4, 5, 6, Rational(9, 24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.jd(2451944, -4, -5, -6, '-9:00') assert_equal([2001, 2, 3, 20, 55, 54, Rational(-9, 24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) end def test_ordinal d = Date.ordinal assert_equal([-4712, 1], [d.year, d.yday]) d = Date.ordinal(-4712, 1) assert_equal([-4712, 1], [d.year, d.yday]) d = Date.ordinal(2001, 2) assert_equal([2001, 2], [d.year, d.yday]) d = Date.ordinal(2001, 2, Date::JULIAN) assert_equal([2001, 2], [d.year, d.yday]) d = Date.ordinal(2001, 2, Date::GREGORIAN) assert_equal([2001, 2], [d.year, d.yday]) d = Date.ordinal(2001, -2, Date::JULIAN) assert_equal([2001, 364], [d.year, d.yday]) d = Date.ordinal(2001, -2, Date::GREGORIAN) assert_equal([2001, 364], [d.year, d.yday]) d = DateTime.ordinal assert_equal([-4712, 1, 1, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.ordinal(-4712, 1) assert_equal([-4712, 1, 1, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.ordinal(2001, 34) assert_equal([2001, 2, 3, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.ordinal(2001, 34, 4, 5, 6) assert_equal([2001, 2, 3, 4, 5, 6, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.ordinal(2001, 34, 4, 5, 6, 0) assert_equal([2001, 2, 3, 4, 5, 6, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.ordinal(2001, 34, 4, 5, 6, '+9:00') assert_equal([2001, 2, 3, 4, 5, 6, Rational(9, 24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.ordinal(2001, 34, -4, -5, -6, '-9:00') assert_equal([2001, 2, 3, 20, 55, 54, Rational(-9, 24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) end def test_commercial d = Date.commercial assert_equal([-4712, 1, 1], [d.cwyear, d.cweek, d.cwday]) d = Date.commercial(-4712, 1, 1) assert_equal([-4712, 1, 1], [d.cwyear, d.cweek, d.cwday]) d = Date.commercial(2001, 2, 3) assert_equal([2001, 2, 3], [d.cwyear, d.cweek, d.cwday]) d = Date.commercial(2001, 2, 3, Date::JULIAN) assert_equal([2001, 2, 3], [d.cwyear, d.cweek, d.cwday]) d = Date.commercial(2001, 2, 3, Date::GREGORIAN) assert_equal([2001, 2, 3], [d.cwyear, d.cweek, d.cwday]) d = Date.commercial(2001, -2, -3) assert_equal([2001, 51, 5], [d.cwyear, d.cweek, d.cwday]) d = Date.commercial(2001, -2, -3, Date::JULIAN) assert_equal([2001, 51, 5], [d.cwyear, d.cweek, d.cwday]) d = Date.commercial(2001, -2, -3, Date::GREGORIAN) assert_equal([2001, 51, 5], [d.cwyear, d.cweek, d.cwday]) d = DateTime.commercial assert_equal([-4712, 1, 1, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.commercial(-4712, 1, 1) assert_equal([-4712, 1, 1, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.commercial(2001, 5, 6) assert_equal([2001, 2, 3, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.commercial(2001, 5, 6, 4, 5, 6) assert_equal([2001, 2, 3, 4, 5, 6, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.commercial(2001, 5, 6, 4, 5, 6, 0) assert_equal([2001, 2, 3, 4, 5, 6, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.commercial(2001, 5, 6, 4, 5, 6, '+9:00') assert_equal([2001, 2, 3, 4, 5, 6, Rational(9, 24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.commercial(2001, 5, 6, -4, -5, -6, '-9:00') assert_equal([2001, 2, 3, 20, 55, 54, Rational(-9, 24)], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) end def test_fractional d = Date.jd(2451944.0) assert_equal(2451944, d.jd) d = Date.jd(Rational(2451944)) assert_equal(2451944, d.jd) d = Date.jd(2451944.5) assert_equal([2451944, 12], [d.jd, d.send('hour')]) d = Date.jd(Rational('2451944.5')) assert_equal([2451944, 12], [d.jd, d.send('hour')]) d = Date.civil(2001, 2, 3.0) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) d = Date.civil(2001, 2, Rational(3)) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) d = Date.civil(2001, 2, 3.5) assert_equal([2001, 2, 3, 12], [d.year, d.mon, d.mday, d.send('hour')]) d = Date.civil(2001, 2, Rational('3.5')) assert_equal([2001, 2, 3, 12], [d.year, d.mon, d.mday, d.send('hour')]) d = Date.ordinal(2001, 2.0) assert_equal([2001, 2], [d.year, d.yday]) d = Date.ordinal(2001, Rational(2)) assert_equal([2001, 2], [d.year, d.yday]) d = Date.commercial(2001, 2, 3.0) assert_equal([2001, 2, 3], [d.cwyear, d.cweek, d.cwday]) d = Date.commercial(2001, 2, Rational(3)) assert_equal([2001, 2, 3], [d.cwyear, d.cweek, d.cwday]) d = DateTime.jd(2451944.0) assert_equal(2451944, d.jd) d = DateTime.jd(Rational(2451944)) assert_equal(2451944, d.jd) d = DateTime.jd(2451944.5) assert_equal([2451944, 12], [d.jd, d.hour]) d = DateTime.jd(Rational('2451944.5')) assert_equal([2451944, 12], [d.jd, d.hour]) d = DateTime.civil(2001, 2, 3.0) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) d = DateTime.civil(2001, 2, Rational(3)) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) d = DateTime.civil(2001, 2, 3.5) assert_equal([2001, 2, 3, 12], [d.year, d.mon, d.mday, d.hour]) d = DateTime.civil(2001, 2, Rational('3.5')) assert_equal([2001, 2, 3, 12], [d.year, d.mon, d.mday, d.hour]) d = DateTime.civil(2001, 2, 3, 4.5) assert_equal([2001, 2, 3, 4, 30], [d.year, d.mon, d.mday, d.hour, d.min]) d = DateTime.civil(2001, 2, 3, Rational('4.5')) assert_equal([2001, 2, 3, 4, 30], [d.year, d.mon, d.mday, d.hour, d.min]) d = DateTime.civil(2001, 2, 3, 4, 5.5) assert_equal([2001, 2, 3, 4, 5, 30], [d.year, d.mon, d.mday, d.hour, d.min, d.sec]) d = DateTime.civil(2001, 2, 3, 4, Rational('5.5')) assert_equal([2001, 2, 3, 4, 5, 30], [d.year, d.mon, d.mday, d.hour, d.min, d.sec]) d = DateTime.ordinal(2001, 2.0) assert_equal([2001, 2], [d.year, d.yday]) d = DateTime.ordinal(2001, Rational(2)) assert_equal([2001, 2], [d.year, d.yday]) d = DateTime.commercial(2001, 2, 3.0) assert_equal([2001, 2, 3], [d.cwyear, d.cweek, d.cwday]) d = DateTime.commercial(2001, 2, Rational(3)) assert_equal([2001, 2, 3], [d.cwyear, d.cweek, d.cwday]) end def test_canon24oc d = DateTime.jd(2451943,24) assert_equal([2001, 2, 3, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.ordinal(2001,33,24) assert_equal([2001, 2, 3, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.new(2001,2,2,24) assert_equal([2001, 2, 3, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) d = DateTime.commercial(2001,5,5,24) assert_equal([2001, 2, 3, 0, 0, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset]) end def test_zone d = Date.new(2001, 2, 3) assert_equal(Encoding::US_ASCII, d.send(:zone).encoding) d = DateTime.new(2001, 2, 3) assert_equal(Encoding::US_ASCII, d.send(:zone).encoding) end def test_to_s d = Date.new(2001, 2, 3) assert_equal(Encoding::US_ASCII, d.to_s.encoding) assert_equal(Encoding::US_ASCII, d.strftime.encoding) d = DateTime.new(2001, 2, 3) assert_equal(Encoding::US_ASCII, d.to_s.encoding) assert_equal(Encoding::US_ASCII, d.strftime.encoding) end def test_inspect d = Date.new(2001, 2, 3) assert_equal(Encoding::US_ASCII, d.inspect.encoding) d = DateTime.new(2001, 2, 3) assert_equal(Encoding::US_ASCII, d.inspect.encoding) end def test_strftime assert_raise(Errno::ERANGE) do Date.today.strftime('%100000z') end assert_raise(Errno::ERANGE) do Date.new(1 << 10000).strftime('%Y') end assert_equal('-3786825600', Date.new(1850).strftime('%s')) assert_equal('-3786825600000', Date.new(1850).strftime('%Q')) end def test_cmp assert_equal(-1, Date.new(2001,2,3) <=> Date.new(2001,2,4)) assert_equal(0, Date.new(2001,2,3) <=> Date.new(2001,2,3)) assert_equal(1, Date.new(2001,2,3) <=> Date.new(2001,2,2)) assert_equal(-1, Date.new(2001,2,3) <=> 2451944.0) assert_equal(-1, Date.new(2001,2,3) <=> 2451944) assert_equal(0, Date.new(2001,2,3) <=> 2451943.5) assert_equal(1, Date.new(2001,2,3) <=> 2451943.0) assert_equal(1, Date.new(2001,2,3) <=> 2451943) assert_equal(-1, Date.new(2001,2,3) <=> Rational('4903888/2')) assert_equal(0, Date.new(2001,2,3) <=> Rational('4903887/2')) assert_equal(1, Date.new(2001,2,3) <=> Rational('4903886/2')) assert_equal(-1, Date.new(-4713,11,1,Date::GREGORIAN) <=> Date.new(-4713,12,1,Date::GREGORIAN)) end def test_eqeqeq assert_equal(false, Date.new(2001,2,3) === Date.new(2001,2,4)) assert_equal(true, Date.new(2001,2,3) === Date.new(2001,2,3)) assert_equal(false, Date.new(2001,2,3) === Date.new(2001,2,2)) assert_equal(true, Date.new(2001,2,3) === 2451944.0) assert_equal(true, Date.new(2001,2,3) === 2451944) assert_equal(false, Date.new(2001,2,3) === 2451943.5) assert_equal(false, Date.new(2001,2,3) === 2451943.0) assert_equal(false, Date.new(2001,2,3) === 2451943) assert_equal(true, Date.new(2001,2,3) === Rational('4903888/2')) assert_equal(false, Date.new(2001,2,3) === Rational('4903887/2')) assert_equal(false, Date.new(2001,2,3) === Rational('4903886/2')) end def test_period # -5000 d = Date.new(-5000,1,1) assert_equal([-5000, 1, 1, 5], [d.year, d.mon, d.mday, d.wday]) d2 = d.gregorian assert_equal([-5001, 11, 22, 5], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.new(-5000,1,1,Date::JULIAN) assert_equal([-5000, 1, 1, 5], [d.year, d.mon, d.mday, d.wday]) d2 = d.gregorian assert_equal([-5001, 11, 22, 5], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.new(-5000,1,1,Date::GREGORIAN) assert_equal([-5000, 1, 1, 3], [d.year, d.mon, d.mday, d.wday]) d2 = d.julian assert_equal([-5000, 2, 10, 3], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.jd(-105192) assert_equal([-5000, 1, 1, 5], [d.year, d.mon, d.mday, d.wday]) d2 = d.gregorian assert_equal([-5001, 11, 22, 5], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.jd(-105192,Date::JULIAN) assert_equal([-5000, 1, 1, 5], [d.year, d.mon, d.mday, d.wday]) d2 = d.gregorian assert_equal([-5001, 11, 22, 5], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.jd(-105152,Date::GREGORIAN) assert_equal([-5000, 1, 1, 3], [d.year, d.mon, d.mday, d.wday]) d2 = d.julian assert_equal([-5000, 2, 10, 3], [d2.year, d2.mon, d2.mday, d.wday]) # -5000000 d = Date.new(-5_000_000,1,1) assert_equal([-5_000_000, 1, 1, 3], [d.year, d.mon, d.mday, d.wday]) d2 = d.gregorian assert_equal([-5_000_103, 4, 28, 3], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.new(-5_000_000,1,1,Date::JULIAN) assert_equal([-5_000_000, 1, 1, 3], [d.year, d.mon, d.mday, d.wday]) d2 = d.gregorian assert_equal([-5_000_103, 4, 28, 3], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.new(-5_000_000,1,1,Date::GREGORIAN) assert_equal([-5_000_000, 1, 1, 6], [d.year, d.mon, d.mday, d.wday]) d2 = d.julian assert_equal([-4_999_898, 9, 4, 6], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.jd(-1824528942) assert_equal([-5_000_000, 1, 1, 3], [d.year, d.mon, d.mday, d.wday]) d2 = d.gregorian assert_equal([-5_000_103, 4, 28, 3], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.jd(-1824528942,Date::JULIAN) assert_equal([-5_000_000, 1, 1, 3], [d.year, d.mon, d.mday, d.wday]) d2 = d.gregorian assert_equal([-5_000_103, 4, 28, 3], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.jd(-1824491440,Date::GREGORIAN) assert_equal([-5_000_000, 1, 1, 6], [d.year, d.mon, d.mday, d.wday]) d2 = d.julian assert_equal([-4_999_898, 9, 4, 6], [d2.year, d2.mon, d2.mday, d.wday]) # 5000000 d = Date.new(5_000_000,1,1) assert_equal([5_000_000, 1, 1, 6], [d.year, d.mon, d.mday, d.wday]) d2 = d.julian assert_equal([4_999_897, 5, 3, 6], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.new(5_000_000,1,1,Date::JULIAN) assert_equal([5_000_000, 1, 1, 5], [d.year, d.mon, d.mday, d.wday]) d2 = d.gregorian assert_equal([5_000_102, 9, 1, 5], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.new(5_000_000,1,1,Date::GREGORIAN) assert_equal([5_000_000, 1, 1, 6], [d.year, d.mon, d.mday, d.wday]) d2 = d.julian assert_equal([4_999_897, 5, 3, 6], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.jd(1827933560) assert_equal([5_000_000, 1, 1, 6], [d.year, d.mon, d.mday, d.wday]) d2 = d.julian assert_equal([4_999_897, 5, 3, 6], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.jd(1827971058,Date::JULIAN) assert_equal([5_000_000, 1, 1, 5], [d.year, d.mon, d.mday, d.wday]) d2 = d.gregorian assert_equal([5_000_102, 9, 1, 5], [d2.year, d2.mon, d2.mday, d.wday]) d = Date.jd(1827933560,Date::GREGORIAN) assert_equal([5_000_000, 1, 1, 6], [d.year, d.mon, d.mday, d.wday]) d2 = d.julian assert_equal([4_999_897, 5, 3, 6], [d2.year, d2.mon, d2.mday, d.wday]) # dt d = DateTime.new(-123456789,2,3,4,5,6,0) assert_equal([-123456789, 2, 3, 4, 5, 6, 1], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.wday]) d2 = d.gregorian assert_equal([-123459325, 12, 27, 4, 5, 6, 1], [d2.year, d2.mon, d2.mday, d2.hour, d2.min, d2.sec, d.wday]) d = DateTime.new(123456789,2,3,4,5,6,0) assert_equal([123456789, 2, 3, 4, 5, 6, 5], [d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.wday]) d2 = d.julian assert_equal([123454254, 1, 19, 4, 5, 6, 5], [d2.year, d2.mon, d2.mday, d2.hour, d2.min, d2.sec, d.wday]) end def period2_iter2(from, to, sg) (from..to).each do |j| d = Date.jd(j, sg) d2 = Date.new(d.year, d.mon, d.mday, sg) assert_equal(d2.jd, j) assert_equal(d2.ajd, d.ajd) assert_equal(d2.year, d.year) d = DateTime.jd(j, 12,0,0, '+12:00', sg) d2 = DateTime.new(d.year, d.mon, d.mday, d.hour, d.min, d.sec, d.offset, sg) assert_equal(d2.jd, j) assert_equal(d2.ajd, d.ajd) assert_equal(d2.year, d.year) end end def period2_iter(from, to) period2_iter2(from, to, Date::GREGORIAN) period2_iter2(from, to, Date::ITALY) period2_iter2(from, to, Date::ENGLAND) period2_iter2(from, to, Date::JULIAN) end def test_period2 cm_period0 = 71149239 cm_period = 0xfffffff.div(cm_period0) * cm_period0 period2_iter(-cm_period * (1 << 64) - 3, -cm_period * (1 << 64) + 3) period2_iter(-cm_period - 3, -cm_period + 3) period2_iter(0 - 3, 0 + 3) period2_iter(+cm_period - 3, +cm_period + 3) period2_iter(+cm_period * (1 << 64) - 3, +cm_period * (1 << 64) + 3) end def test_different_alignments assert_equal(0, Date.jd(0) <=> Date.civil(-4713, 11, 24, Date::GREGORIAN)) assert_equal(0, Date.jd(213447717) <=> Date.civil(579687, 11, 24)) assert_equal(0, Date.jd(-213447717) <=> Date.civil(-589113, 11, 24, Date::GREGORIAN)) assert_equal(0, Date.jd(0) <=> DateTime.civil(-4713, 11, 24, 0, 0, 0, 0, Date::GREGORIAN)) assert_equal(0, Date.jd(213447717) <=> DateTime.civil(579687, 11, 24)) assert_equal(0, Date.jd(-213447717) <=> DateTime.civil(-589113, 11, 24, 0, 0, 0, 0, Date::GREGORIAN)) assert(Date.jd(0) == Date.civil(-4713, 11, 24, Date::GREGORIAN)) assert(Date.jd(213447717) == Date.civil(579687, 11, 24)) assert(Date.jd(-213447717) == Date.civil(-589113, 11, 24, Date::GREGORIAN)) assert(Date.jd(0) == DateTime.civil(-4713, 11, 24, 0, 0, 0, 0, Date::GREGORIAN)) assert(Date.jd(213447717) == DateTime.civil(579687, 11, 24)) assert(Date.jd(-213447717) == DateTime.civil(-589113, 11, 24, 0, 0, 0, 0, Date::GREGORIAN)) assert(Date.jd(0) === Date.civil(-4713, 11, 24, Date::GREGORIAN)) assert(Date.jd(213447717) === Date.civil(579687, 11, 24)) assert(Date.jd(-213447717) === Date.civil(-589113, 11, 24, Date::GREGORIAN)) assert(Date.jd(0) === DateTime.civil(-4713, 11, 24, 12, 0, 0, 0, Date::GREGORIAN)) assert(Date.jd(213447717) === DateTime.civil(579687, 11, 24, 12)) assert(Date.jd(-213447717) === DateTime.civil(-589113, 11, 24, 12, 0, 0, 0, Date::GREGORIAN)) a = Date.jd(0) b = Date.civil(-4713, 11, 24, Date::GREGORIAN) assert_equal(0, a <=> b) a = Date.civil(-4712, 1, 1, Date::JULIAN) b = Date.civil(-4713, 11, 24, Date::GREGORIAN) a.jd; b.jd assert_equal(0, a <=> b) a = Date.jd(0) b = Date.civil(-4713, 11, 24, Date::GREGORIAN) assert(a == b) a = Date.civil(-4712, 1, 1, Date::JULIAN) b = Date.civil(-4713, 11, 24, Date::GREGORIAN) a.jd; b.jd assert(a == b) a = Date.jd(0) b = Date.civil(-4713, 11, 24, Date::GREGORIAN) assert(a === b) a = Date.civil(-4712, 1, 1, Date::JULIAN) b = Date.civil(-4713, 11, 24, Date::GREGORIAN) a.jd; b.jd assert(a === b) end def test_marshal14 s = "\x04\x03u:\x01\x04Date\x01\v\x04\x03[\x01\x02i\x03\xE8i%T" d = Marshal.load(s) assert_equal(Rational(4903887,2), d.ajd) assert_equal(0, d.send(:offset)) assert_equal(Date::GREGORIAN, d.start) end def test_marshal16 s = "\x04\x06u:\tDate\x0F\x04\x06[\ai\x03\xE8i%T" d = Marshal.load(s) assert_equal(Rational(4903887,2), d.ajd) assert_equal(0, d.send(:offset)) assert_equal(Date::GREGORIAN, d.start) end def test_marshal18 s = "\x04\bu:\tDateP\x04\b[\bo:\rRational\a:\x0F@numeratori\x03\xCF\xD3J:\x11@denominatori\ai\x00o:\x13Date::Infinity\x06:\a@di\xFA" d = Marshal.load(s) assert_equal(Rational(4903887,2), d.ajd) assert_equal(0, d.send(:offset)) assert_equal(Date::GREGORIAN, d.start) s = "\x04\bu:\rDateTime`\x04\b[\bo:\rRational\a:\x0F@numeratorl+\b\xC9\xB0\x81\xBD\x02\x00:\x11@denominatori\x02\xC0\x12o;\x00\a;\x06i\b;\ai\ro:\x13Date::Infinity\x06:\a@di\xFA" d = Marshal.load(s) assert_equal(Rational(11769327817,4800), d.ajd) assert_equal(Rational(9,24), d.offset) assert_equal(Date::GREGORIAN, d.start) end def test_marshal192 s = "\x04\bU:\tDate[\bU:\rRational[\ai\x03\xCF\xD3Ji\ai\x00o:\x13Date::Infinity\x06:\a@di\xFA" d = Marshal.load(s) assert_equal(Rational(4903887,2), d.ajd) assert_equal(Rational(0,24), d.send(:offset)) assert_equal(Date::GREGORIAN, d.start) s = "\x04\bU:\rDateTime[\bU:\rRational[\al+\b\xC9\xB0\x81\xBD\x02\x00i\x02\xC0\x12U;\x06[\ai\bi\ro:\x13Date::Infinity\x06:\a@di\xFA" d = Marshal.load(s) assert_equal(Rational(11769327817,4800), d.ajd) assert_equal(Rational(9,24), d.offset) assert_equal(Date::GREGORIAN, d.start) end def test_taint h = Date._strptime('15:43+09:00', '%R%z') assert_equal(false, h[:zone].tainted?) h = Date._strptime('15:43+09:00'.taint, '%R%z') assert_equal(true, h[:zone].tainted?) h = Date._strptime('1;1/0', '%d') assert_equal(false, h[:leftover].tainted?) h = Date._strptime('1;1/0'.taint, '%d') assert_equal(true, h[:leftover].tainted?) h = Date._parse('15:43+09:00') assert_equal(false, h[:zone].tainted?) h = Date._parse('15:43+09:00'.taint) assert_equal(true, h[:zone].tainted?) s = Date.today.strftime('new 105') assert_equal(false, s.tainted?) s = Date.today.strftime('new 105'.taint) assert_equal(true, s.tainted?) s = Date.today.strftime("new \000 105".taint) assert_equal(true, s.tainted?) s = DateTime.now.strftime('super $record') assert_equal(false, s.tainted?) s = DateTime.now.strftime('super $record'.taint) assert_equal(true, s.tainted?) end def test_enc Date::MONTHNAMES.each do |s| assert_equal(Encoding::US_ASCII, s.encoding) if s end Date::DAYNAMES.each do |s| assert_equal(Encoding::US_ASCII, s.encoding) if s end Date::ABBR_MONTHNAMES.each do |s| assert_equal(Encoding::US_ASCII, s.encoding) if s end Date::ABBR_DAYNAMES.each do |s| assert_equal(Encoding::US_ASCII, s.encoding) if s end h = Date._strptime('15:43+09:00'.force_encoding('euc-jp'), '%R%z') assert_equal(Encoding::EUC_JP, h[:zone].encoding) h = Date._strptime('15:43+09:00'.force_encoding('ascii-8bit'), '%R%z') assert_equal(Encoding::ASCII_8BIT, h[:zone].encoding) h = Date._strptime('1;1/0'.force_encoding('euc-jp'), '%d') assert_equal(Encoding::EUC_JP, h[:leftover].encoding) h = Date._strptime('1;1/0'.force_encoding('ascii-8bit'), '%d') assert_equal(Encoding::ASCII_8BIT, h[:leftover].encoding) h = Date._parse('15:43+09:00'.force_encoding('euc-jp')) assert_equal(Encoding::EUC_JP, h[:zone].encoding) h = Date._parse('15:43+09:00'.force_encoding('ascii-8bit')) assert_equal(Encoding::ASCII_8BIT, h[:zone].encoding) s = Date.today.strftime('new 105'.force_encoding('euc-jp')) assert_equal(Encoding::EUC_JP, s.encoding) s = Date.today.strftime('new 105'.force_encoding('ascii-8bit')) assert_equal(Encoding::ASCII_8BIT, s.encoding) s = DateTime.now.strftime('super $record'.force_encoding('euc-jp')) assert_equal(Encoding::EUC_JP, s.encoding) s = DateTime.now.strftime('super $record'.force_encoding('ascii-8bit')) assert_equal(Encoding::ASCII_8BIT, s.encoding) end def test_dup d = Date.new(2001,2,3) d2 = d.dup assert_not_equal(d.object_id, d2.object_id) assert_kind_of(Date, d2) assert_equal(d, d2) d = DateTime.new(2001,2,3) d2 = d.dup assert_not_equal(d.object_id, d2.object_id) assert_kind_of(DateTime, d2) assert_equal(d, d2) end def test_base skip unless defined?(Date.test_all) assert_equal(true, Date.test_all) end end
38.705263
181
0.604025
8759ad8026768f9c47abd6537669dfd069e9ba27
2,368
#!/usr/bin/env ruby # -*- coding: utf-8 -*- require 'rubygems' require 'methodic' class Template attr_reader :list_token attr_reader :template_file attr_reader :content def initialize(_options) options = Methodic.get_options(_options) options.specify_classes_of({:list_token => Array, :template_file => String}) options.specify_presences_of([:list_token,:template_file]) options.validate! @template_file = _options[:template_file] raise NoTemplateFile::new('No template file found') unless File::exist?(@template_file) begin @content = IO::readlines(@template_file).join.chomp rescue raise NoTemplateFile::new('No template file found') end token_from_template = @content.scan(/%%(\w+)%%/).flatten.uniq.map{ |item| item.downcase.to_sym} begin @list_token = _options[:list_token].map!{|_token| _token.downcase.to_sym } @hash_token = Hash::new; @list_token.each{|_item| @hash_token[_item.to_s] = String::new('')} rescue raise InvalidTokenList::new("Token list malformation") end raise InvalidTokenList::new("Token list doesn't match the template") unless token_from_template.sort == @list_token.sort @list_token.each{|_token| eval("def #{_token}=(_value); raise ArgumentError::new('Not a String') unless _value.class == String; @hash_token['#{_token}'] = _value ;end")} @list_token.each{|_token| eval("def #{_token}; @hash_token['#{_token}'] ;end")} end def token(_token,_value) raise ArgumentError::new('Not a String') unless _value.class == String @hash_token[_token.to_s] = _value end def map(_hash) _data = {} _hash.each { |item,val| raise ArgumentError::new("#{item} : Not a String") unless val.class == String _data[item.to_s.downcase] = val } raise InvalidTokenList::new("Token list malformation") unless _data.keys.sort == @list_token.map{|_token| _token.to_s }.sort @hash_token = _data end def method_missing(_name,*_args) raise NotAToken end def output _my_res = String::new('') _my_res = @content @list_token.each{|_token| _my_res.gsub!(/%%#{_token.to_s.upcase}%%/,@hash_token[_token.to_s]) } return _my_res end end class InvalidTokenList < Exception; end class NotAToken < Exception; end class NoTemplateFile < Exception; end
31.573333
173
0.680743
bbddaa55e3187661ab0d00bcdbe405676e6c6bca
330
require 'strings2conf/version' require 'json' require 'erb' include ERB::Util module Strings2conf def self.convert(json) @data = JSON.parse json template_path = File.dirname(File.expand_path(__FILE__)) + '/templates/confluence.html.erb' ERB.new(File.read(template_path), nil, '-').result(binding) end end
25.384615
95
0.715152
38dab0a70f72a415f22f07b1407203a8190533f2
5,259
module Axlsx # The SheetProtection object manages worksheet protection options per sheet. class SheetProtection include Axlsx::OptionsParser include Axlsx::SerializedAttributes include Axlsx::Accessors # Creates a new SheetProtection instance # @option options [Boolean] sheet @see SheetProtection#sheet # @option options [Boolean] objects @see SheetProtection#objects # @option options [Boolean] scenarios @see SheetProtection#scenarios # @option options [Boolean] format_cells @see SheetProtection#objects # @option options [Boolean] format_columns @see SheetProtection#format_columns # @option options [Boolean] format_rows @see SheetProtection#format_rows # @option options [Boolean] insert_columns @see SheetProtection#insert_columns # @option options [Boolean] insert_rows @see SheetProtection#insert_rows # @option options [Boolean] insert_hyperlinks @see SheetProtection#insert_hyperlinks # @option options [Boolean] delete_columns @see SheetProtection#delete_columns # @option options [Boolean] delete_rows @see SheetProtection#delete_rows # @option options [Boolean] select_locked_cells @see SheetProtection#select_locked_cells # @option options [Boolean] sort @see SheetProtection#sort # @option options [Boolean] auto_filter @see SheetProtection#auto_filter # @option options [Boolean] pivot_tables @see SheetProtection#pivot_tables # @option options [Boolean] select_unlocked_cells @see SheetProtection#select_unlocked_cells # @option options [String] password. The password required for unlocking. @see SheetProtection#password= def initialize(options = {}) @objects = @scenarios = @select_locked_cells = @select_unlocked_cells = false @sheet = @format_cells = @format_rows = @format_columns = @insert_columns = @insert_rows = @insert_hyperlinks = @delete_columns = @delete_rows = @sort = @auto_filter = @pivot_tables = true @password = nil parse_options options end boolean_attr_accessor :sheet, :objects, :scenarios, :format_cells, :format_columns, :format_rows, :insert_columns, :insert_rows, :insert_hyperlinks, :delete_columns, :delete_rows, :select_locked_cells, :sort, :auto_filter, :pivot_tables, :select_unlocked_cells serializable_attributes :sheet, :objects, :scenarios, :format_cells, :format_columns, :format_rows, :insert_columns, :insert_rows, :insert_hyperlinks, :delete_columns, :delete_rows, :select_locked_cells, :sort, :auto_filter, :pivot_tables, :select_unlocked_cells, :salt, :password # Specifies the salt which was prepended to the user-supplied password before it was hashed using the hashing algorithm # @return [String] attr_reader :salt_value # Password hash # @return [String] # default nil attr_reader :password # This block is intended to implement the salt_value, hash_value and spin count as per the ECMA-376 standard. # However, it does not seem to actually work in EXCEL - instead they are using their old retro algorithm shown below # defined in the transitional portion of the speck. I am leaving this code in in the hope that someday Ill be able to # figure out why it does not work, and if Excel even supports it. # def propper_password=(v) # @algorithm_name = v == nil ? nil : 'SHA-1' # @salt_value = @spin_count = @hash_value = v if v == nil # return if v == nil # require 'digest/sha1' # @spin_count = 10000 # @salt_value = Digest::SHA1.hexdigest(rand(36**8).to_s(36)) # @spin_count.times do |count| # @hash_value = Digest::SHA1.hexdigest((@hash_value ||= (@salt_value + v.to_s)) + Array(count).pack('V')) # end # end # encodes password for protection locking def password=(v) return if v.nil? @password = create_password_hash(v) end # Serialize the object # @param [String] str # @return [String] def to_xml_string(str = '') serialized_tag('sheetProtection', str) end private # Creates a password hash for a given password # @return [String] def create_password_hash(password) encoded_password = encode_password(password) password_as_hex = [encoded_password].pack('v') password_as_string = password_as_hex.unpack1('H*').upcase password_as_string[2..3] + password_as_string[0..1] end # Encodes a given password # Based on the algorithm provided by Daniel Rentz of OpenOffice. # http://www.openoffice.org/sc/excelfileformat.pdf, Revision 1.42, page 115 (21.05.2012) # @return [String] def encode_password(password) i = 0 chars = password.split(//) count = chars.size chars.collect! do |char| i += 1 char = char.unpack1('c') << i # ord << i low_15 = char & 0x7fff high_15 = char & 0x7fff << 15 high_15 = high_15 >> 15 char = low_15 | high_15 end encoded_password = 0x0000 chars.each { |c| encoded_password ^= c } encoded_password ^= count encoded_password ^= 0xCE4B end end end
44.567797
194
0.686442
79a7762c0f54c39da6d10d54661a0edab023b05a
959
require "test_helper" describe "bin/vanity" do before do not_collecting! end it "responds to version" do assert_output(nil) do proc { ARGV.clear ARGV << '--version' load "bin/vanity" }.must_raise SystemExit end end it "responds to help" do assert_output(nil) do proc { ARGV.clear ARGV << '--help' load "bin/vanity" }.must_raise SystemExit end end it "responds to list" do require "vanity/commands/list" Vanity::Commands.expects(:list) ARGV.clear ARGV << 'list' load "bin/vanity" end it "responds to report" do require "vanity/commands/report" Vanity::Commands.expects(:report) ARGV.clear ARGV << 'report' load "bin/vanity" end it "responds to unknown commands" do assert_output("No such command: upgrade\n") do ARGV.clear ARGV << 'upgrade' load "bin/vanity" end end end
18.09434
50
0.601668
61e4a03a31b1c206e37300e3747f7ba11acc4ab9
33,581
require 'cucumber/messages.dtos' require 'json' # The code was auto-generated by {this script}[https://github.com/cucumber/common/blob/main/messages/jsonschema/scripts/codegen.rb] # module Cucumber module Messages class Attachment ## # Returns a new Attachment from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Attachment.from_h(some_hash) # => #<Cucumber::Messages::Attachment:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( body: hash[:body], content_encoding: hash[:contentEncoding], file_name: hash[:fileName], media_type: hash[:mediaType], source: Source.from_h(hash[:source]), test_case_started_id: hash[:testCaseStartedId], test_step_id: hash[:testStepId], url: hash[:url], ) end end class Duration ## # Returns a new Duration from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Duration.from_h(some_hash) # => #<Cucumber::Messages::Duration:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( seconds: hash[:seconds], nanos: hash[:nanos], ) end end class Envelope ## # Returns a new Envelope from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Envelope.from_h(some_hash) # => #<Cucumber::Messages::Envelope:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( attachment: Attachment.from_h(hash[:attachment]), gherkin_document: GherkinDocument.from_h(hash[:gherkinDocument]), hook: Hook.from_h(hash[:hook]), meta: Meta.from_h(hash[:meta]), parameter_type: ParameterType.from_h(hash[:parameterType]), parse_error: ParseError.from_h(hash[:parseError]), pickle: Pickle.from_h(hash[:pickle]), source: Source.from_h(hash[:source]), step_definition: StepDefinition.from_h(hash[:stepDefinition]), test_case: TestCase.from_h(hash[:testCase]), test_case_finished: TestCaseFinished.from_h(hash[:testCaseFinished]), test_case_started: TestCaseStarted.from_h(hash[:testCaseStarted]), test_run_finished: TestRunFinished.from_h(hash[:testRunFinished]), test_run_started: TestRunStarted.from_h(hash[:testRunStarted]), test_step_finished: TestStepFinished.from_h(hash[:testStepFinished]), test_step_started: TestStepStarted.from_h(hash[:testStepStarted]), undefined_parameter_type: UndefinedParameterType.from_h(hash[:undefinedParameterType]), ) end end class GherkinDocument ## # Returns a new GherkinDocument from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::GherkinDocument.from_h(some_hash) # => #<Cucumber::Messages::GherkinDocument:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( uri: hash[:uri], feature: Feature.from_h(hash[:feature]), comments: hash[:comments]&.map { |item| Comment.from_h(item) }, ) end end class Background ## # Returns a new Background from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Background.from_h(some_hash) # => #<Cucumber::Messages::Background:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( location: Location.from_h(hash[:location]), keyword: hash[:keyword], name: hash[:name], description: hash[:description], steps: hash[:steps]&.map { |item| Step.from_h(item) }, id: hash[:id], ) end end class Comment ## # Returns a new Comment from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Comment.from_h(some_hash) # => #<Cucumber::Messages::Comment:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( location: Location.from_h(hash[:location]), text: hash[:text], ) end end class DataTable ## # Returns a new DataTable from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::DataTable.from_h(some_hash) # => #<Cucumber::Messages::DataTable:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( location: Location.from_h(hash[:location]), rows: hash[:rows]&.map { |item| TableRow.from_h(item) }, ) end end class DocString ## # Returns a new DocString from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::DocString.from_h(some_hash) # => #<Cucumber::Messages::DocString:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( location: Location.from_h(hash[:location]), media_type: hash[:mediaType], content: hash[:content], delimiter: hash[:delimiter], ) end end class Examples ## # Returns a new Examples from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Examples.from_h(some_hash) # => #<Cucumber::Messages::Examples:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( location: Location.from_h(hash[:location]), tags: hash[:tags]&.map { |item| Tag.from_h(item) }, keyword: hash[:keyword], name: hash[:name], description: hash[:description], table_header: TableRow.from_h(hash[:tableHeader]), table_body: hash[:tableBody]&.map { |item| TableRow.from_h(item) }, id: hash[:id], ) end end class Feature ## # Returns a new Feature from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Feature.from_h(some_hash) # => #<Cucumber::Messages::Feature:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( location: Location.from_h(hash[:location]), tags: hash[:tags]&.map { |item| Tag.from_h(item) }, language: hash[:language], keyword: hash[:keyword], name: hash[:name], description: hash[:description], children: hash[:children]&.map { |item| FeatureChild.from_h(item) }, ) end end class FeatureChild ## # Returns a new FeatureChild from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::FeatureChild.from_h(some_hash) # => #<Cucumber::Messages::FeatureChild:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( rule: Rule.from_h(hash[:rule]), background: Background.from_h(hash[:background]), scenario: Scenario.from_h(hash[:scenario]), ) end end class Rule ## # Returns a new Rule from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Rule.from_h(some_hash) # => #<Cucumber::Messages::Rule:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( location: Location.from_h(hash[:location]), tags: hash[:tags]&.map { |item| Tag.from_h(item) }, keyword: hash[:keyword], name: hash[:name], description: hash[:description], children: hash[:children]&.map { |item| RuleChild.from_h(item) }, id: hash[:id], ) end end class RuleChild ## # Returns a new RuleChild from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::RuleChild.from_h(some_hash) # => #<Cucumber::Messages::RuleChild:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( background: Background.from_h(hash[:background]), scenario: Scenario.from_h(hash[:scenario]), ) end end class Scenario ## # Returns a new Scenario from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Scenario.from_h(some_hash) # => #<Cucumber::Messages::Scenario:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( location: Location.from_h(hash[:location]), tags: hash[:tags]&.map { |item| Tag.from_h(item) }, keyword: hash[:keyword], name: hash[:name], description: hash[:description], steps: hash[:steps]&.map { |item| Step.from_h(item) }, examples: hash[:examples]&.map { |item| Examples.from_h(item) }, id: hash[:id], ) end end class Step ## # Returns a new Step from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Step.from_h(some_hash) # => #<Cucumber::Messages::Step:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( location: Location.from_h(hash[:location]), keyword: hash[:keyword], text: hash[:text], doc_string: DocString.from_h(hash[:docString]), data_table: DataTable.from_h(hash[:dataTable]), id: hash[:id], ) end end class TableCell ## # Returns a new TableCell from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::TableCell.from_h(some_hash) # => #<Cucumber::Messages::TableCell:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( location: Location.from_h(hash[:location]), value: hash[:value], ) end end class TableRow ## # Returns a new TableRow from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::TableRow.from_h(some_hash) # => #<Cucumber::Messages::TableRow:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( location: Location.from_h(hash[:location]), cells: hash[:cells]&.map { |item| TableCell.from_h(item) }, id: hash[:id], ) end end class Tag ## # Returns a new Tag from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Tag.from_h(some_hash) # => #<Cucumber::Messages::Tag:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( location: Location.from_h(hash[:location]), name: hash[:name], id: hash[:id], ) end end class Hook ## # Returns a new Hook from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Hook.from_h(some_hash) # => #<Cucumber::Messages::Hook:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( id: hash[:id], name: hash[:name], source_reference: SourceReference.from_h(hash[:sourceReference]), tag_expression: hash[:tagExpression], ) end end class Location ## # Returns a new Location from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Location.from_h(some_hash) # => #<Cucumber::Messages::Location:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( line: hash[:line], column: hash[:column], ) end end class Meta ## # Returns a new Meta from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Meta.from_h(some_hash) # => #<Cucumber::Messages::Meta:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( protocol_version: hash[:protocolVersion], implementation: Product.from_h(hash[:implementation]), runtime: Product.from_h(hash[:runtime]), os: Product.from_h(hash[:os]), cpu: Product.from_h(hash[:cpu]), ci: Ci.from_h(hash[:ci]), ) end end class Ci ## # Returns a new Ci from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Ci.from_h(some_hash) # => #<Cucumber::Messages::Ci:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( name: hash[:name], url: hash[:url], build_number: hash[:buildNumber], git: Git.from_h(hash[:git]), ) end end class Git ## # Returns a new Git from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Git.from_h(some_hash) # => #<Cucumber::Messages::Git:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( remote: hash[:remote], revision: hash[:revision], branch: hash[:branch], tag: hash[:tag], ) end end class Product ## # Returns a new Product from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Product.from_h(some_hash) # => #<Cucumber::Messages::Product:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( name: hash[:name], version: hash[:version], ) end end class ParameterType ## # Returns a new ParameterType from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::ParameterType.from_h(some_hash) # => #<Cucumber::Messages::ParameterType:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( name: hash[:name], regular_expressions: hash[:regularExpressions], prefer_for_regular_expression_match: hash[:preferForRegularExpressionMatch], use_for_snippets: hash[:useForSnippets], id: hash[:id], ) end end class ParseError ## # Returns a new ParseError from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::ParseError.from_h(some_hash) # => #<Cucumber::Messages::ParseError:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( source: SourceReference.from_h(hash[:source]), message: hash[:message], ) end end class Pickle ## # Returns a new Pickle from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Pickle.from_h(some_hash) # => #<Cucumber::Messages::Pickle:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( id: hash[:id], uri: hash[:uri], name: hash[:name], language: hash[:language], steps: hash[:steps]&.map { |item| PickleStep.from_h(item) }, tags: hash[:tags]&.map { |item| PickleTag.from_h(item) }, ast_node_ids: hash[:astNodeIds], ) end end class PickleDocString ## # Returns a new PickleDocString from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::PickleDocString.from_h(some_hash) # => #<Cucumber::Messages::PickleDocString:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( media_type: hash[:mediaType], content: hash[:content], ) end end class PickleStep ## # Returns a new PickleStep from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::PickleStep.from_h(some_hash) # => #<Cucumber::Messages::PickleStep:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( argument: PickleStepArgument.from_h(hash[:argument]), ast_node_ids: hash[:astNodeIds], id: hash[:id], text: hash[:text], ) end end class PickleStepArgument ## # Returns a new PickleStepArgument from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::PickleStepArgument.from_h(some_hash) # => #<Cucumber::Messages::PickleStepArgument:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( doc_string: PickleDocString.from_h(hash[:docString]), data_table: PickleTable.from_h(hash[:dataTable]), ) end end class PickleTable ## # Returns a new PickleTable from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::PickleTable.from_h(some_hash) # => #<Cucumber::Messages::PickleTable:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( rows: hash[:rows]&.map { |item| PickleTableRow.from_h(item) }, ) end end class PickleTableCell ## # Returns a new PickleTableCell from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::PickleTableCell.from_h(some_hash) # => #<Cucumber::Messages::PickleTableCell:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( value: hash[:value], ) end end class PickleTableRow ## # Returns a new PickleTableRow from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::PickleTableRow.from_h(some_hash) # => #<Cucumber::Messages::PickleTableRow:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( cells: hash[:cells]&.map { |item| PickleTableCell.from_h(item) }, ) end end class PickleTag ## # Returns a new PickleTag from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::PickleTag.from_h(some_hash) # => #<Cucumber::Messages::PickleTag:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( name: hash[:name], ast_node_id: hash[:astNodeId], ) end end class Source ## # Returns a new Source from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Source.from_h(some_hash) # => #<Cucumber::Messages::Source:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( uri: hash[:uri], data: hash[:data], media_type: hash[:mediaType], ) end end class SourceReference ## # Returns a new SourceReference from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::SourceReference.from_h(some_hash) # => #<Cucumber::Messages::SourceReference:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( uri: hash[:uri], java_method: JavaMethod.from_h(hash[:javaMethod]), java_stack_trace_element: JavaStackTraceElement.from_h(hash[:javaStackTraceElement]), location: Location.from_h(hash[:location]), ) end end class JavaMethod ## # Returns a new JavaMethod from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::JavaMethod.from_h(some_hash) # => #<Cucumber::Messages::JavaMethod:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( class_name: hash[:className], method_name: hash[:methodName], method_parameter_types: hash[:methodParameterTypes], ) end end class JavaStackTraceElement ## # Returns a new JavaStackTraceElement from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::JavaStackTraceElement.from_h(some_hash) # => #<Cucumber::Messages::JavaStackTraceElement:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( class_name: hash[:className], file_name: hash[:fileName], method_name: hash[:methodName], ) end end class StepDefinition ## # Returns a new StepDefinition from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::StepDefinition.from_h(some_hash) # => #<Cucumber::Messages::StepDefinition:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( id: hash[:id], pattern: StepDefinitionPattern.from_h(hash[:pattern]), source_reference: SourceReference.from_h(hash[:sourceReference]), ) end end class StepDefinitionPattern ## # Returns a new StepDefinitionPattern from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::StepDefinitionPattern.from_h(some_hash) # => #<Cucumber::Messages::StepDefinitionPattern:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( source: hash[:source], type: hash[:type], ) end end class TestCase ## # Returns a new TestCase from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::TestCase.from_h(some_hash) # => #<Cucumber::Messages::TestCase:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( id: hash[:id], pickle_id: hash[:pickleId], test_steps: hash[:testSteps]&.map { |item| TestStep.from_h(item) }, ) end end class Group ## # Returns a new Group from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Group.from_h(some_hash) # => #<Cucumber::Messages::Group:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( children: hash[:children]&.map { |item| Group.from_h(item) }, start: hash[:start], value: hash[:value], ) end end class StepMatchArgument ## # Returns a new StepMatchArgument from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::StepMatchArgument.from_h(some_hash) # => #<Cucumber::Messages::StepMatchArgument:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( group: Group.from_h(hash[:group]), parameter_type_name: hash[:parameterTypeName], ) end end class StepMatchArgumentsList ## # Returns a new StepMatchArgumentsList from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::StepMatchArgumentsList.from_h(some_hash) # => #<Cucumber::Messages::StepMatchArgumentsList:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( step_match_arguments: hash[:stepMatchArguments]&.map { |item| StepMatchArgument.from_h(item) }, ) end end class TestStep ## # Returns a new TestStep from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::TestStep.from_h(some_hash) # => #<Cucumber::Messages::TestStep:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( hook_id: hash[:hookId], id: hash[:id], pickle_step_id: hash[:pickleStepId], step_definition_ids: hash[:stepDefinitionIds], step_match_arguments_lists: hash[:stepMatchArgumentsLists]&.map { |item| StepMatchArgumentsList.from_h(item) }, ) end end class TestCaseFinished ## # Returns a new TestCaseFinished from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::TestCaseFinished.from_h(some_hash) # => #<Cucumber::Messages::TestCaseFinished:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( test_case_started_id: hash[:testCaseStartedId], timestamp: Timestamp.from_h(hash[:timestamp]), will_be_retried: hash[:willBeRetried], ) end end class TestCaseStarted ## # Returns a new TestCaseStarted from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::TestCaseStarted.from_h(some_hash) # => #<Cucumber::Messages::TestCaseStarted:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( attempt: hash[:attempt], id: hash[:id], test_case_id: hash[:testCaseId], timestamp: Timestamp.from_h(hash[:timestamp]), ) end end class TestRunFinished ## # Returns a new TestRunFinished from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::TestRunFinished.from_h(some_hash) # => #<Cucumber::Messages::TestRunFinished:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( message: hash[:message], success: hash[:success], timestamp: Timestamp.from_h(hash[:timestamp]), ) end end class TestRunStarted ## # Returns a new TestRunStarted from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::TestRunStarted.from_h(some_hash) # => #<Cucumber::Messages::TestRunStarted:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( timestamp: Timestamp.from_h(hash[:timestamp]), ) end end class TestStepFinished ## # Returns a new TestStepFinished from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::TestStepFinished.from_h(some_hash) # => #<Cucumber::Messages::TestStepFinished:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( test_case_started_id: hash[:testCaseStartedId], test_step_id: hash[:testStepId], test_step_result: TestStepResult.from_h(hash[:testStepResult]), timestamp: Timestamp.from_h(hash[:timestamp]), ) end end class TestStepResult ## # Returns a new TestStepResult from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::TestStepResult.from_h(some_hash) # => #<Cucumber::Messages::TestStepResult:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( duration: Duration.from_h(hash[:duration]), message: hash[:message], status: hash[:status], ) end end class TestStepStarted ## # Returns a new TestStepStarted from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::TestStepStarted.from_h(some_hash) # => #<Cucumber::Messages::TestStepStarted:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( test_case_started_id: hash[:testCaseStartedId], test_step_id: hash[:testStepId], timestamp: Timestamp.from_h(hash[:timestamp]), ) end end class Timestamp ## # Returns a new Timestamp from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::Timestamp.from_h(some_hash) # => #<Cucumber::Messages::Timestamp:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( seconds: hash[:seconds], nanos: hash[:nanos], ) end end class UndefinedParameterType ## # Returns a new UndefinedParameterType from the given hash. # If the hash keys are camelCased, they are properly assigned to the # corresponding snake_cased attributes. # # Cucumber::Messages::UndefinedParameterType.from_h(some_hash) # => #<Cucumber::Messages::UndefinedParameterType:0x... ...> # def self.from_h(hash) return nil if hash.nil? self.new( expression: hash[:expression], name: hash[:name], ) end end end end
28.410321
131
0.591227
bb77186eb887a61a1761058936647c9beeaab339
156
require 'test_helper' class RegistrationRequestorPortTypeControllerTest < ActionController::TestCase # test "the truth" do # assert true # end end
19.5
78
0.769231
87436d46bca4e46c5063afaa302acafb692ecf38
1,495
class Qjackctl < Formula desc "Simple Qt application to control the JACK sound server daemon" homepage "https://qjackctl.sourceforge.io/" url "https://downloads.sourceforge.net/project/qjackctl/qjackctl/0.6.3/qjackctl-0.6.3.tar.gz" sha256 "9db46376cfacb2e2ee051312245f5f7c383c9f5a958c0e3d661b9bd2a9246b7d" license "GPL-2.0" head "https://git.code.sf.net/p/qjackctl/code.git" livecheck do url :stable regex(%r{url=.*?/qjackctl[._-]v?(\d+(?:\.\d+)+)\.t}i) end bottle do sha256 catalina: "8e30b2f2b2587c3177287a8a47f785862d0f6201e92f8cfc90ea16e17e2e405c" sha256 mojave: "902219e2f8d6e223a2375eeeb92470e0fefce0acb4d960b250a5c2ac5e5cef97" sha256 high_sierra: "c77bf5a0063a9c265b1c9c343a47e399f000a49acc496ace4c081398fa6e16cb" end depends_on "pkg-config" => :build depends_on "jack" depends_on "qt" def install ENV.cxx11 system "./configure", "--disable-debug", "--disable-dbus", "--disable-portaudio", "--disable-xunique", "--prefix=#{prefix}", "--with-jack=#{Formula["jack"].opt_prefix}", "--with-qt=#{Formula["qt"].opt_prefix}" system "make", "install" prefix.install bin/"qjackctl.app" bin.install_symlink prefix/"qjackctl.app/Contents/MacOS/qjackctl" end test do assert_match version.to_s, shell_output("#{bin}/qjackctl --version 2>&1", 1) end end
34.767442
95
0.646823
79695064c225474acf5095b92d707513fd1ab69e
28
module CoreStuffsHelper end
9.333333
23
0.892857
b9c401572a6bde2eae742809a5baf3235dbe0de4
3,421
# require 'erubis' require 'fileutils' # require 'forwardable' require 'rake' # require 'json' # def load_gems # gem_paths.each do |gem_path| # esruby_spec_path = "#{gem_path}/esruby_gem" # load(esruby_spec_path) if File.file?(esruby_spec_path) # end # nil # end # def gem_paths # JSON.parse(File.read(gem_paths_file)) # end # def gem_paths_file # "#{build_directory}/gem_paths.json" # end # production # -O2 # -g0 # --closure 1" #args << %q{-s "BINARYEN_METHOD='native-wasm,asmjs'"} # ENV["EMCC_CLOSURE_ARGS"] = "--language_in=ECMASCRIPT6" #possibly allow setting output: --language_out=ECMASCRIPT6 # sh "java -jar #{PROJECT_DIRECTORY}/emsdk/emscripten/incoming/third_party/closure-compiler/compiler.jar --js #{build.absolute_build_directory}/output.js --js_output_file #{build.absolute_output}" #else #output_file_extensions = ["asm.js", "js", "js.mem", "wasm"] #output_file_extensions = ["js"] #output_file_extensions.each do |extension| # FileUtils.cp("#{build_directory}/#{output_name}.#{extension}", "#{output_directory}/#{output_name}.#{extension}") #end #end #--language_in=ECMASCRIPT6 # end project_directory = File.expand_path(File.dirname(__FILE__)) build_directory = "#{project_directory}/build" FileUtils.mkdir_p(build_directory) mruby_directory = "#{project_directory}/resources/mruby" # build mruby lib raise 'mruby submodule not loaded' unless File.file?("#{mruby_directory}/Rakefile") ENV["MRUBY_CONFIG"] = "#{project_directory}/mruby_config_development.rb" Dir.chdir(mruby_directory) { RakeFileUtils.sh("rake") } ENV["MRUBY_CONFIG"] = nil libmruby_path = "#{build_directory}/emscripten/lib/libmruby.a" bruby_bridge_interface_directory = "#{project_directory}/resources/bruby_gems/bruby-bridge-interface" Dir.chdir(bruby_bridge_interface_directory) { RakeFileUtils.sh("extraneous build") } bruby_extension = "#{project_directory}/resources/bruby_gems/bruby-extension" Dir.chdir(bruby_extension) { RakeFileUtils.sh("extraneous build") } bruby_mruby_print = "#{project_directory}/resources/bruby_gems/bruby-mruby-print" Dir.chdir(bruby_mruby_print) { RakeFileUtils.sh("extraneous build") } output_name = "bruby-mruby.js" output_path = "#{build_directory}/#{output_name}" options = [] options << "-std=c++11" options << "--bind" options << "-lm" options << "-O0" options << "-g" options << "-s DEMANGLE_SUPPORT=1" options << "-s ALLOW_MEMORY_GROWTH=1" options << "-s ASSERTIONS=2" options << "-s WASM=0" options << "-s DISABLE_EXCEPTION_CATCHING=0" options << "-I #{project_directory}/resources/mruby/include" options << "-o #{build_directory}/mruby.o" RakeFileUtils.sh("emcc #{project_directory}/resources/cpp/mruby.cpp #{options.join(" ")}") options = [] options << "-std=c++11" options << "--bind" options << "-lm" options << "--post-js #{project_directory}/resources/js/mruby.js" options << "--post-js #{build_directory}/bruby-bridge-interface.js" options << "--post-js #{build_directory}/bruby-extension.js" options << "--post-js #{build_directory}/bruby-mruby-print.js" options << "-O0" options << "-g" options << "-s DEMANGLE_SUPPORT=1" options << "-s ALLOW_MEMORY_GROWTH=1" options << "-s ASSERTIONS=2" options << "-s WASM=0" options << "-s DISABLE_EXCEPTION_CATCHING=0" options << "-o #{output_path}" RakeFileUtils.sh("emcc #{build_directory}/mruby.o #{libmruby_path} #{options.join(" ")}")
34.21
201
0.715288
0313c28c2799431311544bded6b990d8b4246988
988
# frozen_string_literal: true require 'rails_helper' RSpec.describe ApplicationHelper, type: :helper do describe '#action_in_bem_format' do context 'the controller is in the root namespace' do before do expect(helper) .to(receive(:params)) .at_least(:once) .and_return('controller' => 'application', 'action' => 'index') end it 'formats the controller as E and the action as M ' do expect(helper.action_in_bem_format).to eq('application--index') end end context 'the controller is in a deep namespace' do before do expect(helper) .to(receive(:params)) .at_least(:once) .and_return('controller' => 'yummy_food/desserts/nom', 'action' => 'nom_nom') end it 'formats the namespace as B, the controller as E, and the action as M' do expect(helper.action_in_bem_format).to eq('yummy-food-desserts__nom--nom-nom') end end end end
29.058824
87
0.634615
186509c04e27f4d72a57d696939fd0089bddcb92
2,362
require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/hash/slice' module Mushroom class Subscriber attr_reader :event delegate :payload, :name, :time, :transaction_id, :duration, :to => :event def initialize(event) @event = event end # The endpoint for notifications def notify raise NotImplementedError end def target payload[:target] end class << self # Public: Setter and getter for events # # Can be called multiple times to set events on a Subscriber. # # Events cannot be inherited by subclassed objects. # # Example: # class Handler < Mushroom::Subscriber # events :start, :on => Server # events :stop, :on => [Server, Time] # events :register, :activate, :on => [User] # end # # Returns: Array of current event registrations. def events(*events_and_options) if events_and_options.empty? self._events else create_event_subscription(*events_and_options) end end # Internal: Trigger the notification within this subscriber def notify(event) instance = new(event) if instance.method(:notify).arity == 0 instance.notify elsif instance.method(:notify).arity > 0 instance.notify(*event.payload[:args]) end end protected def _events Thread.current[:"_events_#{object_id}"] ||= [] end def _events=(hash) Thread.current[:"_events_#{object_id}"] = [] end def create_event_subscription(*events_and_options) options = { :on => nil }.update(events_and_options.extract_options!) targets = Array(options[:on]) || raise(ArgumentError, "Event subscription must include :on => Class") targets.each do |target| events_and_options.each do |event| event = Mushroom.event_name(event, target) # Actually subscribe the event ActiveSupport::Notifications.subscribe(event) do |*args| self.notify(ActiveSupport::Notifications::Event.new(*args)) end (self._events ||=[]).push(event) end end return self._events end end end end
25.12766
109
0.596952
87a2b6aa94de79be10b7999ca17d230733dafd4d
1,466
require "administrate/base_dashboard" class DataSourceDashboard < Administrate::BaseDashboard # ATTRIBUTE_TYPES # a hash that describes the type of each of the model's fields. # # Each different type represents an Administrate::Field object, # which determines how the attribute is displayed # on pages throughout the dashboard. ATTRIBUTE_TYPES = { fields: Field::HasMany, id: Field::Number, database_url: Field::String, created_at: Field::DateTime, updated_at: Field::DateTime, }.freeze # COLLECTION_ATTRIBUTES # an array of attributes that will be displayed on the model's index page. # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. COLLECTION_ATTRIBUTES = [ :fields, :id, :database_url, :created_at, ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. SHOW_PAGE_ATTRIBUTES = [ :fields, :id, :database_url, :created_at, :updated_at, ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. FORM_ATTRIBUTES = [ :fields, :database_url, ].freeze # Overwrite this method to customize how data sources are displayed # across all pages of the admin dashboard. # # def display_resource(data_source) # "DataSource ##{data_source.id}" # end end
26.654545
76
0.70191
18cdc1577a1bbdf9b3781072a7c3fbce35014fdf
2,603
require 'credentials_manager/appfile_config' require 'fastlane_core/print_table' require 'spaceship' require 'spaceship/tunes/tunes' require 'spaceship/tunes/members' require 'spaceship/test_flight' require 'fastlane_core/ipa_file_analyser' require_relative 'module' module Pilot class Manager def start(options, should_login: true) return if @config # to not login multiple times @config = options login if should_login end def login config[:username] ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id) UI.message("Login to App Store Connect (#{config[:username]})") Spaceship::Tunes.login(config[:username]) Spaceship::Tunes.select_team(team_id: config[:team_id], team_name: config[:team_name]) UI.message("Login successful") end # The app object we're currently using def app @app_id ||= fetch_app_id @app ||= Spaceship::ConnectAPI::App.get(app_id: @app_id) unless @app UI.user_error!("Could not find app with #{(config[:apple_id] || config[:app_identifier])}") end return @app end # Access the current configuration attr_reader :config # Config Related ################ def fetch_app_id @app_id ||= config[:apple_id] return @app_id if @app_id config[:app_identifier] = fetch_app_identifier if config[:app_identifier] @app ||= Spaceship::ConnectAPI::App.find(config[:app_identifier]) UI.user_error!("Couldn't find app '#{config[:app_identifier]}' on the account of '#{config[:username]}' on App Store Connect") unless @app @app_id ||= @app.id end @app_id ||= UI.input("Could not automatically find the app ID, please enter it here (e.g. 956814360): ") return @app_id end def fetch_app_identifier result = config[:app_identifier] result ||= FastlaneCore::IpaFileAnalyser.fetch_app_identifier(config[:ipa]) result ||= UI.input("Please enter the app's bundle identifier: ") UI.verbose("App identifier (#{result})") return result end def fetch_app_platform(required: true) result = config[:app_platform] result ||= FastlaneCore::IpaFileAnalyser.fetch_app_platform(config[:ipa]) if config[:ipa] if required result ||= UI.input("Please enter the app's platform (appletvos, ios, osx): ") UI.user_error!("App Platform must be ios, appletvos, or osx") unless ['ios', 'appletvos', 'osx'].include?(result) UI.verbose("App Platform (#{result})") end return result end end end
32.135802
146
0.667307
e94a97ec744cdf88fe75904111a7d240b1343742
32,210
#!/usr/bin/env ruby require 'spec_helper' describe Puppet::Type.type(:dsc_xrdsessioncollectionconfiguration) do let :dsc_xrdsessioncollectionconfiguration do Puppet::Type.type(:dsc_xrdsessioncollectionconfiguration).new( :name => 'foo', :dsc_collectionname => 'foo', ) end it 'should allow all properties to be specified' do expect { Puppet::Type.type(:dsc_xrdsessioncollectionconfiguration).new( :name => 'foo', :dsc_collectionname => 'foo', :dsc_activesessionlimitmin => 32, :dsc_authenticateusingnla => true, :dsc_automaticreconnectionenabled => true, :dsc_brokenconnectionaction => 'foo', :dsc_clientdeviceredirectionoptions => 'foo', :dsc_clientprinterasdefault => true, :dsc_clientprinterredirected => true, :dsc_collectiondescription => 'foo', :dsc_connectionbroker => 'foo', :dsc_customrdpproperty => 'foo', :dsc_disconnectedsessionlimitmin => 32, :dsc_encryptionlevel => 'foo', :dsc_idlesessionlimitmin => 32, :dsc_maxredirectedmonitors => 32, :dsc_rdeasyprintdriverenabled => true, :dsc_securitylayer => 'foo', :dsc_temporaryfoldersdeletedonexit => true, :dsc_usergroup => 'foo', )}.to_not raise_error end it "should stringify normally" do expect(dsc_xrdsessioncollectionconfiguration.to_s).to eq("Dsc_xrdsessioncollectionconfiguration[foo]") end it 'should require that dsc_collectionname is specified' do #dsc_xrdsessioncollectionconfiguration[:dsc_collectionname] expect { Puppet::Type.type(:dsc_xrdsessioncollectionconfiguration).new( :name => 'foo', )}.to raise_error(Puppet::Error, /dsc_collectionname is a required attribute/) end it 'should not accept array for dsc_collectionname' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_collectionname] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_collectionname' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_collectionname] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_collectionname' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_collectionname] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_collectionname' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_collectionname] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_activesessionlimitmin' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_activesessionlimitmin] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_activesessionlimitmin' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_activesessionlimitmin] = true}.to raise_error(Puppet::ResourceError) end it 'should accept uint for dsc_activesessionlimitmin' do dsc_xrdsessioncollectionconfiguration[:dsc_activesessionlimitmin] = 32 expect(dsc_xrdsessioncollectionconfiguration[:dsc_activesessionlimitmin]).to eq(32) end it 'should not accept signed (negative) value for dsc_activesessionlimitmin' do value = -32 expect(value).to be < 0 expect{dsc_xrdsessioncollectionconfiguration[:dsc_activesessionlimitmin] = value}.to raise_error(Puppet::ResourceError) end it 'should accept string-like uint for dsc_activesessionlimitmin' do dsc_xrdsessioncollectionconfiguration[:dsc_activesessionlimitmin] = '16' expect(dsc_xrdsessioncollectionconfiguration[:dsc_activesessionlimitmin]).to eq(16) end it 'should accept string-like uint for dsc_activesessionlimitmin' do dsc_xrdsessioncollectionconfiguration[:dsc_activesessionlimitmin] = '32' expect(dsc_xrdsessioncollectionconfiguration[:dsc_activesessionlimitmin]).to eq(32) end it 'should accept string-like uint for dsc_activesessionlimitmin' do dsc_xrdsessioncollectionconfiguration[:dsc_activesessionlimitmin] = '64' expect(dsc_xrdsessioncollectionconfiguration[:dsc_activesessionlimitmin]).to eq(64) end it 'should not accept array for dsc_authenticateusingnla' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should accept boolean for dsc_authenticateusingnla' do dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla] = true expect(dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla]).to eq(true) end it "should accept boolean-like value 'true' and munge this value to boolean for dsc_authenticateusingnla" do dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla] = 'true' expect(dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla]).to eq(true) end it "should accept boolean-like value 'false' and munge this value to boolean for dsc_authenticateusingnla" do dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla] = 'false' expect(dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla]).to eq(false) end it "should accept boolean-like value 'True' and munge this value to boolean for dsc_authenticateusingnla" do dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla] = 'True' expect(dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla]).to eq(true) end it "should accept boolean-like value 'False' and munge this value to boolean for dsc_authenticateusingnla" do dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla] = 'False' expect(dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla]).to eq(false) end it "should accept boolean-like value :true and munge this value to boolean for dsc_authenticateusingnla" do dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla] = :true expect(dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla]).to eq(true) end it "should accept boolean-like value :false and munge this value to boolean for dsc_authenticateusingnla" do dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla] = :false expect(dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla]).to eq(false) end it 'should not accept int for dsc_authenticateusingnla' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_authenticateusingnla' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_authenticateusingnla] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_automaticreconnectionenabled' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should accept boolean for dsc_automaticreconnectionenabled' do dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled] = true expect(dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled]).to eq(true) end it "should accept boolean-like value 'true' and munge this value to boolean for dsc_automaticreconnectionenabled" do dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled] = 'true' expect(dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled]).to eq(true) end it "should accept boolean-like value 'false' and munge this value to boolean for dsc_automaticreconnectionenabled" do dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled] = 'false' expect(dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled]).to eq(false) end it "should accept boolean-like value 'True' and munge this value to boolean for dsc_automaticreconnectionenabled" do dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled] = 'True' expect(dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled]).to eq(true) end it "should accept boolean-like value 'False' and munge this value to boolean for dsc_automaticreconnectionenabled" do dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled] = 'False' expect(dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled]).to eq(false) end it "should accept boolean-like value :true and munge this value to boolean for dsc_automaticreconnectionenabled" do dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled] = :true expect(dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled]).to eq(true) end it "should accept boolean-like value :false and munge this value to boolean for dsc_automaticreconnectionenabled" do dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled] = :false expect(dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled]).to eq(false) end it 'should not accept int for dsc_automaticreconnectionenabled' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_automaticreconnectionenabled' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_automaticreconnectionenabled] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_brokenconnectionaction' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_brokenconnectionaction] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_brokenconnectionaction' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_brokenconnectionaction] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_brokenconnectionaction' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_brokenconnectionaction] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_brokenconnectionaction' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_brokenconnectionaction] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_clientdeviceredirectionoptions' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_clientdeviceredirectionoptions] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_clientdeviceredirectionoptions' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_clientdeviceredirectionoptions] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_clientdeviceredirectionoptions' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_clientdeviceredirectionoptions] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_clientdeviceredirectionoptions' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_clientdeviceredirectionoptions] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_clientprinterasdefault' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should accept boolean for dsc_clientprinterasdefault' do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault] = true expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault]).to eq(true) end it "should accept boolean-like value 'true' and munge this value to boolean for dsc_clientprinterasdefault" do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault] = 'true' expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault]).to eq(true) end it "should accept boolean-like value 'false' and munge this value to boolean for dsc_clientprinterasdefault" do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault] = 'false' expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault]).to eq(false) end it "should accept boolean-like value 'True' and munge this value to boolean for dsc_clientprinterasdefault" do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault] = 'True' expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault]).to eq(true) end it "should accept boolean-like value 'False' and munge this value to boolean for dsc_clientprinterasdefault" do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault] = 'False' expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault]).to eq(false) end it "should accept boolean-like value :true and munge this value to boolean for dsc_clientprinterasdefault" do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault] = :true expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault]).to eq(true) end it "should accept boolean-like value :false and munge this value to boolean for dsc_clientprinterasdefault" do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault] = :false expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault]).to eq(false) end it 'should not accept int for dsc_clientprinterasdefault' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_clientprinterasdefault' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterasdefault] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_clientprinterredirected' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should accept boolean for dsc_clientprinterredirected' do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected] = true expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected]).to eq(true) end it "should accept boolean-like value 'true' and munge this value to boolean for dsc_clientprinterredirected" do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected] = 'true' expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected]).to eq(true) end it "should accept boolean-like value 'false' and munge this value to boolean for dsc_clientprinterredirected" do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected] = 'false' expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected]).to eq(false) end it "should accept boolean-like value 'True' and munge this value to boolean for dsc_clientprinterredirected" do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected] = 'True' expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected]).to eq(true) end it "should accept boolean-like value 'False' and munge this value to boolean for dsc_clientprinterredirected" do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected] = 'False' expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected]).to eq(false) end it "should accept boolean-like value :true and munge this value to boolean for dsc_clientprinterredirected" do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected] = :true expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected]).to eq(true) end it "should accept boolean-like value :false and munge this value to boolean for dsc_clientprinterredirected" do dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected] = :false expect(dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected]).to eq(false) end it 'should not accept int for dsc_clientprinterredirected' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_clientprinterredirected' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_clientprinterredirected] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_collectiondescription' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_collectiondescription] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_collectiondescription' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_collectiondescription] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_collectiondescription' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_collectiondescription] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_collectiondescription' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_collectiondescription] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_connectionbroker' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_connectionbroker] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_connectionbroker' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_connectionbroker] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_connectionbroker' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_connectionbroker] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_connectionbroker' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_connectionbroker] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_customrdpproperty' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_customrdpproperty] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_customrdpproperty' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_customrdpproperty] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_customrdpproperty' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_customrdpproperty] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_customrdpproperty' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_customrdpproperty] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_disconnectedsessionlimitmin' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_disconnectedsessionlimitmin] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_disconnectedsessionlimitmin' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_disconnectedsessionlimitmin] = true}.to raise_error(Puppet::ResourceError) end it 'should accept uint for dsc_disconnectedsessionlimitmin' do dsc_xrdsessioncollectionconfiguration[:dsc_disconnectedsessionlimitmin] = 32 expect(dsc_xrdsessioncollectionconfiguration[:dsc_disconnectedsessionlimitmin]).to eq(32) end it 'should not accept signed (negative) value for dsc_disconnectedsessionlimitmin' do value = -32 expect(value).to be < 0 expect{dsc_xrdsessioncollectionconfiguration[:dsc_disconnectedsessionlimitmin] = value}.to raise_error(Puppet::ResourceError) end it 'should accept string-like uint for dsc_disconnectedsessionlimitmin' do dsc_xrdsessioncollectionconfiguration[:dsc_disconnectedsessionlimitmin] = '16' expect(dsc_xrdsessioncollectionconfiguration[:dsc_disconnectedsessionlimitmin]).to eq(16) end it 'should accept string-like uint for dsc_disconnectedsessionlimitmin' do dsc_xrdsessioncollectionconfiguration[:dsc_disconnectedsessionlimitmin] = '32' expect(dsc_xrdsessioncollectionconfiguration[:dsc_disconnectedsessionlimitmin]).to eq(32) end it 'should accept string-like uint for dsc_disconnectedsessionlimitmin' do dsc_xrdsessioncollectionconfiguration[:dsc_disconnectedsessionlimitmin] = '64' expect(dsc_xrdsessioncollectionconfiguration[:dsc_disconnectedsessionlimitmin]).to eq(64) end it 'should not accept array for dsc_encryptionlevel' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_encryptionlevel] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_encryptionlevel' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_encryptionlevel] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_encryptionlevel' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_encryptionlevel] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_encryptionlevel' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_encryptionlevel] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_idlesessionlimitmin' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_idlesessionlimitmin] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_idlesessionlimitmin' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_idlesessionlimitmin] = true}.to raise_error(Puppet::ResourceError) end it 'should accept uint for dsc_idlesessionlimitmin' do dsc_xrdsessioncollectionconfiguration[:dsc_idlesessionlimitmin] = 32 expect(dsc_xrdsessioncollectionconfiguration[:dsc_idlesessionlimitmin]).to eq(32) end it 'should not accept signed (negative) value for dsc_idlesessionlimitmin' do value = -32 expect(value).to be < 0 expect{dsc_xrdsessioncollectionconfiguration[:dsc_idlesessionlimitmin] = value}.to raise_error(Puppet::ResourceError) end it 'should accept string-like uint for dsc_idlesessionlimitmin' do dsc_xrdsessioncollectionconfiguration[:dsc_idlesessionlimitmin] = '16' expect(dsc_xrdsessioncollectionconfiguration[:dsc_idlesessionlimitmin]).to eq(16) end it 'should accept string-like uint for dsc_idlesessionlimitmin' do dsc_xrdsessioncollectionconfiguration[:dsc_idlesessionlimitmin] = '32' expect(dsc_xrdsessioncollectionconfiguration[:dsc_idlesessionlimitmin]).to eq(32) end it 'should accept string-like uint for dsc_idlesessionlimitmin' do dsc_xrdsessioncollectionconfiguration[:dsc_idlesessionlimitmin] = '64' expect(dsc_xrdsessioncollectionconfiguration[:dsc_idlesessionlimitmin]).to eq(64) end it 'should not accept array for dsc_maxredirectedmonitors' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_maxredirectedmonitors] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_maxredirectedmonitors' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_maxredirectedmonitors] = true}.to raise_error(Puppet::ResourceError) end it 'should accept uint for dsc_maxredirectedmonitors' do dsc_xrdsessioncollectionconfiguration[:dsc_maxredirectedmonitors] = 32 expect(dsc_xrdsessioncollectionconfiguration[:dsc_maxredirectedmonitors]).to eq(32) end it 'should not accept signed (negative) value for dsc_maxredirectedmonitors' do value = -32 expect(value).to be < 0 expect{dsc_xrdsessioncollectionconfiguration[:dsc_maxredirectedmonitors] = value}.to raise_error(Puppet::ResourceError) end it 'should accept string-like uint for dsc_maxredirectedmonitors' do dsc_xrdsessioncollectionconfiguration[:dsc_maxredirectedmonitors] = '16' expect(dsc_xrdsessioncollectionconfiguration[:dsc_maxredirectedmonitors]).to eq(16) end it 'should accept string-like uint for dsc_maxredirectedmonitors' do dsc_xrdsessioncollectionconfiguration[:dsc_maxredirectedmonitors] = '32' expect(dsc_xrdsessioncollectionconfiguration[:dsc_maxredirectedmonitors]).to eq(32) end it 'should accept string-like uint for dsc_maxredirectedmonitors' do dsc_xrdsessioncollectionconfiguration[:dsc_maxredirectedmonitors] = '64' expect(dsc_xrdsessioncollectionconfiguration[:dsc_maxredirectedmonitors]).to eq(64) end it 'should not accept array for dsc_rdeasyprintdriverenabled' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should accept boolean for dsc_rdeasyprintdriverenabled' do dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled] = true expect(dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled]).to eq(true) end it "should accept boolean-like value 'true' and munge this value to boolean for dsc_rdeasyprintdriverenabled" do dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled] = 'true' expect(dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled]).to eq(true) end it "should accept boolean-like value 'false' and munge this value to boolean for dsc_rdeasyprintdriverenabled" do dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled] = 'false' expect(dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled]).to eq(false) end it "should accept boolean-like value 'True' and munge this value to boolean for dsc_rdeasyprintdriverenabled" do dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled] = 'True' expect(dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled]).to eq(true) end it "should accept boolean-like value 'False' and munge this value to boolean for dsc_rdeasyprintdriverenabled" do dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled] = 'False' expect(dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled]).to eq(false) end it "should accept boolean-like value :true and munge this value to boolean for dsc_rdeasyprintdriverenabled" do dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled] = :true expect(dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled]).to eq(true) end it "should accept boolean-like value :false and munge this value to boolean for dsc_rdeasyprintdriverenabled" do dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled] = :false expect(dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled]).to eq(false) end it 'should not accept int for dsc_rdeasyprintdriverenabled' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_rdeasyprintdriverenabled' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_rdeasyprintdriverenabled] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_securitylayer' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_securitylayer] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_securitylayer' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_securitylayer] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_securitylayer' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_securitylayer] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_securitylayer' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_securitylayer] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_temporaryfoldersdeletedonexit' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should accept boolean for dsc_temporaryfoldersdeletedonexit' do dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit] = true expect(dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit]).to eq(true) end it "should accept boolean-like value 'true' and munge this value to boolean for dsc_temporaryfoldersdeletedonexit" do dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit] = 'true' expect(dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit]).to eq(true) end it "should accept boolean-like value 'false' and munge this value to boolean for dsc_temporaryfoldersdeletedonexit" do dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit] = 'false' expect(dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit]).to eq(false) end it "should accept boolean-like value 'True' and munge this value to boolean for dsc_temporaryfoldersdeletedonexit" do dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit] = 'True' expect(dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit]).to eq(true) end it "should accept boolean-like value 'False' and munge this value to boolean for dsc_temporaryfoldersdeletedonexit" do dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit] = 'False' expect(dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit]).to eq(false) end it "should accept boolean-like value :true and munge this value to boolean for dsc_temporaryfoldersdeletedonexit" do dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit] = :true expect(dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit]).to eq(true) end it "should accept boolean-like value :false and munge this value to boolean for dsc_temporaryfoldersdeletedonexit" do dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit] = :false expect(dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit]).to eq(false) end it 'should not accept int for dsc_temporaryfoldersdeletedonexit' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_temporaryfoldersdeletedonexit' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_temporaryfoldersdeletedonexit] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_usergroup' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_usergroup] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_usergroup' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_usergroup] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_usergroup' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_usergroup] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_usergroup' do expect{dsc_xrdsessioncollectionconfiguration[:dsc_usergroup] = 16}.to raise_error(Puppet::ResourceError) end # Configuration PROVIDER TESTS describe "powershell provider tests" do it "should successfully instanciate the provider" do described_class.provider(:powershell).new(dsc_xrdsessioncollectionconfiguration) end before(:each) do @provider = described_class.provider(:powershell).new(dsc_xrdsessioncollectionconfiguration) end describe "when dscmeta_module_name existing/is defined " do it "should compute powershell dsc test script with Invoke-DscResource" do expect(@provider.ps_script_content('test')).to match(/Invoke-DscResource/) end it "should compute powershell dsc test script with method Test" do expect(@provider.ps_script_content('test')).to match(/Method\s+=\s*'test'/) end it "should compute powershell dsc set script with Invoke-DscResource" do expect(@provider.ps_script_content('set')).to match(/Invoke-DscResource/) end it "should compute powershell dsc test script with method Set" do expect(@provider.ps_script_content('set')).to match(/Method\s+=\s*'set'/) end end end end
49.937984
149
0.804067
e2ff488a7540ec323d664fa1dca12efad8d66f38
235
module Licenses class UsageReportDecorator < ApplicationDecorator delegate_all def to_s if object.end_date > Time.zone.today "#{object.to_s} (Current)" else object.to_s end end end end
18.076923
51
0.638298
1d73b3974db51db9efddcd8182ba2ff0cc48a556
613
unless ENV['MSPEC_RUNNER'] begin require 'mspec/helpers' require 'mspec/guards' require 'mspec/runner/shared' require 'mspec/matchers/be_ancestor_of' require 'mspec/matchers/output' require 'mspec/matchers/output_to_fd' require 'mspec/matchers/complain' TOLERANCE = 0.00003 unless Object.const_defined?(:TOLERANCE) rescue LoadError puts "Please install the MSpec gem to run the specs." exit 1 end end unless ENV['OUTPUT_WARNINGS'] $verbose = $VERBOSE $VERBOSE = nil at_exit { $VERBOSE = $verbose } end def has_tty? if STDOUT.tty? then yield end end
20.433333
64
0.7031
ff0b3c527ddd6c6e7fb81fff7bfdc776dc90f925
1,524
# Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Eatech CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/accounts/index" do include AccountsHelper before do view.lookup_context.prefixes << 'entities' assign :per_page, Account.per_page assign :sort_by, Account.sort_by assign :ransack_search, Account.ransack login_and_assign end it "should render account name" do assign(:accounts, [FactoryGirl.build_stubbed(:account, name: 'New Media Inc'), FactoryGirl.build_stubbed(:account)].paginate) render expect(rendered).to have_tag('a', text: "New Media Inc") end it "should render list of accounts if list of accounts is not empty" do assign(:accounts, [FactoryGirl.build_stubbed(:account), FactoryGirl.build_stubbed(:account)].paginate) render expect(view).to render_template(partial: "_account") expect(view).to render_template(partial: "shared/_paginate_with_per_page") end it "should render a message if there're no accounts" do assign(:accounts, [].paginate) render expect(view).not_to render_template(partial: "_account") expect(view).to render_template(partial: "shared/_empty") expect(view).to render_template(partial: "shared/_paginate_with_per_page") end end
36.285714
129
0.7021
1c51c8cdf10e7b3e0a758a5d0b7422975ec90995
1,736
#-- copyright # OpenProject is an open source project management software. # Copyright (C) 2012-2020 the OpenProject GmbH # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-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. #++ module Plugins module LoadPathHelper def self.spec_load_paths plugin_load_paths.map { |path| File.join(path, 'spec') }.keep_if{ |path| File.directory?(path) } end def self.cucumber_load_paths plugin_load_paths.map { |path| File.join(path, 'features') }.keep_if{ |path| File.directory?(path) } end private # fetch load paths for available plugins def self.plugin_load_paths Rails.application.config.plugins_to_test_paths.map(&:to_s) end end end
34.039216
91
0.732719
1844f3484e3f4382070284c9dfe3186fa576c2ca
2,180
# encoding: utf-8 # This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # /spec/fixtures/responses/durban-whois.registry.net.za/durban/status_available.expected # # and regenerate the tests with the following rake task # # $ rake spec:generate # require 'spec_helper' require 'whois/record/parser/durban-whois.registry.net.za.rb' describe Whois::Record::Parser::DurbanWhoisRegistryNetZa, "status_available.expected" do subject do file = fixture("responses", "durban-whois.registry.net.za/durban/status_available.txt") part = Whois::Record::Part.new(body: File.read(file)) described_class.new(part) end describe "#domain" do it do expect(subject.domain).to eq(nil) end end describe "#domain_id" do it do expect(subject.domain_id).to eq(nil) end end describe "#status" do it do expect(subject.status).to eq(:available) end end describe "#available?" do it do expect(subject.available?).to eq(true) end end describe "#registered?" do it do expect(subject.registered?).to eq(false) end end describe "#created_on" do it do expect(subject.created_on).to eq(nil) end end describe "#updated_on" do it do expect(subject.updated_on).to eq(nil) end end describe "#expires_on" do it do expect(subject.expires_on).to eq(nil) end end describe "#registrar" do it do expect(subject.registrar).to eq(nil) end end describe "#registrant_contacts" do it do expect(subject.registrant_contacts).to be_a(Array) expect(subject.registrant_contacts).to eq([]) end end describe "#admin_contacts" do it do expect(subject.admin_contacts).to be_a(Array) expect(subject.admin_contacts).to eq([]) end end describe "#technical_contacts" do it do expect(subject.technical_contacts).to be_a(Array) expect(subject.technical_contacts).to eq([]) end end describe "#nameservers" do it do expect(subject.nameservers).to be_a(Array) expect(subject.nameservers).to eq([]) end end end
23.191489
91
0.675688
b94148b0f85b66c5666ee9453d6dd5a9070ed5e2
688
module PapersHelper def selected_class(tab_name) if controller.action_name == tab_name "selected" end end def badge_link(paper) if paper.accepted? return paper.cross_ref_doi_url else return paper.review_url end end def formatted_body(paper, length=nil) pipeline = HTML::Pipeline.new [ HTML::Pipeline::MarkdownFilter, HTML::Pipeline::SanitizationFilter ] if length body = paper.body.truncate(length, separator: /\s/) else body = paper.body end result = pipeline.call(body) result[:output].to_s.html_safe end def paper_types Rails.application.settings["paper_types"] end end
19.111111
57
0.668605
21b231278a436df9280e700d495b5acce908fe7d
519
module TokyoMetro::Factory::Seed::Reference::TrainTypeInApi private def in_api_in_db( whole = nil , search_by: @train_type ) if whole.present? whole.find_by_same_as( search_by ) else ::Train::Type::InApi.find_by_same_as( search_by ) end end def in_api_id( whole = nil , search_by: @train_type ) _in_api_in_db = in_api_in_db( whole , search_by: search_by ) raise "Error: \"#{ search_by }\" does not exist in the database." if _in_api_in_db.nil? _in_api_in_db.id end end
25.95
91
0.693642
61569947ad1120380fbc10567de7c24cb5047ef9
6,625
# frozen_string_literal: true require 'forwardable' require 'evolvable/version' require 'evolvable/error/undefined_method' require 'evolvable/gene' require 'evolvable/search_space' require 'evolvable/genome' require 'evolvable/goal' require 'evolvable/equalize_goal' require 'evolvable/maximize_goal' require 'evolvable/minimize_goal' require 'evolvable/evaluation' require 'evolvable/evolution' require 'evolvable/selection' require 'evolvable/gene_combination' require 'evolvable/point_crossover' require 'evolvable/uniform_crossover' require 'evolvable/mutation' require 'evolvable/population' require 'evolvable/count_gene' require 'evolvable/rigid_count_gene' require 'evolvable/serializer' # # @readme # The `Evolvable` module makes it possible to implement evolutionary behaviors for # any class by defining a `.search_space` class method and `#value` instance method. # To evolve instances, initialize a population with `.new_population` and use the # `Evolvable::Population#evolve` instance method. # # 1. [Include the `Evolvable` module in the class you want to evolve.](https://rubydoc.info/github/mattruzicka/Evolvable) # 2. [Define `.search_space` and any gene classes that you reference.](https://rubydoc.info/github/mattruzicka/Evolvable/SearchSpace) # 3. [Define `#value`.](https://rubydoc.info/github/mattruzicka/Evolvable/Evaluation) # 4. [Initialize a population with `.new_population` and use `#evolve`.](https://rubydoc.info/github/mattruzicka/Evolvable/Population) # module Evolvable extend Forwardable def self.included(base) base.extend(ClassMethods) end module ClassMethods # # @readme # Initializes a population using configurable defaults that can be configured and optimized. # Accepts the same named parameters as # [Population#initialize](https://rubydoc.info/github/mattruzicka/evolvable/Evolvable/Population#initialize). # def new_population(keyword_args = {}) keyword_args[:evolvable_type] = self Population.new(**keyword_args) end # # Initializes a new instance. Accepts a population object, an array of gene objects, # and the instance's population index. This method is useful for re-initializing # instances and populations that have been saved. # # _It is not recommended that you override this method_ as it is used by # Evolvable internals. If you need to customize how your instances are # initialized you can override either of the following two "initialize_instance" # methods. # def new_evolvable(population: nil, genome: Genome.new, generation_index: nil) evolvable = initialize_evolvable evolvable.population = population evolvable.genome = genome evolvable.generation_index = generation_index evolvable.after_initialize evolvable end def initialize_evolvable new end def new_search_space space_config = search_space.empty? ? gene_space : search_space search_space = SearchSpace.build(space_config, self) search_spaces.each { |space| search_space.merge_search_space!(space) } search_space end # # @abstract # # This method is responsible for configuring the available gene types # of evolvable instances. In effect, it provides the # blueprint for constructing a hyperdimensional genetic space that's capable # of being used and searched by evolvable objects. # # Override this method with a search space config for initializing # SearchSpace objects. The config can be a hash, array of arrays, # or single array when there's only one type of gene. # # The below example definitions could conceivably be used to generate evolvable music. # # @todo # Define gene config attributes - name, type, count # # @example Hash config # def search_space # { instrument: { type: InstrumentGene, count: 1..4 }, # notes: { type: NoteGene, count: 16 } } # end # @example Array of arrays config # # With explicit gene names # def search_space # [[:instrument, InstrumentGene, 1..4], # [:notes, NoteGene, 16]] # end # # # Without explicit gene names # def search_space # [[SynthGene, 0..4], [RhythmGene, 0..8]] # end # @example Array config # # Available when when just one type of gene # def search_space # [NoteGene, 1..100] # end # # # With explicit gene type name. # def search_space # ['notes', 'NoteGene', 1..100] # end # # @return [Hash, Array] # # @see https://github.com/mattruzicka/evolvable#search_space # def search_space {} end # # @abstract Override this method to define multiple search spaces # # @return [Array] # # @see https://github.com/mattruzicka/evolvable#search_space # def search_spaces [] end # @deprecated # Will be removed in version 2.0. # Use {#search_space} instead. def gene_space {} end # # @readme # Runs before evaluation. # def before_evaluation(population); end # # @readme # Runs after evaluation and before evolution. # # @example # class Melody # include Evolvable # # # Play the best melody from each generation # def self.before_evolution(population) # population.best_evolvable.play # end # # # ... # end # def before_evolution(population); end # # @readme # Runs after evolution. # def after_evolution(population); end end # Runs an evolvable is initialized. Ueful for implementing custom initialization logic. def after_initialize; end # # @!method value # Implementing this method is required for evaluation and selection. # attr_accessor :id, :population, :genome, :generation_index, :value # # @deprecated # Will be removed in version 2.0. # Use {#generation_index} instead. # def population_index generation_index end # # @!method find_gene # @see Genome#find_gene # @!method find_genes # @see Genome#find_genes # @!method find_genes_count # @see Genome#find_genes_count # @!method genes # @see Genome#genes # def_delegators :genome, :find_gene, :find_genes, :find_genes_count, :genes end
28.804348
136
0.661887
874faf920d06e11a8fb62b2f0f6a1b05cd981283
784
class PublicKeyResource < ApplicationResource attributes :name, :fingerprint, :key, :last_used_at has_one :group has_one :person before_create do @model.group = context[:group] @model.person = context[:current_user] end def fingerprint @model.fingerprint end def last_used_at @model.builds.order('created_at desc').limit(1).first.try(:created_at) end def updateable_fields super - [:name, :fingerprint, :key, :last_used_at, :person, :group] end def creatable_fields super - [:fingerprint, :last_used_at, :person, :group] end def fetchable_fields super - [:key] end def self.records(options={}) if options[:context][:current_user].try(:staff?) options[:context][:current_user].public_keys end end end
20.631579
74
0.693878
1a910b90873a898382f3ced2af3c80c9fd2f3422
583
# frozen_string_literal: true module Correios module CEP module Config WEB_SERVICE_URL = 'https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente' DEFAULT_REQUEST_TIMEOUT = 5 # seconds attr_accessor :logger, :proxy_url attr_writer :request_timeout, :web_service_url def request_timeout (@request_timeout ||= DEFAULT_REQUEST_TIMEOUT).to_i end def web_service_url @web_service_url ||= WEB_SERVICE_URL end def configure yield self if block_given? end end end end
23.32
104
0.692967
f7c2932242d6c535779c02ca89f44d3057ad7f59
82
class Garden < ApplicationRecord has_many :plants, :dependent => :destroy end
20.5
44
0.743902
e90312cf5739cdd3b6f135fce718d69e82de2544
1,054
class ModalPage include PageObject button(:launch_modal, :id => 'launch_modal_button') end class ModalDialog include PageObject button(:close_window, :id => 'close_window') button(:close_window_with_delay, :id => 'delayed_close') button(:launch_another_modal, :id => 'launch_modal_button') end class AnotherModalDialog include PageObject button(:close_window, :id => 'close_window2') button(:close_window_with_delay, :id => 'delayed_close2') end Given /^I am on the modal page$/ do ModalPage.new(@browser).navigate_to(UrlHelper.modal) end When /^I open a modal dialog$/ do page = ModalPage.new(@browser) page.modal_dialog do page.launch_modal end end Then /^I should be able to close the modal$/ do dialog = ModalDialog.new(@browser) dialog.attach_to_window(:title => 'Modal 1') do dialog.close_window end end When /^I open another modal dialog from that one$/ do dialog = ModalDialog.new(@browser) dialog.attach_to_window(:title => 'Modal 1') dialog.modal_dialog dialog.launch_another_modal end
22.425532
61
0.737192
28687f26977fcc0033db32661edac3caa96d4d85
3,207
require 'fastimage' module MetaInspector module Parsers class ImagesParser < Base delegate [:parsed, :meta, :base_url] => :@main_parser delegate [:each, :length, :size, :[], :last] => :images_collection include Enumerable def initialize(main_parser, options = {}) @download_images = options[:download_images] super(main_parser) end def images self end # Returns either the Facebook Open Graph image, twitter suggested image or # the largest image in the image collection def best owner_suggested || largest end # Returns the parsed image from Facebook's open graph property tags # Most major websites now define this property and is usually relevant # See doc at http://developers.facebook.com/docs/opengraph/ # If none found, tries with Twitter image def owner_suggested suggested_img = content_of(meta['og:image']) || content_of(meta['twitter:image']) URL.absolutify(suggested_img, base_url) if suggested_img end # Returns an array of [img_url, width, height] sorted by image area (width * height) def with_size @with_size ||= begin img_nodes = parsed.search('//img').select{ |img_node| img_node['src'] } imgs_with_size = img_nodes.map { |img_node| [URL.absolutify(img_node['src'], base_url), img_node['width'], img_node['height']] } imgs_with_size.uniq! { |url, width, height| url } if @download_images imgs_with_size.map! do |url, width, height| width, height = FastImage.size(url) if width.nil? || height.nil? [url, width.to_i, height.to_i] end else imgs_with_size.map! do |url, width, height| width, height = [0, 0] if width.nil? || height.nil? [url, width.to_i, height.to_i] end end imgs_with_size.sort_by { |url, width, height| -(width.to_i * height.to_i) } end end # Returns the largest image from the image collection, # filtered for images that are more square than 10:1 or 1:10 def largest @largest_image ||= begin imgs_with_size = with_size.dup imgs_with_size.keep_if do |url, width, height| ratio = width.to_f / height.to_f ratio > 0.1 && ratio < 10 end url, width, height = imgs_with_size.first url end end # Return favicon url if exist def favicon query = '//link[@rel="icon" or contains(@rel, "shortcut")]' value = parsed.xpath(query)[0].attributes['href'].value @favicon ||= URL.absolutify(value, base_url) rescue nil end private def images_collection @images_collection ||= absolutified_images end def absolutified_images parsed_images.map { |i| URL.absolutify(i, base_url) } end def parsed_images cleanup(parsed.search('//img/@src')) end def content_of(content) return nil if content.nil? || content.empty? content end end end end
32.07
138
0.600873
625232a3c27e29fffd855aed5acbc131594caf90
1,087
#! /usr/bin/env ruby # -*- coding: UTF-8 -*- # require 'efl' require 'efl/native/elm/elm_store' # module Efl # module Elm # class ElmStore # include Efl::ClassHelper search_prefixes 'elm_store_' # def initialize o=nil, &block @ptr = ( case o when NilClass FFI::AutoPointer.new Native.elm_store_filesystem_new, ElmStore.method(:release) when FFI::Pointer o else raise ArgumentError.new "wrong argument #{o.class.name}" end ) instance_eval &block if block end def self.release p Native.elm_store_free p end def free @ptr.autorelease=false if @ptr.is_a? FFI::AutoPointer ElmStore.release @ptr @ptr=nil end # end # end end # # EOF
24.704545
103
0.431463
798b949d54ec6aedd4787c62e9dfceb69df50e39
667
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module GomiSellersAdmin class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 6.0 # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. end end
33.35
82
0.767616
1a31a429bef50063b2eabc9144b3840fb7a5bafa
2,630
class ApplicationController < ActionController::Base protect_from_forgery before_action :cache_most_used_page_information before_action :cache_forums_unread_counts # todo name all these methods before_action do if params[:universe].present? && user_signed_in? if params[:universe] == 'all' session.delete(:universe_id) elsif params[:universe].is_a?(String) && params[:universe].to_i.to_s == params[:universe] found_universe = Universe.find_by(id: params[:universe]) found_universe = nil unless current_user.universes.include?(found_universe) || current_user.contributable_universes.include?(found_universe) session[:universe_id] = found_universe.id if found_universe end end end before_action do if current_user && session[:universe_id] @universe_scope = Universe.find_by(id: session[:universe_id]) @universe_scope = nil unless current_user.universes.include?(@universe_scope) || current_user.contributable_universes.include?(@universe_scope) else @universe_scope = nil end end before_action do @page_title ||= '' @page_keywords ||= %w[writing author nanowrimo novel character fiction fantasy universe creative dnd roleplay larp game design] @page_description ||= 'Notebook.ai is a set of tools for writers, game designers, and roleplayers to create magnificent universes — and everything within them.' end def content_type_from_controller(content_controller_name) content_controller_name.to_s.chomp('Controller').singularize.constantize end private # Cache some super-common stuff we need for every page. For example, content lists for the side nav. def cache_most_used_page_information return unless user_signed_in? @activated_content_types = ( Rails.application.config.content_types[:all].map(&:name) & # Use config to dictate order, but AND to only include what a user has turned on current_user.user_content_type_activators.pluck(:content_type) ) # We always want to cache Universes, even if they aren't explicitly turned on. @current_user_content = current_user.content(content_types: @activated_content_types + ['Universe']) @current_user_content['Document'] = current_user.documents end def cache_forums_unread_counts @unread_threads = if user_signed_in? Thredded::Topic.unread_followed_by(current_user).count else 0 end @unread_private_messages = if user_signed_in? Thredded::PrivateTopic .for_user(current_user) .unread(current_user) .count else 0 end end end
36.027397
164
0.738783
1a5a45a7b050c4ea0f1f07996039e625ed62c336
5,533
class AnimeDownloader < Formula include Language::Python::Virtualenv desc "Download your favourite anime" homepage "https://github.com/vn-ki/anime-downloader" url "https://files.pythonhosted.org/packages/f5/61/feb32904b5fa1d1e36908bb781f722e924402e329dbb538ce5cb5eb8c44c/anime-downloader-4.3.0.tar.gz" sha256 "761a0be674a63438b0bce680eebba651fbb8624f14d9c84390d63515e033aff7" license "Unlicense" head "https://github.com/vn-ki/anime-downloader.git" bottle do cellar :any_skip_relocation sha256 "afabaec3f49758f2d6c802a3f6cc732d359bc1aa4f96102d5bbb5db7cb28851f" => :catalina sha256 "7c10ffe30e521687890945769fe95f9d3f08262e8d9a3055072a63b749d9cb26" => :mojave sha256 "842d8ee3c6fc388e9bfb18f9d05f3c07bdeb9aa6b77a218fb05b0803036cd942" => :high_sierra sha256 "e2385d6ea12815ed985d300d6d74664949531850e644d1f664692fc6086c0443" => :x86_64_linux end depends_on "aria2" depends_on "node" depends_on "[email protected]" resource "beautifulsoup4" do url "https://files.pythonhosted.org/packages/52/ba/0e121661f529e7f456e903bf5c4d255b8051d8ce2b5e629c5212efe4c3f1/beautifulsoup4-4.8.2.tar.gz" sha256 "05fd825eb01c290877657a56df4c6e4c311b3965bda790c613a3d6fb01a5462a" end resource "certifi" do url "https://files.pythonhosted.org/packages/41/bf/9d214a5af07debc6acf7f3f257265618f1db242a3f8e49a9b516f24523a6/certifi-2019.11.28.tar.gz" sha256 "25b64c7da4cd7479594d035c08c2d809eb4aab3a26e5a990ea98cc450c320f1f" end resource "cfscrape" do url "https://files.pythonhosted.org/packages/a6/3d/12044a9a927559b2fe09d60b1cd6cd4ed1e062b7a28f15c91367b9ec78f1/cfscrape-2.1.1.tar.gz" sha256 "7c5ef94554e0d6ee7de7cd0d42051526e716ce6c0357679ee0b82c49e189e2ef" end resource "chardet" do url "https://files.pythonhosted.org/packages/fc/bb/a5768c230f9ddb03acc9ef3f0d4a3cf93462473795d18e9535498c8f929d/chardet-3.0.4.tar.gz" sha256 "84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae" end resource "click" do url "https://files.pythonhosted.org/packages/4e/ab/5d6bc3b697154018ef196f5b17d958fac3854e2efbc39ea07a284d4a6a9b/click-7.1.1.tar.gz" sha256 "8a18b4ea89d8820c5d0c7da8a64b2c324b4dabb695804dbfea19b9be9d88c0cc" end resource "coloredlogs" do url "https://files.pythonhosted.org/packages/84/1b/1ecdd371fa68839cfbda15cc671d0f6c92d2c42688df995a9bf6e36f3511/coloredlogs-14.0.tar.gz" sha256 "a1fab193d2053aa6c0a97608c4342d031f1f93a3d1218432c59322441d31a505" end resource "fuzzywuzzy" do url "https://files.pythonhosted.org/packages/11/4b/0a002eea91be6048a2b5d53c5f1b4dafd57ba2e36eea961d05086d7c28ce/fuzzywuzzy-0.18.0.tar.gz" sha256 "45016e92264780e58972dca1b3d939ac864b78437422beecebb3095f8efd00e8" end resource "humanfriendly" do url "https://files.pythonhosted.org/packages/2e/d1/e0d8db85b71fc6e7d5be7d78bb5db64c63790aec45acef6578190d66c666/humanfriendly-8.1.tar.gz" sha256 "25c2108a45cfd1e8fbe9cdb30b825d34ef5d5675c8e11e4775c9aedbfb0bdee2" end resource "idna" do url "https://files.pythonhosted.org/packages/cb/19/57503b5de719ee45e83472f339f617b0c01ad75cba44aba1e4c97c2b0abd/idna-2.9.tar.gz" sha256 "7588d1c14ae4c77d74036e8c22ff447b26d0fde8f007354fd48a7814db15b7cb" end resource "pycryptodome" do url "https://files.pythonhosted.org/packages/69/2a/298b2689bee8e88c502c7e85ba1c9f07c7e182ea91c705c449f693056c9f/pycryptodome-3.9.7.tar.gz" sha256 "f1add21b6d179179b3c177c33d18a2186a09cc0d3af41ff5ed3f377360b869f2" end resource "requests" do url "https://files.pythonhosted.org/packages/f5/4f/280162d4bd4d8aad241a21aecff7a6e46891b905a4341e7ab549ebaf7915/requests-2.23.0.tar.gz" sha256 "b3f43d496c6daba4493e7c431722aeb7dbc6288f52a6e04e7b6023b0247817e6" end resource "requests-cache" do url "https://files.pythonhosted.org/packages/0c/d4/bdc22aad6979ceeea2638297f213108aeb5e25c7b103fa02e4acbe43992e/requests-cache-0.5.2.tar.gz" sha256 "813023269686045f8e01e2289cc1e7e9ae5ab22ddd1e2849a9093ab3ab7270eb" end resource "soupsieve" do url "https://files.pythonhosted.org/packages/15/53/3692c565aea19f7d9dd696fee3d0062782e9ad5bf9535267180511a15967/soupsieve-2.0.tar.gz" sha256 "e914534802d7ffd233242b785229d5ba0766a7f487385e3f714446a07bf540ae" end resource "tabulate" do url "https://files.pythonhosted.org/packages/c4/41/523f6a05e6dc3329a5660f6a81254c6cd87e5cfb5b7482bae3391d86ec3a/tabulate-0.8.6.tar.gz" sha256 "5470cc6687a091c7042cee89b2946d9235fe9f6d49c193a4ae2ac7bf386737c8" end resource "urllib3" do url "https://files.pythonhosted.org/packages/09/06/3bc5b100fe7e878d3dee8f807a4febff1a40c213d2783e3246edde1f3419/urllib3-1.25.8.tar.gz" sha256 "87716c2d2a7121198ebcb7ce7cccf6ce5e9ba539041cfbaeecfb641dc0bf6acc" end def install venv = virtualenv_create(libexec, "python3") venv.pip_install "beautifulsoup4" venv.pip_install "certifi" venv.pip_install "cfscrape" venv.pip_install "chardet" venv.pip_install "Click" venv.pip_install "coloredlogs" venv.pip_install "fuzzywuzzy" venv.pip_install "humanfriendly" venv.pip_install "idna" venv.pip_install "pycryptodome" venv.pip_install "requests" venv.pip_install "requests-cache" venv.pip_install "soupsieve" venv.pip_install "tabulate" venv.pip_install "urllib3" venv.pip_install_and_link buildpath end test do assert_match "anime, version #{version}", shell_output("#{bin}/anime --version") assert_match "Watch is deprecated in favour of adl", shell_output("#{bin}/anime watch 2>&1") end end
44.620968
144
0.813483
bfeece6e5a3a8741cdd1014388fd2c2f2d372732
443
# @class NodeSerializer # 节点 # # == attributes # - *id* [Integer] 编号 # - *name* [String] 节点名称 # - *summary* [String] 简介, Markdown 格式 # - *section_id* [Integer] 大类别编号 # - *section_name* [String] 大类别名称 # - *topics_count* [Integer] 话题数量 # - *sort* {Integer} 排序优先级 # - *updated_at* [DateTime] 更新时间 if node json.cache! ["v1", node] do json.(node, :id, :name, :topics_count, :summary, :section_id, :sort, :section_name, :updated_at) end end
24.611111
100
0.643341
282bdf744d2c74119903873abef25835a55134cf
811
module MilestonesHelper def milestones_filter_path(opts = {}) if @project namespace_project_milestones_path(@project.namespace, @project, opts) elsif @group group_milestones_path(@group, opts) else dashboard_milestones_path(opts) end end def milestone_progress_bar(milestone) options = { class: 'progress-bar progress-bar-success', style: "width: #{milestone.percent_complete}%;" } content_tag :div, class: 'progress' do content_tag :div, nil, options end end def projects_milestones_options milestones = if @project @project.milestones else Milestone.where(project_id: @projects) end.active options_from_collection_for_select(milestones, 'id', 'title', params[:milestone_id]) end end
23.852941
88
0.683107
08da65c949ab356d353bd325fd17373038883225
1,172
require "charlock_holmes" require "gifts/grit_ext/actor" require "gifts/grit_ext/blob" require "gifts/grit_ext/commit" require "gifts/grit_ext/tree" require "gifts/grit_ext/diff" require "gifts/grit_ext/version" module Gifts::GritExt extend self def encode!(message) return nil unless message.respond_to? :force_encoding # if message is utf-8 encoding, just return it message.force_encoding("UTF-8") return message if message.valid_encoding? # return message if message type is binary detect = CharlockHolmes::EncodingDetector.detect(message) return message.force_encoding("BINARY") if detect && detect[:type] == :binary # encoding message to detect encoding if detect && detect[:encoding] message.force_encoding(detect[:encoding]) end # encode and clean the bad chars message.replace clean(message) rescue encoding = detect ? detect[:encoding] : "unknown" "--broken encoding: #{encoding}" end private def clean(message) message.encode("UTF-16BE", :undef => :replace, :invalid => :replace, :replace => "") .encode("UTF-8") .gsub("\0".encode("UTF-8"), "") end end
27.904762
88
0.692833
f70c1e56fc056204242ebcd0ea5b60817300dd5f
829
require 'support/parser_helpers' describe "The not keyword" do it "returns a call sexp" do parsed("not self").should == [:call, [:self], '!'.to_sym, [:arglist]] parsed("not 42").should == [:call, [:int, 42], '!'.to_sym, [:arglist]] end end describe "The '!' expression" do it "returns a call sexp" do parsed("!self").should == [:call, [:self], '!'.to_sym, [:arglist]] parsed("!42").should == [:call, [:int, 42], '!'.to_sym, [:arglist]] end end describe "The '!=' expression" do it "rewrites as !(lhs == rhs)" do parsed("1 != 2").should == [:call, [:call, [:int, 1], :==, [:arglist, [:int, 2]]], '!'.to_sym, [:arglist]] end end describe "The '!~' expression" do it "rewrites as !(lhs =~ rhs)" do parsed("1 !~ 2").should == [:not, [:call, [:int, 1], :=~, [:arglist, [:int, 2]]]] end end
29.607143
110
0.557298
03410532870e3ab8acd25f3d82eb4d3eebd744b4
650
class Quicktree < Formula desc "Phylogenetic neighbor-joining tree builder" homepage "https://www.sanger.ac.uk/resources/software/quicktree/" # tag origin homebrew-science # tag derived url "https://github.com/khowe/quicktree/archive/v2.2.tar.gz" sha256 "e44d9147a81888d6bfed5e538367ecd4e5d373ae882d5eb9649e5e33f54f1bd6" head "https://github.com/khowe/quicktree.git" def install system "make" bin.install "quicktree" doc.install "LICENSE", "README.md" end test do assert_match "UPGMA", shell_output("#{bin}/quicktree -h 2>&1") assert_match version.to_s, shell_output("#{bin}/quicktree -v 2>&1") end end
27.083333
75
0.727692
aba65a9ca4bd327c4c4e4e0bdcabec0a23b942d7
77
class Track < ActiveRecord::Base belongs_to :project has_many :stems end
15.4
32
0.766234
7abd5aa55f296311012e412177c26921b72be1d9
1,249
# frozen_string_literal: true # This file was auto-generated by lib/tasks/web.rake desc 'Pins methods.' command 'pins' do |g| g.desc 'Pins an item to a channel.' g.long_desc %( Pins an item to a channel. ) g.command 'add' do |c| c.flag 'channel', desc: 'Channel to pin the item in.' c.flag 'timestamp', desc: 'Timestamp of the message to pin.' c.action do |_global_options, options, _args| puts JSON.dump($client.pins_add(options)) end end g.desc 'Lists items pinned to a channel.' g.long_desc %( Lists items pinned to a channel. ) g.command 'list' do |c| c.flag 'channel', desc: 'Channel to get pinned items for.' c.action do |_global_options, options, _args| puts JSON.dump($client.pins_list(options)) end end g.desc 'Un-pins an item from a channel.' g.long_desc %( Un-pins an item from a channel. ) g.command 'remove' do |c| c.flag 'channel', desc: 'Channel where the item is pinned to.' c.flag 'file', desc: 'File to un-pin.' c.flag 'file_comment', desc: 'File comment to un-pin.' c.flag 'timestamp', desc: 'Timestamp of the message to un-pin.' c.action do |_global_options, options, _args| puts JSON.dump($client.pins_remove(options)) end end end
33.756757
67
0.668535
621fc229735a244933f28177524c085abd0d1542
672
require 'beaker-rspec/spec_helper' require 'beaker-rspec/helpers/serverspec' require 'beaker/puppet_install_helper' run_puppet_install_helper unless ENV['BEAKER_provision'] == 'no' RSpec.configure do |c| # Project root proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) # Readable test descriptions c.formatter = :documentation # Configure all nodes in nodeset c.before :suite do # Install module and dependencies puppet_module_install(:source => proj_root, :module_name => 'pg_monz') hosts.each do |host| on host, puppet('module', 'install', 'puppetlabs-stdlib'), { :acceptable_exit_codes => [0,1] } end end end
29.217391
100
0.723214
18e3bbb058064c00d8de51cb0038b7374769a04d
9,153
# # Copyright:: Copyright (c) 2015 Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "spec_helper" require "chef-dk/policyfile/lister" describe ChefDK::Policyfile::Lister do def api_url(org_specific_path) "https://chef.example/organizations/myorg/#{org_specific_path}" end let(:config) do double("Chef::Config", chef_server_url: "https://localhost:10443", client_key: "/path/to/client/key.pem", node_name: "deuce") end let(:http_client) { instance_double(Chef::ServerAPI) } subject(:info_fetcher) do described_class.new(config: config) end it "configures an HTTP client" do expect(Chef::ServerAPI).to receive(:new).with("https://localhost:10443", signing_key_filename: "/path/to/client/key.pem", client_name: "deuce") info_fetcher.http_client end context "when the data is fetched successfully from the server" do before do allow(info_fetcher).to receive(:http_client).and_return(http_client) allow(http_client).to receive(:get).with("policy_groups").and_return(policy_group_list_data) allow(http_client).to receive(:get).with("policies").and_return(policy_list_data) end context "when the server has no policies or groups" do let(:policy_group_list_data) { {} } let(:policy_list_data) { {} } it "gives a Hash of policy revisions by policy name" do expect(info_fetcher.policies_by_name).to eq({}) end it "gives a Hash of policy revisions by policy group" do expect(info_fetcher.policies_by_group).to eq({}) end it "is empty" do expect(info_fetcher).to be_empty end it "has no active revisions" do expect(info_fetcher.active_revisions).to be_empty end end context "when the server has policies and groups" do ## # Example API response data copied from oc-chef-pedant: let(:policy_list_data) do { "appserver" => { "uri" => api_url("policies/appserver"), "revisions" => { "1111111111111111111111111111111111111111" => {}, "2222222222222222222222222222222222222222" => {}, "3333333333333333333333333333333333333333" => {}, "4444444444444444444444444444444444444444" => {}, }, }, "db" => { "uri" => api_url("policies/db"), "revisions" => { "6666666666666666666666666666666666666666" => {}, "7777777777777777777777777777777777777777" => {}, "8888888888888888888888888888888888888888" => {}, "9999999999999999999999999999999999999999" => {}, }, }, "cache" => { "uri" => api_url("policies/cache"), "revisions" => { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" => {}, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" => {}, }, }, } end let(:dev_group_data) do { "uri" => api_url("policy_groups/dev"), "policies" => { "db" => { "revision_id" => "6666666666666666666666666666666666666666" }, "appserver" => { "revision_id" => "1111111111111111111111111111111111111111" }, "cache" => { "revision_id" => "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }, }, } end let(:test_group_data) do { "uri" => api_url("policy_groups/test"), "policies" => { "db" => { "revision_id" => "7777777777777777777777777777777777777777" }, "appserver" => { "revision_id" => "2222222222222222222222222222222222222222" }, "cache" => { "revision_id" => "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" }, }, } end let(:prod_group_data) do { "uri" => api_url("policy_groups/prod"), "policies" => { "db" => { "revision_id" => "8888888888888888888888888888888888888888" }, "appserver" => { "revision_id" => "3333333333333333333333333333333333333333" }, }, } end let(:policy_group_list_data) do { "dev" => dev_group_data, "test" => test_group_data, "prod" => prod_group_data, } end let(:expected_policy_list) do { "appserver" => { "1111111111111111111111111111111111111111" => {}, "2222222222222222222222222222222222222222" => {}, "3333333333333333333333333333333333333333" => {}, "4444444444444444444444444444444444444444" => {}, }, "db" => { "6666666666666666666666666666666666666666" => {}, "7777777777777777777777777777777777777777" => {}, "8888888888888888888888888888888888888888" => {}, "9999999999999999999999999999999999999999" => {}, }, "cache" => { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" => {}, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" => {}, }, } end let(:expected_policy_group_list) do { "dev" => { "db" => "6666666666666666666666666666666666666666", "appserver" => "1111111111111111111111111111111111111111", "cache" => "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", }, "test" => { "db" => "7777777777777777777777777777777777777777", "appserver" => "2222222222222222222222222222222222222222", "cache" => "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", }, "prod" => { "db" => "8888888888888888888888888888888888888888", "appserver" => "3333333333333333333333333333333333333333", }, } end it "gives a Hash of policy revisions by policy name" do expect(info_fetcher.policies_by_name).to eq(expected_policy_list) end it "gives a Hash of policy revisions by policy group" do expect(info_fetcher.policies_by_group).to eq(expected_policy_group_list) end it "is not empty" do expect(info_fetcher).to_not be_empty end it "lists active revisions" do expected_active_revisions = expected_policy_group_list.values.map(&:values).flatten expected_active_revisions_set = Set.new(expected_active_revisions) expect(info_fetcher.active_revisions).to eq(expected_active_revisions_set) end it "lists orphaned revisions for a given policy" do expect(info_fetcher.orphaned_revisions("db")).to eq(%w{ 9999999999999999999999999999999999999999 }) expect(info_fetcher.orphaned_revisions("appserver")).to eq(%w{ 4444444444444444444444444444444444444444 }) expect(info_fetcher.orphaned_revisions("cache")).to eq([]) end it "yields revision ids by group" do map = {} info_fetcher.revision_ids_by_group_for_each_policy do |policy_name, rev_id_by_group| map[policy_name] = rev_id_by_group end appserver_rev_ids = { "dev" => "1111111111111111111111111111111111111111", "test" => "2222222222222222222222222222222222222222", "prod" => "3333333333333333333333333333333333333333", } expect(map["appserver"].revision_ids_by_group).to eq(appserver_rev_ids) db_rev_ids = { "dev" => "6666666666666666666666666666666666666666", "test" => "7777777777777777777777777777777777777777", "prod" => "8888888888888888888888888888888888888888", } expect(map["db"].revision_ids_by_group).to eq(db_rev_ids) cache_rev_ids = { "dev" => "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "test" => "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "prod" => nil, } expect(map["cache"].revision_ids_by_group).to eq(cache_rev_ids) end context "when the server has an empty group" do let(:dev_group_data) do { "uri" => api_url("policy_groups/dev"), } end # Regression test: this exercises the case where the policy group data # from the server has no "policies" key, which previously caused a NoMethodError. it "correctly lists groups without policies" do expect(info_fetcher.policies_by_group["dev"]).to eq({}) end end end end end
34.026022
114
0.609636
91697e5218a93811c94fcde8a30c98da8206a28e
7,502
# typed: false # frozen_string_literal: true if ENV["HOMEBREW_TESTS_COVERAGE"] require "simplecov" formatters = [SimpleCov::Formatter::HTMLFormatter] if ENV["HOMEBREW_CODECOV_TOKEN"] && RUBY_PLATFORM[/darwin/] require "codecov" formatters << SimpleCov::Formatter::Codecov if ENV["TEST_ENV_NUMBER"] SimpleCov.at_exit do result = SimpleCov.result result.format! if ParallelTests.number_of_running_processes <= 1 end end ENV["CODECOV_TOKEN"] = ENV["HOMEBREW_CODECOV_TOKEN"] end SimpleCov.formatters = SimpleCov::Formatter::MultiFormatter.new(formatters) end require "rspec/its" require "rspec/wait" require "rspec/retry" require "rubocop" require "rubocop/rspec/support" require "find" require "byebug" require "timeout" $LOAD_PATH.push(File.expand_path("#{ENV["HOMEBREW_LIBRARY"]}/Homebrew/test/support/lib")) require_relative "../global" require "test/support/no_seed_progress_formatter" require "test/support/github_formatter" require "test/support/helper/cask" require "test/support/helper/fixtures" require "test/support/helper/formula" require "test/support/helper/mktmpdir" require "test/support/helper/output_as_tty" require "test/support/helper/spec/shared_context/homebrew_cask" if OS.mac? require "test/support/helper/spec/shared_context/integration_test" require "test/support/helper/spec/shared_examples/formulae_exist" TEST_DIRECTORIES = [ CoreTap.instance.path/"Formula", HOMEBREW_CACHE, HOMEBREW_CACHE_FORMULA, HOMEBREW_CELLAR, HOMEBREW_LOCKS, HOMEBREW_LOGS, HOMEBREW_TEMP, ].freeze RSpec.configure do |config| config.order = :random config.raise_errors_for_deprecations! config.filter_run_when_matching :focus config.silence_filter_announcements = true if ENV["TEST_ENV_NUMBER"] config.expect_with :rspec do |c| c.max_formatted_output_length = 200 end # Use rspec-retry in CI. if ENV["CI"] config.verbose_retry = true config.display_try_failure_messages = true config.default_retry_count = 2 config.around(:each, :needs_network) do |example| example.run_with_retry retry: 3, retry_wait: 3 end end # Never truncate output objects. RSpec::Support::ObjectFormatter.default_instance.max_formatted_output_length = nil config.include(FileUtils) config.include(RuboCop::RSpec::ExpectOffense) config.include(Test::Helper::Cask) config.include(Test::Helper::Fixtures) config.include(Test::Helper::Formula) config.include(Test::Helper::MkTmpDir) config.include(Test::Helper::OutputAsTTY) config.before(:each, :needs_compat) do skip "Requires the compatibility layer." if ENV["HOMEBREW_NO_COMPAT"] end config.before(:each, :needs_linux) do skip "Not running on Linux." unless OS.linux? end config.before(:each, :needs_macos) do skip "Not running on macOS." unless OS.mac? end config.before(:each, :needs_java) do java_installed = if OS.mac? Utils.popen_read("/usr/libexec/java_home", "--failfast", "--version", "1.0+") $CHILD_STATUS.success? else which("java") end skip "Java is not installed." unless java_installed end config.before(:each, :needs_python) do skip "Python is not installed." unless which("python") end config.before(:each, :needs_network) do skip "Requires network connection." unless ENV["HOMEBREW_TEST_ONLINE"] end config.before(:each, :needs_svn) do svn_shim = HOMEBREW_SHIMS_PATH/"scm/svn" skip "Subversion is not installed." unless quiet_system svn_shim, "--version" svn_shim_path = Pathname(Utils.popen_read(svn_shim, "--homebrew=print-path").chomp.presence) svn_paths = PATH.new(ENV["PATH"]) svn_paths.prepend(svn_shim_path.dirname) if OS.mac? xcrun_svn = Utils.popen_read("xcrun", "-f", "svn") svn_paths.append(File.dirname(xcrun_svn)) if $CHILD_STATUS.success? && xcrun_svn.present? end svn = which("svn", svn_paths) skip "svn is not installed." unless svn svnadmin = which("svnadmin", svn_paths) skip "svnadmin is not installed." unless svnadmin ENV["PATH"] = PATH.new(ENV["PATH"]) .append(svn.dirname) .append(svnadmin.dirname) end config.before(:each, :needs_unzip) do skip "Unzip is not installed." unless which("unzip") end config.around do |example| def find_files Find.find(TEST_TMPDIR) .reject { |f| File.basename(f) == ".DS_Store" } .map { |f| f.sub(TEST_TMPDIR, "") } end begin Homebrew.raise_deprecation_exceptions = true Formulary.clear_cache Tap.clear_cache DependencyCollector.clear_cache Formula.clear_cache Keg.clear_cache Tab.clear_cache FormulaInstaller.clear_attempted FormulaInstaller.clear_installed TEST_DIRECTORIES.each(&:mkpath) @__homebrew_failed = Homebrew.failed? @__files_before_test = find_files @__env = ENV.to_hash # dup doesn't work on ENV @__stdout = $stdout.clone @__stderr = $stderr.clone if (example.metadata.keys & [:focus, :byebug]).empty? && !ENV.key?("VERBOSE_TESTS") $stdout.reopen(File::NULL) $stderr.reopen(File::NULL) end begin timeout = example.metadata.fetch(:timeout, 60) Timeout.timeout(timeout) do example.run end rescue Timeout::Error => e example.example.set_exception(e) end rescue SystemExit => e example.example.set_exception(e) ensure ENV.replace(@__env) $stdout.reopen(@__stdout) $stderr.reopen(@__stderr) @__stdout.close @__stderr.close Formulary.clear_cache Tap.clear_cache DependencyCollector.clear_cache Formula.clear_cache Keg.clear_cache Tab.clear_cache FileUtils.rm_rf [ TEST_DIRECTORIES.map(&:children), *Keg::MUST_EXIST_SUBDIRECTORIES, HOMEBREW_LINKED_KEGS, HOMEBREW_PINNED_KEGS, HOMEBREW_PREFIX/"var", HOMEBREW_PREFIX/"Caskroom", HOMEBREW_PREFIX/"Frameworks", HOMEBREW_LIBRARY/"Taps/homebrew/homebrew-cask", HOMEBREW_LIBRARY/"Taps/homebrew/homebrew-bar", HOMEBREW_LIBRARY/"Taps/homebrew/homebrew-bundle", HOMEBREW_LIBRARY/"Taps/homebrew/homebrew-foo", HOMEBREW_LIBRARY/"Taps/homebrew/homebrew-services", HOMEBREW_LIBRARY/"Taps/homebrew/homebrew-shallow", HOMEBREW_LIBRARY/"PinnedTaps", HOMEBREW_REPOSITORY/".git", CoreTap.instance.path/".git", CoreTap.instance.alias_dir, CoreTap.instance.path/"formula_renames.json", *Pathname.glob("#{HOMEBREW_CELLAR}/*/"), ] files_after_test = find_files diff = Set.new(@__files_before_test) ^ Set.new(files_after_test) expect(diff).to be_empty, <<~EOS file leak detected: #{diff.map { |f| " #{f}" }.join("\n")} EOS Homebrew.failed = @__homebrew_failed end end end RSpec::Matchers.define_negated_matcher :not_to_output, :output RSpec::Matchers.alias_matcher :have_failed, :be_failed RSpec::Matchers.alias_matcher :a_string_containing, :include RSpec::Matchers.define :a_json_string do match do |actual| JSON.parse(actual) true rescue JSON::ParserError false end end # Match consecutive elements in an array. RSpec::Matchers.define :array_including_cons do |*cons| match do |actual| expect(actual.each_cons(cons.size)).to include(cons) end end
27.785185
96
0.696081
1d5644960fadc9c6364926ad505d4339f00d62dd
7,879
# -*- coding: utf-8 -*- class AwardYears::V2018::QAEForms class << self def trade_step2 @trade_step2 ||= proc do header :your_internation_trade_header, "" do context %( <p> This section gives you the opportunity to present the detail of your products or services that you export and to give us the evidence of their commercial impact on your business that will enable us to assess your application. </p> <p> Please try to avoid using technical jargon in this section. </p> ) end textarea :trade_business_as_a_whole, "Describe your business as a whole" do sub_ref "B 1" required rows 5 words_max 500 end textarea :trade_overall_growth_strategy, "Explain your overall growth strategy" do sub_ref "B 1.1" required rows 5 words_max 500 end textarea :trade_brief_history, "Provide a brief history of your company, corporate targets and direction" do sub_ref "B 1.2" required rows 5 words_max 500 end textarea :trade_overall_importance, "Explain the overall importance of exporting to your company" do sub_ref "B 1.3" required rows 5 words_max 500 end textarea :trade_goods_briefly, "Please briefly describe all products or services that you sell internationally" do sub_ref "B 1.4" required context %( <p> This summary will be used in publicity material if your application is successful. </p> <p> e.g. Design and manufacture of contract fabrics for commercial interiors. Design and manufacture of mass passenger transport fabrics. </p> <p> e.g. Musical heritage tours and events, exploring popular music history by theme, genre or specific artist. </p> ) rows 2 words_max 15 end checkbox_seria :application_relate_to_header, "This entry relates to:" do ref "B 2" required context %( <p>Select all that apply.</p> ) check_options [ ["products", "Products"], ["services", "Services"] ] application_type_question true end dropdown :trade_goods_amount, "How many types of products/services make up your international trade?" do ref "B 2.1" required context %( <p> If you have more than 5, please try to group them into fewer types of products/services. </p> ) option "", "Select" option "1", "1" option "2", "2" option "3", "3" option "4", "4" option "5", "5" default_option "1" end by_trade_goods_and_services_label :trade_goods_and_services_explanations, "Please list and briefly describe each product or services you export" do classes "sub-question word-max-strict" sub_ref "B 2.2" required context %( <p> If relevant, give details of material used or end use. e.g. 'design and manufacture of bespoke steel windows and doors'. Your percentage answers below should add up to 100. </p> ) additional_pdf_context %( You will need to complete this information for each product or service depending on your answer for question B2.1 ) rows 2 words_max 15 min 0 max 100 conditional :trade_goods_amount, :true end textarea :trade_plans_desc, "Describe your international and domestic trading strategies (plans), their vision/objectives for the future, their method of implementation, and how your actual performance compared to the plans set out" do ref "B 3" required context %( <p> Include for example: your overseas market structure, comparisons between domestic and international strategies, treatment of different markets (linking to top performing markets), market research, market development, routes to market, after sales and technical advice, activities to sustain/grow markets, staff language training, export practices, overseas distributors, inward/outward trade missions, trade fairs and visits to existing/potential markets. Make sure you explain how your actual performance compares to your planned performance. </p> ) rows 5 words_max 800 end header :overseas_markets_header, "Overseas Markets" do ref "B 4" context %( <p> If applicable, demonstrate why penetration of a particular market represents a significant achievement: for example are you the first, leading, fastest growing UK exporter to an overseas market? How does your performance compare with other companies operating in your sector or overseas market? </p> ) end textarea :markets_geo_spread, "Describe the geographical spread of your overseas markets" do required sub_ref "B 4.1" classes "sub-question" context %( <p> Include evidence of how you segment and manage geographical regions to demonstrate your company’s focus. Please supply market share information. </p> ) rows 5 words_max 500 end textarea :top_overseas_sales, "What percentage of total overseas sales was made to each of your top 5 overseas markets (ie. individual countries) during the final year of your entry?" do classes "sub-question" sub_ref "B 4.2" required rows 5 words_max 100 end textarea :identify_new_overseas, "Identify new overseas markets established during your period of entry, and their contribution to total overseas sales" do classes "sub-question" sub_ref "B 4.3" required rows 5 words_max 250 end textarea :trade_factors, "Describe any special challenges affecting your trade in products or services, and how you overcame them" do ref "B 5" required rows 5 words_max 200 end checkbox_seria :operate_overseas, "How do you run your overseas operations?" do ref "B 6" required context %( <p>Select all that apply.</p> ) check_options [ ["franchise", "As a franchise"], ["other", "Other business model(s)"] ] end textarea :operate_model_benefits, "Please explain your franchise and/or other business model(s) and rationale for this. Describe the benefits this brings to the UK" do classes "sub-question" sub_ref "B 6.1" required rows 5 words_max 300 end options :received_grant, "Did you receive any grant funding to support this product/service?" do ref "B 7" required yes_no context %( <p> We ask this in order to help us carry out due diligence if your application is shortlisted. </p> ) end textarea :funding_details, "Please give details of date(s), source(s) and level(s) of funding" do classes "sub-question" sub_ref "B 7.1" required rows 5 words_max 200 conditional :received_grant, "yes" end end end end end
37.165094
557
0.594492
7a758c5e34f0d2870c53feeaf0c62b207a03aed2
559
module StatlyHelper def stat(controller, action, message) stat_counter = Stat.where("date(created_at) = date(:today) and controller = :controller and action = :action and message = :message", {today: Date.today, controller: controller, action: action, message: message}).first if stat_counter.nil? stat_counter = Stat.new stat_counter.controller = controller stat_counter.action = action stat_counter.message = message stat_counter.count = 1 stat_counter.save! else stat_counter.count += 1 stat_counter.save! end end end
27.95
220
0.735242
f75d90c4d6647618d8b4a578bfc25497a877f8f3
969
require 'spec_helper' describe 'omnibus::_yaml' do let(:chef_run) { ChefSpec::Runner.new.converge(described_recipe) } context 'on debian' do let(:chef_run) do ChefSpec::Runner.new(platform: 'debian', version: '7.4') .converge(described_recipe) end it 'installs the correct development packages' do expect(chef_run).to install_package('libyaml-dev') end end context 'on freebsd' do let(:chef_run) do ChefSpec::Runner.new(platform: 'freebsd', version: '9.1') .converge(described_recipe) end it 'installs the correct development packages' do expect(chef_run).to install_package('libyaml') end end context 'on mac_os_x' do let(:chef_run) do ChefSpec::Runner.new(platform: 'mac_os_x', version: '10.8.2') .converge(described_recipe) end it 'installs the correct development packages' do expect(chef_run).to install_package('libyaml') end end end
24.846154
68
0.672859
7a2efb3dec7ee2a27da05d48262823208b23a9c7
119
class AddUserIdToPlays < ActiveRecord::Migration[6.0] def change add_column :plays, :user_id, :integer end end
19.833333
53
0.739496
79917b2193b37727f9cb6e4cc763b8f0bbd6cfb6
1,806
require 'spec_helper' describe SimpleNavigation::ItemsProvider do before(:each) do @provider = stub(:provider) @items_provider = SimpleNavigation::ItemsProvider.new(@provider) end describe 'initialize' do it "should set the provider" do @items_provider.provider.should == @provider end end describe 'items' do before(:each) do @items = stub(:items) end context 'provider is symbol' do before(:each) do @items_provider.instance_variable_set(:@provider, :provider_method) @context = stub(:context, :provider_method => @items) SimpleNavigation.stub!(:context_for_eval => @context) end it "should call the method specified by symbol on the context" do @context.should_receive(:provider_method) @items_provider.items end it "should return the items returned by the helper method" do @items_provider.items.should == @items end end context 'provider responds to items' do before(:each) do @provider.stub!(:items => @items) end it "should get the items from the items_provider" do @provider.should_receive(:items) @items_provider.items end it "should return the items of the provider" do @items_provider.items.should == @items end end context 'provider is a collection' do before(:each) do @items_collection = [] @items_provider.instance_variable_set(:@provider, @items_collection) end it "should return the collection itsself" do @items_provider.items.should == @items_collection end end context 'neither symbol nor items_provider.items nor collection' do it {lambda {@items_provider.items}.should raise_error} end end end
30.1
76
0.662237
bff027b26e720fdbfde6512a6ed5efb9bafe51dc
205
require 'eventmachine' module AsakusaSatellite class AsyncRunner def self.run(&block) if EM.reactor_running? EM.defer(block) else block.call end end end end
13.666667
28
0.62439
1cb3b40656bfea9deaa89240f6f9a0071b28c3e7
3,232
require 'eventbrite/api_objects/organizer' require 'eventbrite/api_objects/venue' require 'eventbrite/api_objects/ticket' require 'eventbrite/api_objects/organizer' require 'eventbrite/api_objects/discount' require 'eventbrite/api_objects/attendee' module Eventbrite # The Event class is the main point of interaction for most Eventbrite api # calls. Most objects have to be directly related to an Event. # # Events must have a Venue and an Organizer. # # Events have collections of Attendees, Tickets, and Discounts class Event < Eventbrite::ApiObject updatable :title, :description, :tags, :timezone updatable_date :start_date, :end_date updatable :capacity, :url updatable :privacy, :password, :status updatable :created, :modified, :logo, :logo_ssl updatable :text_color, :link_color, :title_text_color, :background_color updatable :box_background_color, :box_text_color, :box_border_color updatable :box_header_background_color, :box_header_text_color updatable :currency updatable :venue_id, :organizer_id readable :category, :num_attendee_rows reformats :privacy, :timezone, :start_date, :end_date requires :title ignores :organizer, :venue, :tickets renames :id => :event_id attr_accessor :organizer, :venue has :organizer => Eventbrite::Organizer has :venue => Eventbrite::Venue collection :tickets => Eventbrite::TicketCollection collection :attendees => Eventbrite::AttendeeCollection collection :discounts => Eventbrite::DiscountCollection # Returns privacy status of event def privacy case attribute_get(:privacy) when "Private" attribute_set(:privacy, 0) when "Public" attribute_set(:privacy, 1) end attribute_get(:privacy) end # Returns currency, setting to default of USD. def currency attribute_get(:currency) || attribute_set(:currency, "USD") end # Returns timezone, reformatting to GMT offset if necessary. def timezone return attribute_get(:timezone) if attribute_get(:timezone) =~ /GMT[+-]\d{1,2}/ time = TZInfo::Timezone.get(attribute_get(:timezone)).current_period seconds = time.utc_offset offset = (seconds / (60*60)) attribute_set(:timezone, (offset < 0 ? "GMT#{offset}" : "GMT+#{offset}")) attribute_get(:timezone) end # Returns true if event is private def private? privacy == 0 ? true : false end # Returns true if event is not private def public? !private? end # @private # Handle differences in api - occasionally response is double # wrapped in the XML. def unnest_child_response(response) response.has_key?('event') ? response['event'] : response end # @private # Mark the user's event collection as dirty def after_new @owner.dirty_events! end # @private # When requesting collections, request as many as possible. def nested_hash {:id => id, :count => 99999, :user => owner} # It's over 9000! end end # A collection of events. class EventCollection < ApiObjectCollection; collection_for Event; end end
32
85
0.688119
1af4266ab43d83a184c424d6f9fc145ddee5f553
82
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'belugas/java'
27.333333
58
0.731707
f8086af284ac3790c4f66fc21cfbf39ee5a1b046
96
class ApplicationMailer < ActionMailer::Base default from: @admin_email layout 'mailer' end
19.2
44
0.78125
87d6bb4ced2b0ca81955729c8dc7e59c796ee219
145
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_photo_gallery_session'
36.25
83
0.813793
2806fe2ef9e6cb0f5f3c364fe6f764b1038ff244
1,095
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/google_ads/v1/enums/income_range_type.proto require 'google/protobuf' require 'google/api/annotations_pb' Google::Protobuf::DescriptorPool.generated_pool.build do add_message "google.ads.googleads.v1.enums.IncomeRangeTypeEnum" do end add_enum "google.ads.googleads.v1.enums.IncomeRangeTypeEnum.IncomeRangeType" do value :UNSPECIFIED, 0 value :UNKNOWN, 1 value :INCOME_RANGE_0_50, 510001 value :INCOME_RANGE_50_60, 510002 value :INCOME_RANGE_60_70, 510003 value :INCOME_RANGE_70_80, 510004 value :INCOME_RANGE_80_90, 510005 value :INCOME_RANGE_90_UP, 510006 value :INCOME_RANGE_UNDETERMINED, 510000 end end module Google::Ads::GoogleAds::V1::Enums IncomeRangeTypeEnum = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v1.enums.IncomeRangeTypeEnum").msgclass IncomeRangeTypeEnum::IncomeRangeType = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v1.enums.IncomeRangeTypeEnum.IncomeRangeType").enummodule end
40.555556
175
0.800913
e9fae810410eb43e815e4feb6d329d4b84ebb998
3,054
# frozen_string_literal: true require 'singleton' require 'spree/core/class_constantizer' module Spree # A class responsible for associating {Spree::Role} with a list of permission sets. # # @see Spree::PermissionSets # # @example Adding order, product, and user display to customer service users. # Spree::RoleConfiguration.configure do |config| # config.assign_permissions :customer_service, [ # Spree::PermissionSets::OrderDisplay, # Spree::PermissionSets::UserDisplay, # Spree::PermissionSets::ProductDisplay # ] # end class RoleConfiguration # An internal structure for the association between a role and a # set of permissions. class Role attr_reader :name, :permission_sets def initialize(name, permission_sets) @name = name @permission_sets = Spree::Core::ClassConstantizer::Set.new @permission_sets.concat permission_sets end end attr_accessor :roles class << self def instance Spree::Deprecation.warn "Spree::RoleConfiguration.instance is DEPRECATED use Spree::Config.roles instead" Spree::Config.roles end # Yields the instance of the singleton, used for configuration # @yieldparam instance [Spree::RoleConfiguration] def configure Spree::Deprecation.warn "Spree::RoleConfiguration.configure is deprecated. Call Spree::Config.roles.assign_permissions instead" yield(Spree::Config.roles) end end # Given a CanCan::Ability, and a user, determine what permissions sets can # be activated on the ability, then activate them. # # This performs can/cannot declarations on the ability, and can modify its # internal permissions. # # @param ability [CanCan::Ability] the ability to invoke declarations on # @param user [#spree_roles] the user that holds the spree_roles association. def activate_permissions!(ability, user) spree_roles = ['default'] | user.spree_roles.map(&:name) applicable_permissions = Set.new spree_roles.each do |role_name| applicable_permissions |= roles[role_name].permission_sets end applicable_permissions.each do |permission_set| permission_set.new(ability).activate! end end # Not public due to the fact this class is a Singleton # @!visibility private def initialize @roles = Hash.new do |hash, name| hash[name] = Role.new(name, Set.new) end end # Assign permission sets for a {Spree::Role} that has the name of role_name # @param role_name [Symbol, String] The name of the role to associate permissions with # @param permission_sets [Array<Spree::PermissionSets::Base>, Set<Spree::PermissionSets::Base>] # A list of permission sets to activate if the user has the role indicated by role_name def assign_permissions(role_name, permission_sets) name = role_name.to_s roles[name].permission_sets.concat permission_sets roles[name] end end end
34.314607
135
0.696464
2849ddc1d4f219ea91378123039a0fbf00f8271f
4,319
# 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_08_01 module Models # # Backend Address Pool of an application gateway. # class ApplicationGatewayBackendAddressPool < SubResource include MsRestAzure # @return [Array<NetworkInterfaceIPConfiguration>] Collection of # references to IPs defined in network interfaces. attr_accessor :backend_ipconfigurations # @return [Array<ApplicationGatewayBackendAddress>] Backend addresses. attr_accessor :backend_addresses # @return [ProvisioningState] The provisioning state of the backend # address pool resource. Possible values include: 'Succeeded', # 'Updating', 'Deleting', 'Failed' attr_accessor :provisioning_state # @return [String] Name of the backend address pool that is unique within # an Application Gateway. attr_accessor :name # @return [String] A unique read-only string that changes whenever the # resource is updated. attr_accessor :etag # @return [String] Type of the resource. attr_accessor :type # # Mapper for ApplicationGatewayBackendAddressPool class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ApplicationGatewayBackendAddressPool', type: { name: 'Composite', class_name: 'ApplicationGatewayBackendAddressPool', model_properties: { id: { client_side_validation: true, required: false, serialized_name: 'id', type: { name: 'String' } }, backend_ipconfigurations: { client_side_validation: true, required: false, serialized_name: 'properties.backendIPConfigurations', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'NetworkInterfaceIPConfigurationElementType', type: { name: 'Composite', class_name: 'NetworkInterfaceIPConfiguration' } } } }, backend_addresses: { client_side_validation: true, required: false, serialized_name: 'properties.backendAddresses', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'ApplicationGatewayBackendAddressElementType', type: { name: 'Composite', class_name: 'ApplicationGatewayBackendAddress' } } } }, provisioning_state: { client_side_validation: true, required: false, serialized_name: 'properties.provisioningState', type: { name: 'String' } }, name: { client_side_validation: true, required: false, serialized_name: 'name', type: { name: 'String' } }, etag: { client_side_validation: true, required: false, serialized_name: 'etag', type: { name: 'String' } }, type: { client_side_validation: true, required: false, serialized_name: 'type', type: { name: 'String' } } } } } end end end end
32.473684
85
0.50081
4a1b4570a265bd6c8756773b33c9767a6d63dbde
83
module Tailwindcss end require "tailwindcss/version" require "tailwindcss/engine"
13.833333
29
0.831325
ed0c25618818445e5a2c7c500ff7c2f99ea828d2
636
require 'spec_helper' describe YARD::Cov::ReportOutput, '#write' do subject do described_class.new(target).write do |io| io.puts 'content' end end let(:target) { double('Pathname', dirname: dirname) } let(:dirname) { double } before do allow(dirname).to receive(:mkpath) allow(target).to receive(:open) end it 'creates directory' do expect(dirname).to receive(:mkpath) subject end it 'writes content' do io = double expect(io).to receive(:puts).with('content') expect(target).to receive(:open).with('w').and_yield(io) subject end end
21.2
60
0.624214
f8b091b05a8ce6cca9863eb1346bc2a3df48e4aa
2,811
require File.expand_path('../boot', __FILE__) require 'rails/all' if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end module BadSql 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. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # 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 # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable escaping HTML in JSON. config.active_support.escape_html_entities_in_json = true # Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Enforce whitelist mode for mass assignment. # This will create an empty whitelist of attributes available for mass-assignment for all models # in your app. As such, your models will need to explicitly whitelist or blacklist accessible # parameters by using an attr_accessible or attr_protected declaration. config.active_record.whitelist_attributes = true # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' end end
44.619048
100
0.734258
ed9c3246cd1e300c5578338f57cbb46392ecf194
1,716
# 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::KubernetesConfiguration::Mgmt::V2021_03_01 module Models # # Proxy Resource # The resource model definition for a Azure Resource Manager proxy # resource. It will not have tags and a location # class ProxyResource < Resource include MsRestAzure # # Mapper for ProxyResource class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ProxyResource', type: { name: 'Composite', class_name: 'ProxyResource', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } } } } } end end end end
26
70
0.482517
393fa4ce6c803c51eef93d3214f66e2fc7795313
211
require 'mxx_ru/binary_unittest' path = 'test/so_5/env_infrastructure/simple_not_mtsafe_st/stop_in_init_fn' MxxRu::setup_target( MxxRu::BinaryUnittestTarget.new( "#{path}/prj.ut.rb", "#{path}/prj.rb" ) )
21.1
74
0.748815
330a796ad1544e86a3b900e6a3595321f297bb5a
656
Pod::Spec.new do |s| s.name = "Artsy+UILabels" s.version = "1.0.0" s.summary = "UILabels subclasses and related categories." s.homepage = "https://github.com/artsy/Artsy-UILabels" s.license = 'MIT' s.author = { "Orta" => "[email protected]" } s.source = { :git => "https://github.com/artsy/Artsy-UILabels.git" } s.social_media_url = 'https://twitter.com/artsy' s.platform = :ios, '7.0' s.requires_arc = true s.source_files = 'Pod/Classes' s.resources = 'Pod/Assets/*.png' s.frameworks = 'UIKit' s.dependencies = 'Artsy+UIColors', 'Artsy+UIFonts' end
32.8
80
0.585366
ab682dac7c56b264811ff10453676ecebccc5674
77
require 'test_helper' class SimulationHelperTest < ActionView::TestCase end
15.4
49
0.831169
6ac8466b887bcb45570e45a28373048ac00f601b
5,189
# frozen_string_literal: true require 'json' require 'base64' require 'open3' require 'krane/kubectl' module Krane class EjsonSecretError < FatalDeploymentError def initialize(msg) super("Generation of Kubernetes secrets from ejson failed: #{msg}") end end class EjsonSecretProvisioner EJSON_SECRET_ANNOTATION = "kubernetes-deploy.shopify.io/ejson-secret" EJSON_SECRET_KEY = "kubernetes_secrets" EJSON_SECRETS_FILE = "secrets.ejson" EJSON_KEYS_SECRET = "ejson-keys" delegate :namespace, :context, :logger, to: :@task_config def initialize(task_config:, ejson_keys_secret:, ejson_file:, statsd_tags:, selector: nil) @ejson_keys_secret = ejson_keys_secret @ejson_file = ejson_file @statsd_tags = statsd_tags @selector = selector @task_config = task_config @kubectl = Kubectl.new( task_config: @task_config, log_failure_by_default: false, output_is_sensitive_default: true # output may contain ejson secrets ) end def resources @resources ||= build_secrets end private def build_secrets unless @ejson_keys_secret raise EjsonSecretError, "Secret #{EJSON_KEYS_SECRET} not provided, cannot decrypt secrets" end return [] unless File.exist?(@ejson_file) with_decrypted_ejson do |decrypted| secrets = decrypted[EJSON_SECRET_KEY] unless secrets.present? logger.warn("#{EJSON_SECRETS_FILE} does not have key #{EJSON_SECRET_KEY}."\ "No secrets will be created.") return [] end secrets.map do |secret_name, secret_spec| validate_secret_spec(secret_name, secret_spec) resource = generate_secret_resource(secret_name, secret_spec["_type"], secret_spec["data"]) resource.validate_definition(@kubectl) if resource.validation_failed? raise EjsonSecretError, "Resulting resource Secret/#{secret_name} failed validation" end resource end end end def encrypted_ejson @encrypted_ejson ||= load_ejson_from_file end def public_key encrypted_ejson["_public_key"] end def private_key @private_key ||= fetch_private_key_from_secret end def validate_secret_spec(secret_name, spec) errors = [] errors << "secret type unspecified" if spec["_type"].blank? errors << "no data provided" if spec["data"].blank? unless errors.empty? raise EjsonSecretError, "Ejson incomplete for secret #{secret_name}: #{errors.join(', ')}" end end def generate_secret_resource(secret_name, secret_type, data) unless data.is_a?(Hash) && data.values.all? { |v| v.is_a?(String) } # Secret data is map[string]string raise EjsonSecretError, "Data for secret #{secret_name} was invalid. Only key-value pairs are permitted." end encoded_data = data.each_with_object({}) do |(key, value), encoded| # Leading underscores in ejson keys are used to skip encryption of the associated value # To support this ejson feature, we need to exclude these leading underscores from the secret's keys secret_key = key.sub(/\A_/, '') encoded[secret_key] = Base64.strict_encode64(value) end labels = { "name" => secret_name } labels.reverse_merge!(@selector.to_h) if @selector secret = { 'kind' => 'Secret', 'apiVersion' => 'v1', 'type' => secret_type, 'metadata' => { "name" => secret_name, "labels" => labels, "namespace" => namespace, "annotations" => { EJSON_SECRET_ANNOTATION => "true" }, }, "data" => encoded_data, } Krane::Secret.build( namespace: namespace, context: context, logger: logger, definition: secret, statsd_tags: @statsd_tags, ) end def load_ejson_from_file return {} unless File.exist?(@ejson_file) JSON.parse(File.read(@ejson_file)) end def with_decrypted_ejson return unless File.exist?(@ejson_file) Dir.mktmpdir("ejson_keydir") do |key_dir| File.write(File.join(key_dir, public_key), private_key) decrypted = decrypt_ejson(key_dir) yield decrypted end end def decrypt_ejson(key_dir) out, err, st = Open3.capture3("EJSON_KEYDIR=#{key_dir} ejson decrypt #{@ejson_file}") unless st.success? # older ejson versions dump some errors to STDOUT msg = err.presence || out raise EjsonSecretError, msg end JSON.parse(out) rescue JSON::ParserError raise EjsonSecretError, "Failed to parse decrypted ejson" end def fetch_private_key_from_secret encoded_private_key = @ejson_keys_secret["data"][public_key] unless encoded_private_key raise EjsonSecretError, "Private key for #{public_key} not found in #{EJSON_KEYS_SECRET} secret" end Base64.decode64(encoded_private_key) rescue Kubectl::ResourceNotFoundError raise EjsonSecretError, "Secret/#{EJSON_KEYS_SECRET} is required to decrypt EJSON and could not be found" end end end
32.841772
113
0.663326
61616a5a9d41fc4e314458dee6adc7ede7b972ae
18,752
# 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::Reservations::Mgmt::V2019_07_19_preview # # Microsoft Azure Quota Resource Provider. # class QuotaRequestStatus include MsRestAzure # # Creates and initializes a new instance of the QuotaRequestStatus class. # @param client service class for accessing basic functionality. # def initialize(client) @client = client end # @return [ReservationsManagementClient] reference to the ReservationsManagementClient attr_reader :client # # Gets the QuotaRequest details and status by the quota request Id for the # resources for the resource provider at a specific location. The requestId is # returned as response to the Put requests for serviceLimits. # # @param subscription_id [String] Azure subscription id. # @param provider_id [String] Azure resource provider id. # @param location [String] Azure region. # @param id [String] Quota Request id. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [QuotaRequestDetails] operation results. # def get(subscription_id, provider_id, location, id, custom_headers:nil) response = get_async(subscription_id, provider_id, location, id, custom_headers:custom_headers).value! response.body unless response.nil? end # # Gets the QuotaRequest details and status by the quota request Id for the # resources for the resource provider at a specific location. The requestId is # returned as response to the Put requests for serviceLimits. # # @param subscription_id [String] Azure subscription id. # @param provider_id [String] Azure resource provider id. # @param location [String] Azure region. # @param id [String] Quota Request id. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def get_with_http_info(subscription_id, provider_id, location, id, custom_headers:nil) get_async(subscription_id, provider_id, location, id, custom_headers:custom_headers).value! end # # Gets the QuotaRequest details and status by the quota request Id for the # resources for the resource provider at a specific location. The requestId is # returned as response to the Put requests for serviceLimits. # # @param subscription_id [String] Azure subscription id. # @param provider_id [String] Azure resource provider id. # @param location [String] Azure region. # @param id [String] Quota Request id. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def get_async(subscription_id, provider_id, location, id, custom_headers:nil) fail ArgumentError, 'subscription_id is nil' if subscription_id.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'provider_id is nil' if provider_id.nil? fail ArgumentError, 'location is nil' if location.nil? fail ArgumentError, 'id is nil' if id.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests/{id}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => subscription_id,'providerId' => provider_id,'location' => location,'id' => id}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Reservations::Mgmt::V2019_07_19_preview::Models::QuotaRequestDetails.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # For the specified location and Resource provider gets the current quota # requests under the subscription over the time period of one year ago from now # to one year back. oData filter can be used to select quota requests. # # @param subscription_id [String] Azure subscription id. # @param provider_id [String] Azure resource provider id. # @param location [String] Azure region. # @param filter [String] | Field | Supported operators # |---------------------|------------------------ # # |requestSubmitTime | ge, le, eq, gt, lt # # @param top [Integer] Number of records to return. # @param skiptoken [String] Skiptoken is only used if a previous operation # returned a partial result. If a previous response contains a nextLink # element, the value of the nextLink element will include a skiptoken parameter # that specifies a starting point to use for subsequent calls # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Array<QuotaRequestDetails>] operation results. # def list(subscription_id, provider_id, location, filter:nil, top:nil, skiptoken:nil, custom_headers:nil) first_page = list_as_lazy(subscription_id, provider_id, location, filter:filter, top:top, skiptoken:skiptoken, custom_headers:custom_headers) first_page.get_all_items end # # For the specified location and Resource provider gets the current quota # requests under the subscription over the time period of one year ago from now # to one year back. oData filter can be used to select quota requests. # # @param subscription_id [String] Azure subscription id. # @param provider_id [String] Azure resource provider id. # @param location [String] Azure region. # @param filter [String] | Field | Supported operators # |---------------------|------------------------ # # |requestSubmitTime | ge, le, eq, gt, lt # # @param top [Integer] Number of records to return. # @param skiptoken [String] Skiptoken is only used if a previous operation # returned a partial result. If a previous response contains a nextLink # element, the value of the nextLink element will include a skiptoken parameter # that specifies a starting point to use for subsequent calls # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_with_http_info(subscription_id, provider_id, location, filter:nil, top:nil, skiptoken:nil, custom_headers:nil) list_async(subscription_id, provider_id, location, filter:filter, top:top, skiptoken:skiptoken, custom_headers:custom_headers).value! end # # For the specified location and Resource provider gets the current quota # requests under the subscription over the time period of one year ago from now # to one year back. oData filter can be used to select quota requests. # # @param subscription_id [String] Azure subscription id. # @param provider_id [String] Azure resource provider id. # @param location [String] Azure region. # @param filter [String] | Field | Supported operators # |---------------------|------------------------ # # |requestSubmitTime | ge, le, eq, gt, lt # # @param top [Integer] Number of records to return. # @param skiptoken [String] Skiptoken is only used if a previous operation # returned a partial result. If a previous response contains a nextLink # element, the value of the nextLink element will include a skiptoken parameter # that specifies a starting point to use for subsequent calls # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_async(subscription_id, provider_id, location, filter:nil, top:nil, skiptoken:nil, custom_headers:nil) fail ArgumentError, 'subscription_id is nil' if subscription_id.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'provider_id is nil' if provider_id.nil? fail ArgumentError, 'location is nil' if location.nil? fail ArgumentError, "'top' should satisfy the constraint - 'InclusiveMinimum': '1'" if !top.nil? && top < 1 request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => subscription_id,'providerId' => provider_id,'location' => location}, query_params: {'api-version' => @client.api_version,'$filter' => filter,'$top' => top,'$skiptoken' => skiptoken}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Reservations::Mgmt::V2019_07_19_preview::Models::QuotaRequestDetailsList.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # For the specified location and Resource provider gets the current quota # requests under the subscription over the time period of one year ago from now # to one year back. oData filter can be used to select quota requests. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [QuotaRequestDetailsList] operation results. # def list_next(next_page_link, custom_headers:nil) response = list_next_async(next_page_link, custom_headers:custom_headers).value! response.body unless response.nil? end # # For the specified location and Resource provider gets the current quota # requests under the subscription over the time period of one year ago from now # to one year back. oData filter can be used to select quota requests. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_next_with_http_info(next_page_link, custom_headers:nil) list_next_async(next_page_link, custom_headers:custom_headers).value! end # # For the specified location and Resource provider gets the current quota # requests under the subscription over the time period of one year ago from now # to one year back. oData filter can be used to select quota requests. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_next_async(next_page_link, custom_headers:nil) fail ArgumentError, 'next_page_link is nil' if next_page_link.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = '{nextLink}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], skip_encoding_path_params: {'nextLink' => next_page_link}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Reservations::Mgmt::V2019_07_19_preview::Models::QuotaRequestDetailsList.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # For the specified location and Resource provider gets the current quota # requests under the subscription over the time period of one year ago from now # to one year back. oData filter can be used to select quota requests. # # @param subscription_id [String] Azure subscription id. # @param provider_id [String] Azure resource provider id. # @param location [String] Azure region. # @param filter [String] | Field | Supported operators # |---------------------|------------------------ # # |requestSubmitTime | ge, le, eq, gt, lt # # @param top [Integer] Number of records to return. # @param skiptoken [String] Skiptoken is only used if a previous operation # returned a partial result. If a previous response contains a nextLink # element, the value of the nextLink element will include a skiptoken parameter # that specifies a starting point to use for subsequent calls # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [QuotaRequestDetailsList] which provide lazy access to pages of the # response. # def list_as_lazy(subscription_id, provider_id, location, filter:nil, top:nil, skiptoken:nil, custom_headers:nil) response = list_async(subscription_id, provider_id, location, filter:filter, top:top, skiptoken:skiptoken, custom_headers:custom_headers).value! unless response.nil? page = response.body page.next_method = Proc.new do |next_page_link| list_next_async(next_page_link, custom_headers:custom_headers) end page end end end end
47.115578
162
0.69134
6ac81460292e407f7a93741d1e3644a46673846e
261
require_relative 'test_helper' class TestFakerSuperhero < Test::Unit::TestCase def setup @tester = Faker::Superhero end def test_power assert @tester.power.match(/\w+\.?/) end def test_name assert @tester.name.match(/\w+\.?/) end end
16.3125
47
0.67433
6ac86b6524c9b9fff02d245fda1ad06a0ce43540
10,055
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Google module Cloud module Dialogflow module V2 # Represents a conversational agent. # @!attribute [rw] parent # @return [String] # Required. The project of this agent. # Format: +projects/<Project ID>+. # @!attribute [rw] display_name # @return [String] # Required. The name of this agent. # @!attribute [rw] default_language_code # @return [String] # Required. The default language of the agent as a language tag. See # [Language Support](https://dialogflow.com/docs/reference/language) for a # list of the currently supported language codes. # This field cannot be set by the +Update+ method. # @!attribute [rw] supported_language_codes # @return [Array<String>] # Optional. The list of all languages supported by this agent (except for the # +default_language_code+). # @!attribute [rw] time_zone # @return [String] # Required. The time zone of this agent from the # [time zone database](https://www.iana.org/time-zones), e.g., # America/New_York, Europe/Paris. # @!attribute [rw] description # @return [String] # Optional. The description of this agent. # The maximum length is 500 characters. If exceeded, the request is rejected. # @!attribute [rw] avatar_uri # @return [String] # Optional. The URI of the agent's avatar. # Avatars are used throughout the Dialogflow console and in the self-hosted # [Web Demo](https://dialogflow.com/docs/integrations/web-demo) integration. # @!attribute [rw] enable_logging # @return [true, false] # Optional. Determines whether this agent should log conversation queries. # @!attribute [rw] match_mode # @return [Google::Cloud::Dialogflow::V2::Agent::MatchMode] # Optional. Determines how intents are detected from user queries. # @!attribute [rw] classification_threshold # @return [Float] # Optional. To filter out false positive results and still get variety in # matched natural language inputs for your agent, you can tune the machine # learning classification threshold. If the returned score value is less than # the threshold value, then a fallback intent is be triggered or, if there # are no fallback intents defined, no intent will be triggered. The score # values range from 0.0 (completely uncertain) to 1.0 (completely certain). # If set to 0.0, the default of 0.3 is used. class Agent # Match mode determines how intents are detected from user queries. module MatchMode # Not specified. MATCH_MODE_UNSPECIFIED = 0 # Best for agents with a small number of examples in intents and/or wide # use of templates syntax and composite entities. MATCH_MODE_HYBRID = 1 # Can be used for agents with a large number of examples in intents, # especially the ones using @sys.any or very large developer entities. MATCH_MODE_ML_ONLY = 2 end end # The request message for {Google::Cloud::Dialogflow::V2::Agents::GetAgent Agents::GetAgent}. # @!attribute [rw] parent # @return [String] # Required. The project that the agent to fetch is associated with. # Format: +projects/<Project ID>+. class GetAgentRequest; end # The request message for {Google::Cloud::Dialogflow::V2::Agents::SearchAgents Agents::SearchAgents}. # @!attribute [rw] parent # @return [String] # Required. The project to list agents from. # Format: +projects/<Project ID or '-'>+. # @!attribute [rw] page_size # @return [Integer] # Optional. The maximum number of items to return in a single page. By # default 100 and at most 1000. # @!attribute [rw] page_token # @return [String] # Optional. The next_page_token value returned from a previous list request. class SearchAgentsRequest; end # The response message for {Google::Cloud::Dialogflow::V2::Agents::SearchAgents Agents::SearchAgents}. # @!attribute [rw] agents # @return [Array<Google::Cloud::Dialogflow::V2::Agent>] # The list of agents. There will be a maximum number of items returned based # on the page_size field in the request. # @!attribute [rw] next_page_token # @return [String] # Token to retrieve the next page of results, or empty if there are no # more results in the list. class SearchAgentsResponse; end # The request message for {Google::Cloud::Dialogflow::V2::Agents::TrainAgent Agents::TrainAgent}. # @!attribute [rw] parent # @return [String] # Required. The project that the agent to train is associated with. # Format: +projects/<Project ID>+. class TrainAgentRequest; end # The request message for {Google::Cloud::Dialogflow::V2::Agents::ExportAgent Agents::ExportAgent}. # @!attribute [rw] parent # @return [String] # Required. The project that the agent to export is associated with. # Format: +projects/<Project ID>+. # @!attribute [rw] agent_uri # @return [String] # Optional. The Google Cloud Storage URI to export the agent to. # Note: The URI must start with # "gs://". If left unspecified, the serialized agent is returned inline. class ExportAgentRequest; end # The response message for {Google::Cloud::Dialogflow::V2::Agents::ExportAgent Agents::ExportAgent}. # @!attribute [rw] agent_uri # @return [String] # The URI to a file containing the exported agent. This field is populated # only if +agent_uri+ is specified in +ExportAgentRequest+. # @!attribute [rw] agent_content # @return [String] # The exported agent. # # Example for how to export an agent to a zip file via a command line: # # curl \ # 'https://dialogflow.googleapis.com/v2/projects/<project_name>/agent:export'\ # -X POST \ # -H 'Authorization: Bearer '$(gcloud auth print-access-token) \ # -H 'Accept: application/json' \ # -H 'Content-Type: application/json' \ # --compressed \ # --data-binary '{}' \ # | grep agentContent | sed -e 's/.*"agentContent": "\([^"]*\)".*/\1/' \ # | base64 --decode > <agent zip file> class ExportAgentResponse; end # The request message for {Google::Cloud::Dialogflow::V2::Agents::ImportAgent Agents::ImportAgent}. # @!attribute [rw] parent # @return [String] # Required. The project that the agent to import is associated with. # Format: +projects/<Project ID>+. # @!attribute [rw] agent_uri # @return [String] # The URI to a Google Cloud Storage file containing the agent to import. # Note: The URI must start with "gs://". # @!attribute [rw] agent_content # @return [String] # The agent to import. # # Example for how to import an agent via the command line: # # curl \ # 'https://dialogflow.googleapis.com/v2/projects/<project_name>/agent:import\ # -X POST \ # -H 'Authorization: Bearer '$(gcloud auth print-access-token) \ # -H 'Accept: application/json' \ # -H 'Content-Type: application/json' \ # --compressed \ # --data-binary "{ # 'agentContent': '$(cat <agent zip file> | base64 -w 0)' # }" class ImportAgentRequest; end # The request message for {Google::Cloud::Dialogflow::V2::Agents::RestoreAgent Agents::RestoreAgent}. # @!attribute [rw] parent # @return [String] # Required. The project that the agent to restore is associated with. # Format: +projects/<Project ID>+. # @!attribute [rw] agent_uri # @return [String] # The URI to a Google Cloud Storage file containing the agent to restore. # Note: The URI must start with "gs://". # @!attribute [rw] agent_content # @return [String] # The agent to restore. # # Example for how to restore an agent via the command line: # # curl \ # 'https://dialogflow.googleapis.com/v2/projects/<project_name>/agent:restore\ # -X POST \ # -H 'Authorization: Bearer '$(gcloud auth print-access-token) \ # -H 'Accept: application/json' \ # -H 'Content-Type: application/json' \ # --compressed \ # --data-binary "{ # 'agentContent': '$(cat <agent zip file> | base64 -w 0)' # }" \ class RestoreAgentRequest; end end end end end
47.206573
110
0.588463
1c81bd5af0bdac3a168d1223d99c1990f251e570
1,418
require 'spec_helper' RSpec.describe Steps::Check::KindForm do let(:arguments) { { disclosure_check: disclosure_check, kind: kind } } let(:disclosure_check) { instance_double(DisclosureCheck, kind: nil) } let(:kind) { nil } subject { described_class.new(arguments) } describe '.choices' do it 'returns the relevant choices' do expect(described_class.choices).to eq(%w( caution conviction )) end end describe '#save' do it_behaves_like 'a value object form', attribute_name: :kind, example_value: 'caution' context 'when form is valid' do let(:kind) { 'caution' } it 'saves the record' do expect(disclosure_check).to receive(:update).with( kind: 'caution', # Dependent attributes to be reset under_age: nil, caution_type: nil, conviction_type: nil, conviction_subtype: nil, conviction_date: nil ).and_return(true) expect(subject.save).to be(true) end context 'when kind is already the same on the model' do let(:disclosure_check) { instance_double(DisclosureCheck, kind: kind) } let(:kind) { 'conviction' } it 'does not save the record but returns true' do expect(disclosure_check).to_not receive(:update) expect(subject.save).to be(true) end end end end end
26.259259
90
0.624824
b970b6eb9848525bf44d3617744937ba0b95cf20
46
module ColoradoTrails VERSION = "0.1.2" end
11.5
21
0.717391
6af88e881d7820c485f4d9fb81dc0e87c2a1380e
2,291
require 'rspec/core' module RSpec module Interactive class Runner def initialize(args) ::RSpec.world.wants_to_quit = false @options = ::RSpec::Core::ConfigurationOptions.new(args) end def run() begin @options.configure(::RSpec.configuration) return if ::RSpec.world.wants_to_quit ::RSpec.configuration.load_spec_files ensure ::RSpec.world.announce_filters end return ::RSpec.configuration.reporter.exit_early(::RSpec.configuration.failure_exit_code) if ::RSpec.world.wants_to_quit example_groups = ::RSpec.world.ordered_example_groups examples_count = ::RSpec.world.example_count(example_groups) exit_code = ::RSpec.configuration.reporter.report(examples_count) do |reporter| ::RSpec.configuration.with_suite_hooks do if examples_count == 0 && ::RSpec.configuration.fail_if_no_examples return ::RSpec.configuration.failure_exit_code end group_results = example_groups.map do |example_group| example_group.run(reporter) end success = group_results.all? exit_code = success ? 0 : 1 if ::RSpec.world.non_example_failure success = false exit_code = ::RSpec.configuration.failure_exit_code end persist_example_statuses exit_code end end if exit_code != 0 && ::RSpec.configuration.example_status_persistence_file_path ::RSpec.configuration.output_stream.puts "Rerun failures by executing the previous command with --only-failures or --next-failure." ::RSpec.configuration.output_stream.puts end exit_code end def quit ::RSpec.world.wants_to_quit = true end def persist_example_statuses return if ::RSpec.configuration.dry_run return unless (path = ::RSpec.configuration.example_status_persistence_file_path) ::RSpec::Core::ExampleStatusPersister.persist(::RSpec.world.all_examples, path) rescue SystemCallError => e ::RSpec.configuration.error_stream.puts "warning: failed to write results to #{path}" end end end end
32.728571
141
0.647752
e8dcf684f46abecbb4f75e38bd659ca4c8e433d5
643
# # Use bundler to load dependencies # GEMFILE_EXTENSIONS = [ '.local', '' ] unless ENV['BUNDLE_GEMFILE'] require 'pathname' msfenv_real_pathname = Pathname.new(__FILE__).realpath root = msfenv_real_pathname.parent.parent GEMFILE_EXTENSIONS.each do |extension| extension_pathname = root.join("Gemfile#{extension}") if extension_pathname.readable? ENV['BUNDLE_GEMFILE'] ||= extension_pathname.to_path break end end end begin require 'bundler/setup' rescue ::LoadError $stderr.puts "[*] Metasploit requires the Bundler gem to be installed" $stderr.puts " $ gem install bundler" exit(0) end
19.484848
72
0.713841
397c01d89521667975409636f4b02cb467b92900
1,823
class TreeBuilderDatastores < TreeBuilder has_kids_for Hash, [:x_get_tree_hash_kids] def initialize(name, type, sandbox, build = true, root = nil) @root = root @data = Storage.all.inject({}) { |h, st| h[st.id] = st; h } super(name, type, sandbox, build) end private def tree_init_options(_tree_name) {:full_ids => false, :add_root => false, :lazy => false} end def set_locals_for_render locals = super locals.merge!(:checkboxes => true, :onselect => "miqOnCheckCUFilters", :highlight_changes => true, :check_url => "/ops/cu_collection_field_changed/") end def root_options [] end def x_get_tree_roots(count_only = false, _options) nodes = @root.map do |node| children = [] if @data[node[:id]].hosts.present? children = @data[node[:id]].hosts.sort_by { |host| host.name.try(:downcase) }.map do |kid| {:name => kid.name} end end { :id => node[:id].to_s, :text => "<b>#{node[:name]}</b> [#{node[:location]}]".html_safe, :image => '100/storage.png', :tip => "#{node[:name]} [#{node[:location]}]", :select => node[:capture] == true, :cfmeNoClick => true, :children => children } end count_only_or_objects(count_only, nodes) end def x_get_tree_hash_kids(parent, count_only) nodes = parent[:children].map do |node| { :id => node[:name], :text => node[:name], :image => '100/host.png', :tip => node[:name], :hideCheckbox => true, :cfmeNoClick => true, :children => [] } end count_only_or_objects(count_only, nodes) end end
29.403226
98
0.536478
1100445352f17f391c994be0a74c1cb978c52167
3,463
require 'alchemy/shell' namespace :alchemy do namespace :tidy do desc "Tidy up Alchemy database." task :up do Rake::Task['alchemy:tidy:cells'].invoke Rake::Task['alchemy:tidy:element_positions'].invoke Rake::Task['alchemy:tidy:content_positions'].invoke end desc "Creates missing cells for pages." task :cells => :environment do if !File.exist? Rails.root.join('config/alchemy/cells.yml') puts "No page cell definitions found." else cells = Alchemy::Cell.definitions page_layouts = Alchemy::PageLayout.all if cells && page_layouts Alchemy::Tidy.create_missing_cells(page_layouts, cells) else puts "No page layouts or cell definitions found." end end end desc "Fixes element positions." task :element_positions => [:environment] do Alchemy::Tidy.update_element_positions end desc "Fixes content positions." task :content_positions => [:environment] do Alchemy::Tidy.update_content_positions end end end module Alchemy class Tidy extend Shell def self.create_missing_cells(page_layouts, cells) page_layouts.each do |layout| next if layout['cells'].blank? cells_for_layout = cells.select { |cell| layout['cells'].include? cell['name'] } Alchemy::Page.where(page_layout: layout['name']).each do |page| cells_for_layout.each do |cell_for_layout| cell = Alchemy::Cell.find_or_initialize_by(name: cell_for_layout['name'], page_id: page.id) cell.elements << page.elements.select { |element| cell_for_layout['elements'].include?(element.name) } if cell.new_record? cell.save log "Creating cell #{cell.name} for page #{page.name}" else log "Cell #{cell.name} for page #{page.name} already present", :skip end end end end end def self.update_element_positions Alchemy::Page.all.each do |page| if page.elements.any? puts "\n## Updating element positions of page `#{page.name}`" end page.elements.group_by(&:cell_id).each do |cell_id, elements| elements.each_with_index do |element, idx| position = idx + 1 if element.position != position log "Updating position for element ##{element.id} to #{position}" element.update_column(:position, position) else log "Position for element ##{element.id} is already correct (#{position})", :skip end end end end end def self.update_content_positions Alchemy::Element.all.each do |element| if element.contents.any? puts "\n## Updating content positions of element `#{element.name}`" end element.contents.group_by(&:essence_type).each do |essence_type, contents| puts "-> Contents of type `#{essence_type}`" contents.each_with_index do |content, idx| position = idx + 1 if content.position != position log "Updating position for content ##{content.id} to #{position}" content.update_column(:position, position) else log "Position for content ##{content.id} is already correct (#{position})", :skip end end end end end end end
33.621359
114
0.61132
28cf55f74861434d48f836abf89c65bef5f9f611
3,449
# frozen_string_literal: true # # A Namespace::TraversalHierarchy is the collection of namespaces that descend # from a root Namespace as defined by the Namespace#traversal_ids attributes. # # This class provides operations to be performed on the hierarchy itself, # rather than individual namespaces. # # This includes methods for synchronizing traversal_ids attributes to a correct # state. We use recursive methods to determine the correct state so we don't # have to depend on the integrity of the traversal_ids attribute values # themselves. # class Namespace class TraversalHierarchy attr_accessor :root def self.for_namespace(namespace) new(recursive_root_ancestor(namespace)) end def initialize(root) raise StandardError.new('Must specify a root node') if root.parent_id @root = root end # Update all traversal_ids in the current namespace hierarchy. def sync_traversal_ids! # An issue in Rails since 2013 prevents this kind of join based update in # ActiveRecord. https://github.com/rails/rails/issues/13496 # Ideally it would be: # `incorrect_traversal_ids.update_all('traversal_ids = cte.traversal_ids')` sql = """ UPDATE namespaces SET traversal_ids = cte.traversal_ids FROM (#{recursive_traversal_ids(lock: true)}) as cte WHERE namespaces.id = cte.id AND namespaces.traversal_ids <> cte.traversal_ids """ Namespace.connection.exec_query(sql) rescue ActiveRecord::Deadlocked db_deadlock_counter.increment(source: 'Namespace#sync_traversal_ids!') raise end # Identify all incorrect traversal_ids in the current namespace hierarchy. def incorrect_traversal_ids(lock: false) Namespace .joins("INNER JOIN (#{recursive_traversal_ids(lock: lock)}) as cte ON namespaces.id = cte.id") .where('namespaces.traversal_ids <> cte.traversal_ids') end private # Determine traversal_ids for the namespace hierarchy using recursive methods. # Generate a collection of [id, traversal_ids] rows. # # Note that the traversal_ids represent a calculated traversal path for the # namespace and not the value stored within the traversal_ids attribute. # # Optionally locked with FOR UPDATE to ensure isolation between concurrent # updates of the heirarchy. def recursive_traversal_ids(lock: false) root_id = Integer(@root.id) sql = <<~SQL WITH RECURSIVE cte(id, traversal_ids, cycle) AS ( VALUES(#{root_id}, ARRAY[#{root_id}], false) UNION ALL SELECT n.id, cte.traversal_ids || n.id, n.id = ANY(cte.traversal_ids) FROM namespaces n, cte WHERE n.parent_id = cte.id AND NOT cycle ) SELECT id, traversal_ids FROM cte SQL sql += ' FOR UPDATE' if lock sql end # This is essentially Namespace#root_ancestor which will soon be rewritten # to use traversal_ids. We replicate here as a reliable way to find the # root using recursive methods. def self.recursive_root_ancestor(namespace) Gitlab::ObjectHierarchy .new(Namespace.where(id: namespace)) .base_and_ancestors .reorder(nil) .find_by(parent_id: nil) end def db_deadlock_counter Gitlab::Metrics.counter(:db_deadlock, 'Counts the times we have deadlocked in the database') end end end
34.838384
102
0.698463
ff640d9927644bd41cadb5a3d9df8f45e8ea8dda
634
# frozen_string_literal: true module MasterfilesApp class RmtDeliveryDestinationRepo < BaseRepo build_for_select :rmt_delivery_destinations, label: :delivery_destination_code, value: :id, order_by: :delivery_destination_code build_inactive_select :rmt_delivery_destinations, label: :delivery_destination_code, value: :id, order_by: :delivery_destination_code crud_calls_for :rmt_delivery_destinations, name: :rmt_delivery_destination, wrapper: RmtDeliveryDestination end end
37.294118
111
0.65142
18a7f021fdd10cd75c073c0a561bac64b5937412
1,872
require 'rubygems' require 'sinatra' require 'sinatra/reloader' def new_user new_user = File.open "./public/users_list.txt","a" if @barber == "Не важно" new_user.write "Клиент #{@new_user_name} записан на #{@new_user_datetime}. К любому специалисту. Телефон для связи #{@new_user_phone}. \n" else new_user.write "Клиент #{@new_user_name} записан на #{@new_user_datetime} к специалисту #{@barber}. Телефон для связи #{@new_user_phone}. \n" end new_user.close end configure do enable :sessions end helpers do def username session[:identity] ? 'Вы вошли, как ' + session[:identity] : 'Войдите в кабинет' end end before '/cabinet' do unless session[:identity] session[:previous_url] = request.path @error = 'Для входа в кабинет необходимо авторизоваться' halt erb(:login_form) end end get '/' do erb :index end get '/visit' do erb :visit end post '/visit' do @new_user_name = params[:new_user_name] @new_user_phone = params[:new_user_phone] @new_user_datetime = params[:new_user_datetime] @barber = params[:barber] new_user erb "Уважаемый #{@new_user_name}, мы будем ждать Вас #{@new_user_datetime}!" end get '/login/form' do erb :login_form end post '/login/attempt' do @login = params[:username] @password = params[:user_password] if @login == 'admin' && @password == 'secret' session[:identity] = params[:username] new_user = File.open "./public/users_list.txt","r" new_user.read erb :cabinet else @message = " Доступ закрыт. Введите правильные логин и пароль." erb :login_form end end get '/cabinet' do erb :cabinet end get '/cabinet' do new_user.read end get '/logout' do session.delete(:identity) redirect to '/' end
17.333333
144
0.644231
ab9b7c602b5dc728f206b05a2f8edac8face4b50
2,811
module API class GroupMembers < Grape::API before { authenticate! } resource :groups do # Get a list of group members viewable by the authenticated user. # # Example Request: # GET /groups/:id/members get ":id/members" do group = find_group(params[:id]) users = group.users present users, with: Entities::GroupMember, group: group end # Add a user to the list of group members # # Parameters: # id (required) - group id # user_id (required) - the users id # access_level (required) - Project access level # Example Request: # POST /groups/:id/members post ":id/members" do group = find_group(params[:id]) authorize! :admin_group, group required_attributes! [:user_id, :access_level] unless validate_access_level?(params[:access_level]) render_api_error!("Wrong access level", 422) end if group.group_members.find_by(user_id: params[:user_id]) render_api_error!("Already exists", 409) end group.add_users([params[:user_id]], params[:access_level], current_user) member = group.group_members.find_by(user_id: params[:user_id]) present member.user, with: Entities::GroupMember, group: group end # Update group member # # Parameters: # id (required) - The ID of a group # user_id (required) - The ID of a group member # access_level (required) - Project access level # Example Request: # PUT /groups/:id/members/:user_id put ':id/members/:user_id' do group = find_group(params[:id]) authorize! :admin_group, group required_attributes! [:access_level] group_member = group.group_members.find_by(user_id: params[:user_id]) not_found!('User can not be found') if group_member.nil? if group_member.update_attributes(access_level: params[:access_level]) @member = group_member.user present @member, with: Entities::GroupMember, group: group else handle_member_errors group_member.errors end end # Remove member. # # Parameters: # id (required) - group id # user_id (required) - the users id # # Example Request: # DELETE /groups/:id/members/:user_id delete ":id/members/:user_id" do group = find_group(params[:id]) authorize! :admin_group, group member = group.group_members.find_by(user_id: params[:user_id]) if member.nil? render_api_error!("404 Not Found - user_id:#{params[:user_id]} not a member of group #{group.name}",404) else member.destroy end end end end end
31.943182
114
0.611526
03b058edcf76991549c982107ee88d5be8090510
5,481
# # Author:: Stuart Preston (<[email protected]>) # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../powershell" require_relative "../pwsh" # The powershell_exec mixin provides in-process access to the PowerShell engine. # # powershell_exec is initialized with a string that should be set to the script # to run and also takes an optional interpreter argument which must be either # :powershell (Windows PowerShell which is the default) or :pwsh (PowerShell # Core). It will return a Chef::PowerShell object that provides 4 methods: # # .result - returns a hash representing the results returned by executing the # PowerShell script block # .errors - this is an array of string containing any messages written to the # PowerShell error stream during execution # .error? - returns true if there were error messages written to the PowerShell # error stream during execution # .error! - raise Chef::PowerShell::CommandFailed if there was an error # # Some examples of usage: # # > powershell_exec("(Get-Item c:\\windows\\system32\\w32time.dll).VersionInfo" # ).result["FileVersion"] # => "10.0.14393.0 (rs1_release.160715-1616)" # # > powershell_exec("(get-process ruby).Mainmodule").result["FileName"] # => C:\\opscode\\chef\\embedded\\bin\\ruby.exe" # # > powershell_exec("$a = $true; $a").result # => true # # > powershell_exec("$PSVersionTable", :pwsh).result["PSEdition"] # => "Core" # # > powershell_exec("not-found").errors # => ["ObjectNotFound: (not-found:String) [], CommandNotFoundException: The # term 'not-found' is not recognized as the name of a cmdlet, function, script # file, or operable program. Check the spelling of the name, or if a path was # included, verify that the path is correct and try again. (at <ScriptBlock>, # <No file>: line 1)"] # # > powershell_exec("not-found").error? # => true # # > powershell_exec("get-item c:\\notfound -erroraction stop") # WIN32OLERuntimeError: (in OLE method `ExecuteScript': ) # OLE error code:80131501 in System.Management.Automation # The running command stopped because the preference variable # "ErrorActionPreference" or common parameter is set to Stop: Cannot find # path 'C:\notfound' because it does not exist. # # *Why use this and not powershell_out?* Startup time to invoke the PowerShell # engine is much faster (over 7X faster in tests) than writing the PowerShell # to disk, shelling out to powershell.exe and retrieving the .stdout or .stderr # methods afterwards. Additionally we are able to have a higher fidelity # conversation with PowerShell because we are now working with the objects that # are returned by the script, rather than having to parse the stdout of # powershell.exe to get a result. # # *How does this work?* In .NET terms, when you run a PowerShell script block # through the engine, behind the scenes you get a Collection<PSObject> returned # and simply we are serializing this, adding any errors that were generated to # a custom JSON string transferred in memory to Ruby. The easiest way to # develop for this approach is to imagine that the last thing that happens in # your PowerShell script block is "ConvertTo-Json". That's exactly what we are # doing here behind the scenes. # # There are a handful of current limitations with this approach: # - Windows UAC elevation is controlled by the token assigned to the account # that Ruby.exe is running under. # - Terminating errors will result in a WIN32OLERuntimeError and typically are # handled as an exception. # - There are no return/error codes, as we are not shelling out to # powershell.exe but calling a method inline, no errors codes are returned. # - There is no settable timeout on powershell_exec method execution. # - It is not possible to impersonate another user running powershell, the # credentials of the user running Chef Client are used. # class Chef module Mixin module PowershellExec # Run a command under PowerShell via a managed (.NET) API. # # Requires: .NET Framework 4.0 or higher on the target machine. # # @param script [String] script to run # @param interpreter [Symbol] the interpreter type, `:powershell` or `:pwsh` # @return [Chef::PowerShell] output def powershell_exec(script, interpreter = :powershell) case interpreter when :powershell Chef::PowerShell.new(script) when :pwsh Chef::Pwsh.new(script) else raise ArgumentError, "Expected interpreter of :powershell or :pwsh" end end # The same as the #powershell_exec method except this will raise # Chef::PowerShell::CommandFailed if the command fails def powershell_exec!(script, interpreter = :powershell) cmd = powershell_exec(script, interpreter) cmd.error! cmd end end end end
43.15748
82
0.722861
8766e0f96e99d7d7c5bf75e0b547a3775e7b6b4a
12,222
class Employers::CensusEmployeesController < ApplicationController before_action :find_employer before_action :find_census_employee, only: [:edit, :update, :show, :delink, :terminate, :rehire, :benefit_group, :cobra ,:cobra_reinstate, :confirm_effective_date] before_action :updateable?, except: [:edit, :show, :update, :benefit_group] layout "two_column" def new @census_employee = build_census_employee @no_ssn = @benefit_sponsorship.is_no_ssn_enabled flash[:notice] = "SSN requirement is currently disabled. This means you are not required to input an SSN when adding new employees to your roster at this time." if @no_ssn end def create @census_employee = CensusEmployee.new(census_employee_params.merge!({ benefit_sponsorship_id: @benefit_sponsorship.id, benefit_sponsors_employer_profile_id: @employer_profile.id, active_benefit_group_assignment: benefit_group_id, renewal_benefit_group_assignment: renewal_benefit_group_id, no_ssn_allowed: @benefit_sponsorship.is_no_ssn_enabled })) # @census_employee.assign_benefit_packages(benefit_group_id: benefit_group_id, renewal_benefit_group_id: renewal_benefit_group_id) if @census_employee.save flash[:notice] = "Census Employee is successfully created." if @census_employee.active_benefit_group_assignment.blank? flash[:notice] = "Your employee was successfully added to your roster." end redirect_to benefit_sponsors.profiles_employers_employer_profile_path(@employer_profile, tab: 'employees') else @reload = true render action: "new" end end def edit authorize @census_employee, :show? @census_employee.build_address unless @census_employee.address.present? @census_employee.build_email unless @census_employee.email.present? @census_employee.benefit_group_assignments.build unless @census_employee.benefit_group_assignments.present? @no_ssn = @census_employee.no_ssn_allowed end def update authorize @employer_profile, :updateable? @status = params[:status] # @census_employee.assign_benefit_packages(benefit_group_id: benefit_group_id, renewal_benefit_group_id: renewal_benefit_group_id) @census_employee.attributes = census_employee_params.merge!({ active_benefit_group_assignment: benefit_group_id, renewal_benefit_group_assignment: renewal_benefit_group_id, no_ssn_allowed: @census_employee.no_ssn_allowed || @benefit_sponsorship.is_no_ssn_enabled }) destroyed_dependent_ids = census_employee_params[:census_dependents_attributes].delete_if{|k,v| v.has_key?("_destroy") }.values.map{|x| x[:id]} if census_employee_params[:census_dependents_attributes] authorize @census_employee, :update? if @census_employee.attributes[:email].present? && @census_employee.attributes[:email][:address].blank? e = @census_employee.email e.destroy @census_employee.reload end @census_employee.unset(:encrypted_ssn) if (@census_employee.no_ssn_allowed || @benefit_sponsorship.is_no_ssn_enabled) && @census_employee.ssn.blank? if @census_employee.save if destroyed_dependent_ids.present? destroyed_dependent_ids.each do |g| census_dependent = @census_employee.census_dependents.find(g) census_dependent.delete end end flash[:notice] = "Census Employee is successfully updated." if benefit_group_id.blank? flash[:notice] += " Note: new employee cannot enroll on #{site_short_name} until they are assigned a benefit group." end redirect_to employers_employer_profile_census_employee_path(@employer_profile.id, @census_employee.id, tab: 'employees', status: params[:status]) else flash[:error] = @census_employee.errors.full_messages redirect_to employers_employer_profile_census_employee_path(@employer_profile.id, @census_employee.id, tab: 'employees', status: params[:status]) end #else #flash[:error] = "Please select Benefit Group." #render action: "edit" #end end def terminate authorize EmployerProfile, :updateable? status = params[:status] termination_date = params["termination_date"] if termination_date.present? termination_date = DateTime.strptime(termination_date, '%m/%d/%Y').try(:to_date) if termination_date >= (TimeKeeper.date_of_record - 60.days) @fa = @census_employee.terminate_employment(termination_date) end end respond_to do |format| format.js { if termination_date.present? && @fa flash[:notice] = "Successfully terminated Census Employee." else flash[:error] = "Census Employee could not be terminated: Termination date must be within the past 60 days." end } format.all { flash[:notice] = "Successfully terminated Census Employee." } end flash.keep(:error) flash.keep(:notice) render js: "window.location = '#{employers_employer_profile_census_employee_path(@employer_profile.id, @census_employee.id, status: status)}'" end def rehire authorize EmployerProfile, :updateable? status = params[:status] rehiring_date = params["rehiring_date"] if rehiring_date.present? rehiring_date = DateTime.strptime(rehiring_date, '%m/%d/%Y').try(:to_date) else rehiring_date = "" end @rehiring_date = rehiring_date if @rehiring_date.present? && @rehiring_date > @census_employee.employment_terminated_on new_census_employee = @census_employee.replicate_for_rehire if new_census_employee.present? # not an active family, then it is ready for rehire.# new_census_employee.hired_on = @rehiring_date if new_census_employee.valid? && @census_employee.valid? @census_employee.save new_census_employee.save # for new_census_employee new_census_employee.build_address if new_census_employee.address.blank? @census_employee = new_census_employee flash[:notice] = "Successfully rehired Census Employee." else flash[:error] = "Error during rehire." end else # active family, dont replicate for rehire, just return error flash[:error] = "Census Employee is already active." end elsif @rehiring_date.blank? flash[:error] = "Please enter rehiring date." else flash[:error] = "Rehiring date can't occur before terminated date." end flash.keep(:error) flash.keep(:notice) render js: "window.location = '#{employers_employer_profile_path(@employer_profile.id, :tab=>'employees', status: params[:status])}'" end def cobra cobra_date = params["cobra_date"] if cobra_date.present? @cobra_date = DateTime.strptime(cobra_date, '%m/%d/%Y').try(:to_date) else @cobra_date = "" end if @cobra_date.present? && @census_employee.can_elect_cobra? if @census_employee.update_for_cobra(@cobra_date, current_user) flash[:notice] = "Successfully update Census Employee." else flash[:error] = "COBRA cannot be initiated for this employee with the effective date entered. Please contact #{site_short_name} at #{contact_center_phone_number} for further assistance." end else flash[:error] = "Please enter cobra date." end end def confirm_effective_date confirmation_type = params[:type] render "#{confirmation_type}_effective_date" end def cobra_reinstate if @census_employee.reinstate_eligibility! flash[:notice] = "Successfully update Census Employee." else flash[:error] = "Unable to update Census Employee." end end def show authorize @census_employee, :show? @family = @census_employee.employee_role.person.primary_family if @census_employee.employee_role.present? @status = params[:status] || '' @no_ssn = @census_employee.no_ssn_allowed || false @hbx_enrollments = @census_employee.enrollments_for_display if @census_employee.no_ssn_allowed && !@benefit_sponsorship.is_no_ssn_enabled && @census_employee.encrypted_ssn.nil? flash[:notice] = "This employee does not have an SSN because he/she was created at a time when an SSN was not required." end end def delink employee_role = @census_employee.employee_role if employee_role.present? employee_role.census_employee_id = nil user = employee_role.person.user user.roles.delete("employee") end benefit_group_assignment = @census_employee.benefit_group_assignments.last hbx_enrollment = benefit_group_assignment.hbx_enrollment benefit_group_assignment.delink_coverage @census_employee.delink_employee_role if @census_employee.valid? user.try(:save) employee_role.try(:save) benefit_group_assignment.save hbx_enrollment.destroy @census_employee.save flash[:notice] = "Successfully delinked census employee." redirect_to employers_employer_profile_path(@employer_profile) else flash[:alert] = "Delink census employee failure." redirect_to employers_employer_profile_path(@employer_profile) end end def benefit_group @census_employee.benefit_group_assignments.build unless @census_employee.benefit_group_assignments.present? end def change_expected_selection if params[:ids] begin census_employees = CensusEmployee.find(params[:ids]) census_employees.each do |census_employee| census_employee.update_attributes(:expected_selection=>params[:expected_selection].downcase) end render json: { status: 200, message: 'successfully submitted the selected Employees participation status' } rescue => e render json: { status: 500, message: 'An error occured while submitting employees participation status' } end end end private def updateable? authorize ::EmployerProfile, :updateable? end def benefit_group_id params[:census_employee][:benefit_group_assignments_attributes]["0"][:benefit_group_id] rescue nil end def renewal_benefit_group_id params[:census_employee][:renewal_benefit_group_assignments][:benefit_group_id] rescue nil end def census_employee_params =begin [:dob, :hired_on].each do |attr| if params[:census_employee][attr].present? params[:census_employee][attr] = DateTime.strptime(params[:census_employee][attr].to_s, '%m/%d/%Y').try(:to_date) end end census_dependents_attributes = params[:census_employee][:census_dependents_attributes] if census_dependents_attributes.present? census_dependents_attributes.each do |id, dependent_params| if census_dependents_attributes[id][:dob].present? params[:census_employee][:census_dependents_attributes][id][:dob] = DateTime.strptime(dependent_params[:dob].to_s, '%m/%d/%Y').try(:to_date) end end end =end params.require(:census_employee).permit(:id, :first_name, :middle_name, :last_name, :name_sfx, :dob, :ssn, :gender, :hired_on, :employment_terminated_on, :is_business_owner, :existing_cobra, :cobra_begin_date, :address_attributes => [ :id, :kind, :address_1, :address_2, :city, :state, :zip ], :email_attributes => [:id, :kind, :address], :census_dependents_attributes => [ :id, :first_name, :last_name, :middle_name, :name_sfx, :dob, :gender, :employee_relationship, :_destroy, :ssn ] ) end def find_employer @employer_profile = BenefitSponsors::Organizations::Organization.all.where(:"profiles._id" => BSON::ObjectId.from_string(params[:employer_profile_id])).first.employer_profile @benefit_sponsorship = @employer_profile.parent.active_benefit_sponsorship end def find_census_employee id = params[:id] || params[:census_employee_id] @census_employee = CensusEmployee.find(id) end def build_census_employee @census_employee = CensusEmployee.new @census_employee.build_address @census_employee.build_email @census_employee.benefit_group_assignments.build @census_employee.benefit_sponsors_employer_profile_id = @employer_profile.id @census_employee end private end
39.681818
204
0.728195
1c12d313c8aa4bcd519eac0fc4795985dd8fab49
3,899
# # Copyright:: Copyright (c) 2017 GitLab Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require_relative '../helpers/settings_helper.rb' module Gitlab extend(Mixlib::Config) extend(SettingsHelper) ## Attributes that don't get passed to the node node nil roles nil edition :ce git_data_dirs ConfigMash.new ## Roles role('application').use { ApplicationRole } role('redis_sentinel').use { RedisSentinelRole } role('redis_master').use { RedisMasterRole } role('redis_slave') role('geo_primary', manage_services: false).use { GeoPrimaryRole } role('geo_secondary', manage_services: false).use { GeoSecondaryRole } role('postgres').use { PostgresRole } role('pgbouncer').use { PgbouncerRole } role('consul').use { ConsulRole } ## Attributes directly on the node attribute('registry', priority: 20).use { Registry } attribute('repmgr') attribute('repmgrd') attribute('consul') attribute('gitaly').use { Gitaly } attribute('mattermost', priority: 30).use { GitlabMattermost } # Mattermost checks if GitLab is enabled on the same box attribute('letsencrypt') ## Attributes under node['gitlab'] attribute_block 'gitlab' do # EE attributes ee_attribute('sidekiq_cluster', priority: 20).use { SidekiqCluster } ee_attribute('geo_postgresql', priority: 20).use { GeoPostgresql } ee_attribute('geo_secondary') ee_attribute('geo_logcursor') ee_attribute('sentinel').use { Sentinel } # Base GitLab attributes attribute('gitlab_shell', priority: 10).use { GitlabShell } # Parse shell before rails for data dir settings attribute('gitlab_rails', priority: 15).use { GitlabRails } # Parse rails first as others may depend on it attribute('gitlab_workhorse', priority: 20).use { GitlabWorkhorse } attribute('logging', priority: 20).use { Logging } attribute('redis', priority: 20).use { Redis } attribute('postgresql', priority: 20).use { Postgresql } attribute('unicorn', priority: 20).use { Unicorn } attribute('mailroom', priority: 20).use { IncomingEmail } attribute('gitlab_pages', priority: 20).use { GitlabPages } attribute('prometheus', priority: 20).use { Prometheus } attribute('storage_check', priority: 30).use { StorageCheck } attribute('nginx', priority: 40).use { Nginx } # Parse nginx last so all external_url are parsed before it attribute('external_url', default: nil) attribute('registry_external_url', default: nil) attribute('mattermost_external_url', default: nil) attribute('pages_external_url', default: nil) attribute('runtime_dir', default: nil) attribute('bootstrap') attribute('omnibus_gitconfig') attribute('manage_accounts') attribute('manage_storage_directories') attribute('user') attribute('gitlab_ci') attribute('sidekiq') attribute('mattermost_nginx') attribute('pages_nginx') attribute('registry_nginx') attribute('remote_syslog') attribute('logrotate') attribute('high_availability') attribute('web_server') attribute('node_exporter') attribute('redis_exporter') attribute('postgres_exporter') attribute('gitlab_monitor') attribute('prometheus_monitoring') attribute('pgbouncer') end end
39.383838
121
0.700692
1c58e1353af4ac2eec9bd49db59c98ded2c67c4f
323
class FileUploader < CarrierWave::Uploader::Base storage :file def store_dir "uploads/#{model.class.to_s.underscore}_#{mounted_as}" end def extension_white_list %w(doc docx xls xlsx ppt htm html txt zip rar gz bz2) end def filename "#{cache_id}.#{file.extension}" if original_filename end end
19
58
0.712074
1aa654a5ac61f888e3ed96672712f8354c69e4c1
1,777
class TopicUpdator def initialize(topic, update_topics_with_links = false) @topic = topic @update_topics_with_links = update_topics_with_links @original_content = topic.content end def update(args) args[:slug] = Topic::ContentSlugGenerator.new(args[:content]).generate if args[:content].present? && args[:ancestry].nil? Topic.transaction do topic.update!(args) create_new_topics_from_links! update_topics_with_links! if update_topics_with_links end true rescue ActiveRecord::RecordInvalid => e Rails.logger.error("Error updating topic #{topic.inspect}\nparams: #{args.inspect}\n#{e.message}\n#{e.backtrace.join("\n")}") false end private attr_reader :topic, :update_topics_with_links, :original_content def create_new_topics_from_links! topic.content.split(/\[\[([^\[]*)\]\]/).each_with_index do |content, index| link_to_other_user = content.match(/^([^\s:]+):(.*)/) create_new_topic!(content) if !link_to_other_user && link_to_topic?(index) && !root_topic_exists?(content) end end def update_topics_with_links! orig_cont = Regexp.escape(original_content) cont = topic.content Topic. where.not(id: topic.id). where(user_id: topic.user_id). where("content like ?", "%[[#{orig_cont}]]%").find_each do |t| t.update!(content: t.content.gsub(/\[\[#{orig_cont}\]\]/, "[[#{cont}]]")) end end def create_new_topic!(content) Topic.create!(content: content, ancestry: nil, user_id: topic.user_id) end def root_topic_exists?(content) slug = Topic::ContentSlugGenerator.new(content).generate Topic.where(slug: slug, ancestry: nil, user_id: topic.user_id).exists? end def link_to_topic?(index) index % 2 == 1 end end
32.309091
129
0.687676
7a23984c39975b939e1d3f970d43eb93f2897ef0
548
module Forms class Dependent < Base attribute :children, Boolean attribute :children_number, Integer validates :children, inclusion: { in: [true, false] } validates :children_number, presence: true, numericality: { allow_blank: true, less_than: 100 }, if: :children? private def export_params { children: export_children } end def export_children if children.nil? nil elsif children children_number else 0 end end end end
18.896552
97
0.609489
28989acbc41746262aaa272b6457c7597200a7dc
384
require "spec_helper" RSpec.describe "Scraper" do let(:scraper) { Scraper.new("https://player.fm/series/the-ezra-klein-show") } describe "#fetch_episodes" do it "instantiates some episodes" do expect(Episode.all).not_to be_empty end end describe "#write_books" do it "instantiates some books" do expect(Book.all).not_to be_empty end end end
21.333333
79
0.690104
117aa8c4b9481c850febfea967f6d7e36455a305
1,485
Pod::Spec.new do |s| s.name = "LCAuthManager" s.version = "1.0.0" s.summary = "A comprehensive, efficient and easy-to-use rights verification library, including Gesture Password, Touch ID and Face ID." s.description = <<-DESC LCAuthManager has the following advantages: 1. Configurable, providing configuration for gesture password pages and features, such as password length, maximum number of trial and error, and auxiliary operations. 2. Can be combined to combine gesture password and biometric verification, and be customized by the developer. 3. Provide a large number of external interfaces, provide external interfaces for credential storage, and developers can access their own credential storage methods. 4. The project provides a common demo that can help developers integrate quickly. DESC s.homepage = "https://github.com/LennonChin/LCAuthManager" s.license = "MIT" s.author = { "LennonChin" => "[email protected]" } s.social_media_url = "https://blog.coderap.com/" s.platform = :ios, "8.0" s.source = { :git => "https://github.com/LennonChin/LCAuthManager.git", :tag => s.version } s.source_files = "LCAuthManager/LCAuthManager/**/*.{h,m}" s.resource = "LCAuthManager/LCAuthManager/**/*.{xib}", "LCAuthManager/LCAuthManager/Resources/LCAuthManager.bundle" s.requires_arc = true end
67.5
186
0.668687
79447349cd2b55f4e674cdca28101128e3d8422f
129
require 'rails_helper' RSpec.describe Facility, :type => :model do pending "add some examples to (or delete) #{__FILE__}" end
21.5
56
0.728682
628283fb1be810c136f941b020adad606d4da7d4
1,092
require 'bismuth' class ActionExample < Bi::Scene def initialize super add_timer(1000){ Bi::Window.title = "FPS:#{Bi::RunLoop.fps}" } @invaders = 8.times.map{|x| i = Bi::Sprite.new("invader_white.png") i.x = 16 + x*32 i.y = 120 i.angle = 90 i.anchor_x = i.anchor_y = 0.5 add_child i i } t = 5000 # 5sec @actions = [ Bi::Action::move_to(t,20,20){|node| p [node,:move_to] }, Bi::Action::move_by(t,20,20){|node| p [node,:move_by] }, Bi::Action::rotate_by(t,360){|node| p [node,:rotate_by] }, Bi::Action::rotate_to(t,360){|node| p [node,:rotate_to] }, Bi::Action::fade_alpha_to(t,0){|node| p [node,:fade_alpha_to] }, Bi::Action::scale_to(t,2.0,2.0){|node| p [node,:scale_to] }, Bi::Action::remove(){|node| p [node,:remove] }, Bi::Action::wait(t){|node| p [node,:wait] }, ] @actions.each_with_index{|a,i| @invaders[i].run_action a } end end Bi::System.init(debug:true) Bi::Window.make_window(320,240) Bi::RunLoop.instance.run_with_scene ActionExample.new
27.3
70
0.587912
87cf9e61f0346854c69a6edbd210bd042e81be31
260
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :address, :class => 'Customerx::Address' do province "my prov" city_county_district "city county" add_line "123 road" customer_id 1 end end
23.636364
68
0.726923
79687d591043d53bf89fdbf667fe09c853cfda60
972
module IntacctRuby # methods to avoid duplication when creating and updating contact records module ContactsHelper def contact_params(attributes, id, person_type) xml = Builder::XmlMarkup.new name = full_name(attributes) xml.contact do xml.contactname contactname(name, id, person_type) xml.printas full_name(attributes) xml.firstname attributes[:first_name] xml.lastname attributes[:last_name] xml.email1 attributes[:email1] end xml.target! end def contactname(name, id, person_type) # a unique identifier for a contact, to be used for Intacct's # contactname field. Person Type required to ensure that there aren't # duplicates (e.g. a customer and employee w/ ID 1 both named # 'John Smith') "#{name} (#{person_type} \##{id})" end def full_name(attrs = {}) "#{attrs[:first_name]} #{attrs[:last_name]}" end end end
29.454545
75
0.650206
1c4ea6369f60cc754b16497a3be551966e0e875a
636
## ## $Rev: 77 $ ## $Release: 2.6.2 $ ## copyright(c) 2006-2008 kuwata-lab.com all rights reserved. ## unless defined?(TESTDIR) TESTDIR = File.dirname(__FILE__) LIBDIR = TESTDIR == '.' ? '../lib' : File.dirname(TESTDIR) + '/lib' $: << TESTDIR $: << LIBDIR end require 'test/unit' #require 'test/unit/ui/console/testrunner' require 'assert-text-equal' require 'yaml' require 'testutil' require 'erubis' if $0 == __FILE__ require "#{TESTDIR}/test-erubis.rb" require "#{TESTDIR}/test-engines.rb" require "#{TESTDIR}/test-enhancers.rb" require "#{TESTDIR}/test-main.rb" require "#{TESTDIR}/test-users-guide.rb" end
20.516129
70
0.66195
6a6c6c1f2a2845b5aabed44dbbbf50d063b8a875
113
require "#{Rails.root}/lib/base/base_image.rb" class BaseLib def self.img @img = BaseImage.new end end
12.555556
46
0.690265
bbc0e63b808fe47b5abd156b73e6c9ff3def455f
1,730
require File.dirname(__FILE__) + '/../spec_helper' require 'token' describe "A token" do before(:each) do @token = Token.new(:my_type,"my value") end it "should have a name" do @token.should respond_to(:type) @token.name.should == :my_type end it "should have a value" do @token.should respond_to(:value) @token.value.should == "my value" end it "can be coerced to a string" do @token.should respond_to(:to_str) @token.should respond_to(:to_s) @token.to_s.should == "my value" @token.to_str.should == "my value" end it "can be a value = nil and it must respond correctly to nil?" do @token = Token.new(:my_type,nil) @token.should be_nil end it "should have :nil,nil as default values for type,value" do @token = Token.new @token.value.should == nil @token.name.should == :nil end it "should behave correctly when called ==" do t2 = Token.new(:my_type,"my value") @token.should == t2 @token.should == "my value" @token.should == :my_type @token.should == :everything end it "should be matched with a regexp" do (@token =~ /.*value/).should_not be_nil (@token !~ /.*value/).should == false end it "should have a line attribute, which is initialized to -1" do @token.should respond_to(:line) @token.line.should == -1 lambda { @token = Token.new(:my_type, "my value", 5) }.should_not raise_error @token.line.should == 5 end it "should have a char attribute, which is initialized to -1" do @token.should respond_to(:char) @token.char.should == -1 lambda { @token = Token.new(:my_type, "my value", 5,7) }.should_not raise_error @token.char.should == 7 end end
24.366197
83
0.64104